chore(i18n,curriculum): update translations (#43046)
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5895f70df9fc0f352b528e68
|
||||
title: Authentication Strategies
|
||||
title: Estratégias de autenticação
|
||||
challengeType: 2
|
||||
forumTopicId: 301547
|
||||
dashedName: authentication-strategies
|
||||
@@ -8,11 +8,11 @@ dashedName: authentication-strategies
|
||||
|
||||
# --description--
|
||||
|
||||
A strategy is a way of authenticating a user. You can use a strategy for allowing users to authenticate based on locally saved information (if you have them register first) or from a variety of providers such as Google or GitHub. For this project, we will set up a local strategy. To see a list of the hundreds of strategies, visit Passport's site [here](http://passportjs.org/).
|
||||
Uma estratégia é uma maneira de autenticar um usuário. Você pode usar uma estratégia para permitir que os usuários se autentiquem com base em informações salvas localmente (se você os tem registrados primeiro) ou em uma variedade de provedores, como o Google ou o GitHub. Para este projeto, vamos configurar uma estratégia local. Para ver uma lista das centenas de estratégias, visite o site do Passport [aqui](http://passportjs.org/).
|
||||
|
||||
Add `passport-local@~1.0.0` as a dependency and add it to your server as follows: `const LocalStrategy = require('passport-local');`
|
||||
Adicione `passport-local@~1.0.0` como uma dependência e adicione-a ao seu servidor da seguinte forma: `const LocalStrategy = require('passport-local');`
|
||||
|
||||
Now you will have to tell passport to **use** an instantiated LocalStrategy object with a few settings defined. Make sure this (as well as everything from this point on) is encapsulated in the database connection since it relies on it!
|
||||
Agora, você precisará dizer ao passport para **usar** um objeto LocalStrategy instanciado com algumas configurações definidas. Certifique-se de que isso (assim como tudo a partir desse ponto) esteja encapsulado na conexão do banco de dados, já que isso depende dela!
|
||||
|
||||
```js
|
||||
passport.use(new LocalStrategy(
|
||||
@@ -28,17 +28,17 @@ passport.use(new LocalStrategy(
|
||||
));
|
||||
```
|
||||
|
||||
This is defining the process to use when we try to authenticate someone locally. First, it tries to find a user in our database with the username entered, then it checks for the password to match, then finally, if no errors have popped up that we checked for, like an incorrect password, the `user`'s object is returned and they are authenticated.
|
||||
Isso está definindo o processo a ser usado quando tentamos autenticar alguém localmente. Primeiro, há a tentativa de encontrar um usuário em nosso banco de dados com o nome de usuário inserido. Depois, verifica-se a senha correspondente e, em seguida, por fim, se nenhum erro tiver aparecido durante a verificação, como uma senha incorreta, o objeto `user` é retornado e autenticado.
|
||||
|
||||
Many strategies are set up using different settings, but generally it is easy to set it up based on the README in that strategy's repository. A good example of this is the GitHub strategy where we don't need to worry about a username or password because the user will be sent to GitHub's auth page to authenticate. As long as they are logged in and agree then GitHub returns their profile for us to use.
|
||||
Muitas estratégias são configuradas usando definições diferentes, mas geralmente é fácil fazer a configuração com base no README do repositório da estratégia. Um bom exemplo disso é a estratégia do GitHub, onde não precisamos nos preocupar com um nome de usuário ou senha, porque o usuário será enviado para a página de autenticação do GitHub para ser autenticado. Desde que estejam logados e que concordem com isso, o GitHub retorna seu perfil para que o vejamos.
|
||||
|
||||
In the next step, we will set up how to actually call the authentication strategy to validate a user based on form data!
|
||||
Na próxima etapa, vamos configurar como chamar realmente a estratégia de autenticação para validar um usuário com base nos dados do formulário!
|
||||
|
||||
Submit your page when you think you've got it right. If you're running into errors, you can check out the project completed up to this point [here](https://gist.github.com/camperbot/53b495c02b92adeee0aa1bd3f3be8a4b).
|
||||
Envie sua página quando você achar que ela está certa. Se você encontrar erros, pode conferir o projeto concluído até este momento [aqui](https://gist.github.com/camperbot/53b495c02b92adeee0aa1bd3f3be8a4b).
|
||||
|
||||
# --hints--
|
||||
|
||||
Passport-local should be a dependency.
|
||||
Passport-local deve ser uma dependência.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -57,7 +57,7 @@ Passport-local should be a dependency.
|
||||
);
|
||||
```
|
||||
|
||||
Passport-local should be correctly required and setup.
|
||||
Passport-local deve ser solicitado e configurado corretamente.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5895f70df9fc0f352b528e69
|
||||
title: How to Use Passport Strategies
|
||||
title: Usar as estratégias do Passport
|
||||
challengeType: 2
|
||||
forumTopicId: 301555
|
||||
dashedName: how-to-use-passport-strategies
|
||||
@@ -8,21 +8,21 @@ dashedName: how-to-use-passport-strategies
|
||||
|
||||
# --description--
|
||||
|
||||
In the `index.pug` file supplied, there is actually a login form. It has previously been hidden because of the inline JavaScript `if showLogin` with the form indented after it. Before `showLogin` as a variable was never defined, so it never rendered the code block containing the form. Go ahead and on the `res.render` for that page add a new variable to the object `showLogin: true`. When you refresh your page, you should then see the form! This form is set up to **POST** on `/login`, so this is where we should set up to accept the POST and authenticate the user.
|
||||
No arquivo `index.pug` fornecido, existe, na verdade, um formulário de login. Ele foi escondido antes por causa do JavaScript integrado `if showLogin` com o formulário indentado depois disso. Anteriormente, `showLogin` nunca foi definido como uma variável. Por isso, o bloco de código contendo o formulário nunca foi renderizado. No `res.render` daquela página, adicione uma nova variável para o objeto `showLogin: true`. Ao atualizar sua página, você deverá ver o formulário! Este formulário está configurado para o método **POST** em `/login`. Então, é aqui que devemos configurar para aceitar a solicitação de POST e autenticar o usuário.
|
||||
|
||||
For this challenge you should add the route `/login` to accept a POST request. To authenticate on this route, you need to add a middleware to do so before then sending a response. This is done by just passing another argument with the middleware before your `function(req,res)` with your response! The middleware to use is `passport.authenticate('local')`.
|
||||
Para este desafio, você deve adicionar a rota `/login` para aceitar uma solicitação de POST. Para autenticar nessa rota, você precisa adicionar um middleware que faça isso antes de enviar uma resposta. Isso é feito simplesmente passando outro argumento com o middleware antes de sua `function(req,res)` com sua resposta! O middleware a ser usado é o `passport.authenticate('local')`.
|
||||
|
||||
`passport.authenticate` can also take some options as an argument such as: `{ failureRedirect: '/' }` which is incredibly useful, so be sure to add that in as well. The response after using the middleware (which will only be called if the authentication middleware passes) should be to redirect the user to `/profile` and that route should render the view `profile.pug`.
|
||||
`passport.authenticate` também pode aceitar algumas opções como argumento, como: `{ failureRedirect: '/' }`, que é incrivelmente útil. Não se esqueça de acrescentá-lo também. A resposta depois de usar o middleware (que somente será chamado se o middleware de autenticação passar) deve ser redirecionar o usuário para `/profile`. Essa rota deve renderizar a visualização `profile.pug`.
|
||||
|
||||
If the authentication was successful, the user object will be saved in `req.user`.
|
||||
Se a autenticação for bem-sucedida, o objeto do usuário será salvo em `req.user`.
|
||||
|
||||
At this point, if you enter a username and password in the form, it should redirect to the home page `/`, and the console of your server should display `'User {USERNAME} attempted to log in.'`, since we currently cannot login a user who isn't registered.
|
||||
Neste ponto, se você digitar um nome de usuário e uma senha no formulário, ele deve redirecionar para a página inicial `/`. O console do servidor deve exibir `'User {USERNAME} attempted to log in.'`, já que, no momento, não podemos fazer login com um usuário que não está registrado.
|
||||
|
||||
Submit your page when you think you've got it right. If you're running into errors, you can check out the project completed up to this point [here](https://gist.github.com/camperbot/7ad011ac54612ad53188b500c5e99cb9).
|
||||
Envie sua página quando você achar que ela está certa. Se você encontrar erros, pode conferir o projeto concluído até este momento [aqui](https://gist.github.com/camperbot/7ad011ac54612ad53188b500c5e99cb9).
|
||||
|
||||
# --hints--
|
||||
|
||||
All steps should be correctly implemented in the server.js.
|
||||
Todas as etapas devem ser corretamente implementadas no server.js.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -50,7 +50,7 @@ All steps should be correctly implemented in the server.js.
|
||||
);
|
||||
```
|
||||
|
||||
A POST request to /login should correctly redirect to /.
|
||||
Uma solicitação de POST para /login deve redirecionar corretamente para /.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 589a8eb3f9fc0f352b528e72
|
||||
title: Implementation of Social Authentication III
|
||||
title: Implementar a autenticação social III
|
||||
challengeType: 2
|
||||
forumTopicId: 301558
|
||||
dashedName: implementation-of-social-authentication-iii
|
||||
@@ -8,7 +8,7 @@ dashedName: implementation-of-social-authentication-iii
|
||||
|
||||
# --description--
|
||||
|
||||
The final part of the strategy is handling the profile returned from GitHub. We need to load the user's database object if it exists, or create one if it doesn't, and populate the fields from the profile, then return the user's object. GitHub supplies us a unique *id* within each profile which we can use to search with to serialize the user with (already implemented). Below is an example implementation you can use in your project--it goes within the function that is the second argument for the new strategy, right below where `console.log(profile);` currently is:
|
||||
A parte final da estratégia é tratar do perfil retornado do GitHub. Precisamos carregar o banco de dados do usuário, se ele existir, ou criar um, se não existir. Além disso, temos que preencher os campos do perfil e, em seguida, retornar o objeto do usuário. O GitHub nos fornece um *id* único dentro de cada perfil que podemos usar para pesquisar e para serializar o usuário (já implementado). Abaixo, vemos um exemplo de implementação que você pode usar em seu projeto. Ele vai dentro da função, que é o segundo argumento para a nova estratégia, logo abaixo onde `console.log(profile);` está atualmente:
|
||||
|
||||
```js
|
||||
myDataBase.findOneAndUpdate(
|
||||
@@ -38,15 +38,15 @@ myDataBase.findOneAndUpdate(
|
||||
);
|
||||
```
|
||||
|
||||
`findOneAndUpdate` allows you to search for an object and update it. If the object doesn't exist, it will be inserted and made available to the callback function. In this example, we always set `last_login`, increment the `login_count` by `1`, and only populate the majority of the fields when a new object (new user) is inserted. Notice the use of default values. Sometimes a profile returned won't have all the information filled out or the user will keep it private. In this case, you handle it to prevent an error.
|
||||
`findOneAndUpdate` permite pesquisar um objeto e atualizá-lo. Se o objeto não existir, ele será inserido e disponibilizado para a função de callback. Neste exemplo, sempre definimos o `last_login`, incrementamos a `login_count` em `1` e somente preenchemos a maioria dos campos quando um novo objeto (novo usuário) for inserido. Observe o uso dos valores padrão. Às vezes, um perfil retornado não terá todas as informações preenchidas. O usuário também pode mantê-las privadas. Neste caso, você faz o tratamento para evitar um erro.
|
||||
|
||||
You should be able to login to your app now--try it!
|
||||
Você deve poder acessar a aplicação agora - experimente!
|
||||
|
||||
Submit your page when you think you've got it right. If you're running into errors, you can check out the project completed up to this point [here](https://gist.github.com/camperbot/183e968f0e01d81dde015d45ba9d2745).
|
||||
Envie sua página quando você achar que ela está certa. Se você encontrar erros, pode conferir o projeto concluído até este momento [aqui](https://gist.github.com/camperbot/183e968f0e01d81dde015d45ba9d2745).
|
||||
|
||||
# --hints--
|
||||
|
||||
GitHub strategy setup should be complete.
|
||||
A configuração da estratégia do GitHub deve estar concluída.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 58966a17f9fc0f352b528e6d
|
||||
title: Registration of New Users
|
||||
title: Registro de novos usuários
|
||||
challengeType: 2
|
||||
forumTopicId: 301561
|
||||
dashedName: registration-of-new-users
|
||||
@@ -8,11 +8,11 @@ dashedName: registration-of-new-users
|
||||
|
||||
# --description--
|
||||
|
||||
Now we need to allow a new user on our site to register an account. On the `res.render` for the home page add a new variable to the object passed along--`showRegistration: true`. When you refresh your page, you should then see the registration form that was already created in your `index.pug` file! This form is set up to **POST** on `/register`, so this is where we should set up to accept the **POST** and create the user object in the database.
|
||||
Agora, precisamos permitir que um novo usuário em nosso site crie uma conta. Na `res.render` para a página inicial, adicione uma nova variável para o objeto passado, `showRegistration: true`. Ao atualizar sua página, você deve então ver o formulário de registro que já foi criado no arquivo `index.pug`! Este formulário está configurado para o método **POST** em `/register`. Então, é aqui que devemos configurar para aceitar a solicitação de **POST** e criar o objeto de usuário no banco de dados.
|
||||
|
||||
The logic of the registration route should be as follows: Register the new user > Authenticate the new user > Redirect to /profile
|
||||
A lógica da rota de registro deve ser a seguinte: registrar o novo usuário > autenticar o novo usuário > redirecionar para /profile
|
||||
|
||||
The logic of step 1, registering the new user, should be as follows: Query database with a findOne command > if user is returned then it exists and redirect back to home *OR* if user is undefined and no error occurs then 'insertOne' into the database with the username and password, and, as long as no errors occur, call *next* to go to step 2, authenticating the new user, which we've already written the logic for in our POST */login* route.
|
||||
A lógica da etapa 1, registrar o novo usuário, deve ser a seguinte: consultar banco de dados com um comando findOne > se o usuário for retornado, então ele existe e devemos redirecionar de volta para a página inicial *OU*, se o usuário retornar undefined e nenhum erro ocorrer, então 'insertOne' (inserir um) no banco de dados com o nome de usuário e senha. Desde que não haja erros, chamar *next* para ir para a etapa 2, autenticando o novo usuário, para o qual já escrevemos a lógica em nossa solicitação de POST para a rota */login*.
|
||||
|
||||
```js
|
||||
app.route('/register')
|
||||
@@ -47,13 +47,13 @@ app.route('/register')
|
||||
);
|
||||
```
|
||||
|
||||
Submit your page when you think you've got it right. If you're running into errors, you can check out the project completed up to this point [here](https://gist.github.com/camperbot/b230a5b3bbc89b1fa0ce32a2aa7b083e).
|
||||
Envie sua página quando você achar que ela está certa. Se você encontrar erros, pode conferir o projeto concluído até este momento [aqui](https://gist.github.com/camperbot/b230a5b3bbc89b1fa0ce32a2aa7b083e).
|
||||
|
||||
**NOTE:** From this point onwards, issues can arise relating to the use of the *picture-in-picture* browser. If you are using an online IDE which offers a preview of the app within the editor, it is recommended to open this preview in a new tab.
|
||||
**OBSERVAÇÃO:** a partir deste ponto, podem surgir problemas relacionados com o uso do navegador *picture-in-picture*. Se você estiver usando uma IDE on-line que oferece uma pré-visualização do aplicativo dentro do editor, é recomendável abrir esta pré-visualização em uma nova aba.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should register route and display on home.
|
||||
Você deve registrar a rota e exibi-la na página inicial.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -76,7 +76,7 @@ You should register route and display on home.
|
||||
);
|
||||
```
|
||||
|
||||
Registering should work.
|
||||
O registo deve dar certo.
|
||||
|
||||
```js
|
||||
async (getUserInput) => {
|
||||
@@ -104,7 +104,7 @@ async (getUserInput) => {
|
||||
};
|
||||
```
|
||||
|
||||
Login should work.
|
||||
O login deve dar certo.
|
||||
|
||||
```js
|
||||
async (getUserInput) => {
|
||||
@@ -153,7 +153,7 @@ async (getUserInput) => {
|
||||
};
|
||||
```
|
||||
|
||||
Logout should work.
|
||||
O logout deve dar certo.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -171,7 +171,7 @@ Logout should work.
|
||||
);
|
||||
```
|
||||
|
||||
Profile should no longer work after logout.
|
||||
O perfil não deve mais funcionar após o logout.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5895f70cf9fc0f352b528e66
|
||||
title: Serialization of a User Object
|
||||
title: Serialização de um objeto de usuário
|
||||
challengeType: 2
|
||||
forumTopicId: 301563
|
||||
dashedName: serialization-of-a-user-object
|
||||
@@ -8,11 +8,11 @@ dashedName: serialization-of-a-user-object
|
||||
|
||||
# --description--
|
||||
|
||||
Serialization and deserialization are important concepts in regards to authentication. To serialize an object means to convert its contents into a small *key* that can then be deserialized into the original object. This is what allows us to know who has communicated with the server without having to send the authentication data, like the username and password, at each request for a new page.
|
||||
Serialização e desserialização são conceitos importantes no que diz respeito à autenticação. Serializar um objeto significa converter seu conteúdo em uma pequena *chave* que pode ser desserializada no objeto original. Isto é o que nos permite saber quem se comunicou com o servidor sem ter que enviar os dados de autenticação, como o nome de usuário e a senha, em cada solicitação de uma nova página.
|
||||
|
||||
To set this up properly, we need to have a serialize function and a deserialize function. In Passport, we create these with `passport.serializeUser( OURFUNCTION )` and `passport.deserializeUser( OURFUNCTION )`
|
||||
Para configurar isso corretamente, precisamos ter uma função de serialização e uma função de desserialização. No Passport, criamos estas funções com `passport.serializeUser( OURFUNCTION )` e `passport.deserializeUser( OURFUNCTION )`
|
||||
|
||||
The `serializeUser` is called with 2 arguments, the full user object and a callback used by passport. A unique key to identify that user should be returned in the callback, the easiest one to use being the user's `_id` in the object. It should be unique as it is generated by MongoDB. Similarly, `deserializeUser` is called with that key and a callback function for passport as well, but, this time, we have to take that key and return the full user object to the callback. To make a query search for a Mongo `_id`, you will have to create `const ObjectID = require('mongodb').ObjectID;`, and then to use it you call `new ObjectID(THE_ID)`. Be sure to add `mongodb@~3.6.0` as a dependency. You can see this in the examples below:
|
||||
`serializeUser` é chamada com 2 argumentos, o objeto de usuário completo e uma função de callback usada pelo passport. Uma chave única para identificar que o usuário deve ser retornado na função de callback. A mais fácil de usar é o `_id` do usuário no objeto. Ele deve ser único, já que é gerado pelo MongoDB. Da mesma forma, `deserializeUser` também é chamada com essa chave e uma função de callback para o passport. Desta vez, porém, temos de pegar essa chave e devolver o objeto do usuário completo à função de callback. Para fazer uma pesquisa de consulta para um `_id` do Mongo, você precisará criar `const ObjectID = require('mongodb').ObjectID;`. Então, para usá-la, você chama `new ObjectID(THE_ID)`. Certifique-se de adicionar `mongodb@~3.6.0` como uma dependência. Você pode ver isso nos exemplos abaixo:
|
||||
|
||||
```js
|
||||
passport.serializeUser((user, done) => {
|
||||
@@ -26,13 +26,13 @@ passport.deserializeUser((id, done) => {
|
||||
});
|
||||
```
|
||||
|
||||
NOTE: This `deserializeUser` will throw an error until we set up the DB in the next step, so for now comment out the whole block and just call `done(null, null)` in the function `deserializeUser`.
|
||||
OBSERVAÇÃO: `deserializeUser` vai lançar um erro até que tenhamos definido o banco de dados na próxima etapa. Portanto, por enquanto, comente todo o bloco e apenas chame `done(null, null)` na função `deserializeUser`.
|
||||
|
||||
Submit your page when you think you've got it right. If you're running into errors, you can check out the project completed up to this point [here](https://gist.github.com/camperbot/7068a0d09e61ec7424572b366751f048).
|
||||
Envie sua página quando você achar que ela está certa. Se você encontrar erros, pode conferir o projeto concluído até este momento [aqui](https://gist.github.com/camperbot/7068a0d09e61ec7424572b366751f048).
|
||||
|
||||
# --hints--
|
||||
|
||||
You should serialize user function correctly.
|
||||
Você deve serializar a função do usuário corretamente.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -55,7 +55,7 @@ You should serialize user function correctly.
|
||||
);
|
||||
```
|
||||
|
||||
You should deserialize user function correctly.
|
||||
Você deve desserializar a função do usuário corretamente.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -78,7 +78,7 @@ You should deserialize user function correctly.
|
||||
);
|
||||
```
|
||||
|
||||
MongoDB should be a dependency.
|
||||
O MongoDB deve ser uma dependência.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -97,7 +97,7 @@ MongoDB should be a dependency.
|
||||
);
|
||||
```
|
||||
|
||||
Mongodb should be properly required including the ObjectId.
|
||||
O MongoDB deve ser solicitado adequadamente, incluindo o ObjectId.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
Reference in New Issue
Block a user