chore(i18n,curriculum): update translations (#43073)
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 589fc832f9fc0f352b528e78
|
||||
title: Announce New Users
|
||||
title: Anunciar novos usuários
|
||||
challengeType: 2
|
||||
forumTopicId: 301546
|
||||
dashedName: announce-new-users
|
||||
@@ -8,9 +8,9 @@ dashedName: announce-new-users
|
||||
|
||||
# --description--
|
||||
|
||||
Many chat rooms are able to announce when a user connects or disconnects and then display that to all of the connected users in the chat. Seeing as though you already are emitting an event on connect and disconnect, you will just have to modify this event to support such a feature. The most logical way of doing so is sending 3 pieces of data with the event: the name of the user who connected/disconnected, the current user count, and if that name connected or disconnected.
|
||||
Muitas salas de bate-papo são capazes de anunciar quando um usuário conecta ou desconecta e, em seguida, exibem isso para todos os usuários conectados no bate-papo. Considerando que você já está emitindo um evento ao se conectar e desconectar, você só terá que modificar esse evento para dar suporte a esse recurso. A maneira mais lógica de fazer isso é enviando 3 dados com o evento: o nome do usuário que se conectou/desconectou, a contagem de usuário atual e se esse nome conectou ou desconectou.
|
||||
|
||||
Change the event name to `'user'`, and pass an object along containing the fields 'name', 'currentUsers', and 'connected' (to be `true` in case of connection, or `false` for disconnection of the user sent). Be sure to change both 'user count' events and set the disconnect one to send `false` for the field 'connected' instead of `true` like the event emitted on connect.
|
||||
Altere o nome do evento para `'user'` e passe um objeto junto com o evento contendo os campos 'name', 'currentUsers', e 'connected' (para ser `true` quando for enviada uma conexão, ou `false` em caso de desconexão do usuário). Certifique-se de alterar os dois eventos 'user count' e defina o evento de desconexão para que envie `false` para o campo 'connected' em vez de `true` como ocorre quando o evento é emitido ao conectar.
|
||||
|
||||
```js
|
||||
io.emit('user', {
|
||||
@@ -20,9 +20,9 @@ io.emit('user', {
|
||||
});
|
||||
```
|
||||
|
||||
Now your client will have all the necessary information to correctly display the current user count and announce when a user connects or disconnects! To handle this event on the client side we should listen for `'user'`, then update the current user count by using jQuery to change the text of `#num-users` to `'{NUMBER} users online'`, as well as append a `<li>` to the unordered list with id `messages` with `'{NAME} has {joined/left} the chat.'`.
|
||||
Agora, o client terá todas as informações necessárias para exibir corretamente a contagem de usuário atual e anunciar quando um usuário se conectar ou desconectar! Para tratar este evento do lado do client, devemos escutar `'user'`. Em seguida, atualizamos a contagem de usuário atual, usando jQuery para alterar o texto de `#num-users` para `'{NUMBER} users online'`. Também acrescentamos um `<li>` à lista não ordenada com o id `messages` dizendo `'{NAME} has {joined/left} the chat.'`.
|
||||
|
||||
An implementation of this could look like the following:
|
||||
Uma implementação disso seria semelhante a:
|
||||
|
||||
```js
|
||||
socket.on('user', data => {
|
||||
@@ -34,11 +34,11 @@ socket.on('user', data => {
|
||||
});
|
||||
```
|
||||
|
||||
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/bf95a0f74b756cf0771cd62c087b8286).
|
||||
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/bf95a0f74b756cf0771cd62c087b8286).
|
||||
|
||||
# --hints--
|
||||
|
||||
Event `'user'` should be emitted with name, currentUsers, and connected.
|
||||
O evento `'user'` deve ser emitido com name, currentUsers e connected.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -56,7 +56,7 @@ Event `'user'` should be emitted with name, currentUsers, and connected.
|
||||
);
|
||||
```
|
||||
|
||||
Client should properly handle and display the new data from event `'user'`.
|
||||
O client deve manipular e exibir adequadamente os novos dados do evento `'user'`.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 589fc831f9fc0f352b528e77
|
||||
title: Authentication with Socket.IO
|
||||
title: Autenticação com Socket.IO
|
||||
challengeType: 2
|
||||
forumTopicId: 301548
|
||||
dashedName: authentication-with-socket-io
|
||||
@@ -8,9 +8,9 @@ dashedName: authentication-with-socket-io
|
||||
|
||||
# --description--
|
||||
|
||||
Currently, you cannot determine who is connected to your web socket. While `req.user` contains the user object, that's only when your user interacts with the web server, and with web sockets you have no `req` (request) and therefore no user data. One way to solve the problem of knowing who is connected to your web socket is by parsing and decoding the cookie that contains the passport session then deserializing it to obtain the user object. Luckily, there is a package on NPM just for this that turns a once complex task into something simple!
|
||||
Atualmente, você não pode determinar quem está conectado ao socket da web. Embora `req.user` contenha o objeto do usuário,isso só ocorre quando o usuário interage com o servidor web. Com sockets da web, você não tem `req` (solicitação) e, portanto, não tem dados do usuário. Uma maneira de resolver o problema de saber quem está conectando ao socket da web é analisar e decodificar o cookie que contém a sessão do Passport e desserializá-lo para obter o objeto do usuário. Por sorte, existe um pacote no NPM só para este efeito, que transforma uma tarefa que antes era complexa em algo simples!
|
||||
|
||||
Add `passport.socketio@~3.7.0`, `connect-mongo@~3.2.0`, and `cookie-parser@~1.4.5` as dependencies and require them as `passportSocketIo`, `MongoStore`, and `cookieParser` respectively. Also, we need to initialize a new memory store, from `express-session` which we previously required. It should look like this:
|
||||
Adicione `passport.socketio@~3.7.0`, `connect-mongo@~3.2.0` e `cookie-parser@~1.4.5` como dependências e solicite-as como `passportSocketIo`, `MongoStore` e `cookieParser`, respectivamente. Além disso, precisamos inicializar uma nova store de memória, a partir do `express-session` que solicitamos anteriormente. Deve ficar assim:
|
||||
|
||||
```js
|
||||
const MongoStore = require('connect-mongo')(session);
|
||||
@@ -18,7 +18,7 @@ const URI = process.env.MONGO_URI;
|
||||
const store = new MongoStore({ url: URI });
|
||||
```
|
||||
|
||||
Now we just have to tell Socket.IO to use it and set the options. Be sure this is added before the existing socket code and not in the existing connection listener. For your server, it should look like this:
|
||||
Agora, só precisamos dizer ao Socket.IO para usá-la e definir as opções. Certifique-se de que ela foi adicionada antes do código do socket existente e não no listener das conexões existentes. Para o servidor, ele deve ficar assim:
|
||||
|
||||
```js
|
||||
io.use(
|
||||
@@ -33,11 +33,11 @@ io.use(
|
||||
);
|
||||
```
|
||||
|
||||
Be sure to add the `key` and `store` to the `session` middleware mounted on the app. This is necessary to tell *SocketIO* which session to relate to.
|
||||
Certifique-se de adicionar a `key` e a `store` no middleware `session` montado na aplicação. Isto é necessário para informar ao *SocketIO* a qual sessão ele deve se relacionar.
|
||||
|
||||
<hr />
|
||||
|
||||
Now, define the `success`, and `fail` callback functions:
|
||||
Agora, defina as funções de `success` e `fail` na função de callback:
|
||||
|
||||
```js
|
||||
function onAuthorizeSuccess(data, accept) {
|
||||
@@ -53,19 +53,19 @@ function onAuthorizeFail(data, message, error, accept) {
|
||||
}
|
||||
```
|
||||
|
||||
The user object is now accessible on your socket object as `socket.request.user`. For example, now you can add the following:
|
||||
Agora, o objeto de usuário está acessível no seu objeto de socket como `socket.request.user`. Por exemplo, agora, você pode adicionar o seguinte:
|
||||
|
||||
```js
|
||||
console.log('user ' + socket.request.user.name + ' connected');
|
||||
```
|
||||
|
||||
It will log to the server console who has connected!
|
||||
Ele vai logar no console do servidor que está conectado!
|
||||
|
||||
Submit your page when you think you've got it right. If you're running into errors, you can check out the project up to this point [here](https://gist.github.com/camperbot/1414cc9433044e306dd7fd0caa1c6254).
|
||||
Envie sua página quando você achar que ela está certa. Se você encontrar erros, pode conferir o projeto até este momento [aqui](https://gist.github.com/camperbot/1414cc9433044e306dd7fd0caa1c6254).
|
||||
|
||||
# --hints--
|
||||
|
||||
`passport.socketio` should be a dependency.
|
||||
`passport.socketio` deve ser uma dependência.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -84,7 +84,7 @@ Submit your page when you think you've got it right. If you're running into erro
|
||||
);
|
||||
```
|
||||
|
||||
`cookie-parser` should be a dependency.
|
||||
`cookie-parser` deve ser uma dependência.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -103,7 +103,7 @@ Submit your page when you think you've got it right. If you're running into erro
|
||||
);
|
||||
```
|
||||
|
||||
passportSocketIo should be properly required.
|
||||
O passportSocketIo deve ser solicitado adequadamente.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -121,7 +121,7 @@ passportSocketIo should be properly required.
|
||||
);
|
||||
```
|
||||
|
||||
passportSocketIo should be properly setup.
|
||||
O passportSocketIo deve ser configurado adequadamente.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 589690e6f9fc0f352b528e6e
|
||||
title: Clean Up Your Project with Modules
|
||||
title: Limpar seu projeto com módulos
|
||||
challengeType: 2
|
||||
forumTopicId: 301549
|
||||
dashedName: clean-up-your-project-with-modules
|
||||
@@ -8,9 +8,9 @@ dashedName: clean-up-your-project-with-modules
|
||||
|
||||
# --description--
|
||||
|
||||
Right now, everything you have is in your `server.js` file. This can lead to hard to manage code that isn't very expandable. Create 2 new files: `routes.js` and `auth.js`
|
||||
Nesse momento, tudo que você tem é o seu arquivo `server.js`. Isso pode levar a dificuldades para gerenciar um código que não é muito expansível. Crie 2 arquivos novos: `routes.js` e `auth.js`
|
||||
|
||||
Both should start with the following code:
|
||||
Ambos devem começar com o seguinte código:
|
||||
|
||||
```js
|
||||
module.exports = function (app, myDataBase) {
|
||||
@@ -18,19 +18,19 @@ module.exports = function (app, myDataBase) {
|
||||
}
|
||||
```
|
||||
|
||||
Now, in the top of your server file, require these files like so: `const routes = require('./routes.js');` Right after you establish a successful connection with the database, instantiate each of them like so: `routes(app, myDataBase)`
|
||||
Agora, no topo do arquivo do seu servidor, solicite estes arquivos assim: `const routes = require('./routes.js');` Depois disso, estabeleça uma conexão com o banco de dados, instanciando cada um dos arquivos da seguinte forma: `routes(app, myDataBase)`
|
||||
|
||||
Finally, take all of the routes in your server and paste them into your new files, and remove them from your server file. Also take the `ensureAuthenticated` function, since it was specifically created for routing. Now, you will have to correctly add the dependencies in which are used, such as `const passport = require('passport');`, at the very top, above the export line in your `routes.js` file.
|
||||
Por fim, pegue todas as rotas do servidor, cole-as em seus novos arquivos e remova-as do arquivo do arquivo do servidor. Leve também a função `ensureAuthenticated`, já que ela foi especificamente criada para o roteamento. Agora, você precisará adicionar corretamente as dependências em que são usadas, tais como `const passport = require('passport');`, no topo do arquivo, acima da linha de exportação do arquivo `routes.js`.
|
||||
|
||||
Keep adding them until no more errors exist, and your server file no longer has any routing (**except for the route in the catch block**)!
|
||||
Continue adicionando-os até que não existam mais erros e que o arquivo do servidor não tenha mais nenhuma rota (**exceto a rota no bloco catch**)!
|
||||
|
||||
Now do the same thing in your auth.js file with all of the things related to authentication such as the serialization and the setting up of the local strategy and erase them from your server file. Be sure to add the dependencies in and call `auth(app, myDataBase)` in the server in the same spot.
|
||||
Agora, faça a mesma coisa no arquivo auth.js. com tudo o que estiver relacionado à autenticação, como a serialização e a configuração da estratégia local, e apague-os do arquivo do servidor. Certifique-se de adicionar as dependências e de chamar `auth(app, myDataBase)` no servidor no mesmo local.
|
||||
|
||||
Submit your page when you think you've got it right. If you're running into errors, you can check out an example of the completed project [here](https://gist.github.com/camperbot/2d06ac5c7d850d8cf073d2c2c794cc92).
|
||||
Envie sua página quando você achar que ela está certa. Se você encontrar erros, pode conferir um exemplo do projeto concluído [aqui](https://gist.github.com/camperbot/2d06ac5c7d850d8cf073d2c2c794cc92).
|
||||
|
||||
# --hints--
|
||||
|
||||
Modules should be present.
|
||||
Os módulos devem estar presentes.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 589fc831f9fc0f352b528e75
|
||||
title: Communicate by Emitting
|
||||
title: Comunicar por envio
|
||||
challengeType: 2
|
||||
forumTopicId: 301550
|
||||
dashedName: communicate-by-emitting
|
||||
@@ -8,27 +8,27 @@ dashedName: communicate-by-emitting
|
||||
|
||||
# --description--
|
||||
|
||||
<dfn>Emit</dfn> is the most common way of communicating you will use. When you emit something from the server to 'io', you send an event's name and data to all the connected sockets. A good example of this concept would be emitting the current count of connected users each time a new user connects!
|
||||
<dfn>Enviar</dfn> é a forma mais comum de comunicação que você usará. Quando você envia algo do servidor para 'io', está enviando o nome e os dados de um evento para todos os sockets conectados. Um bom exemplo deste conceito seria enviar a contagem atual de usuários conectados a cada vez que um novo usuário se conecta!
|
||||
|
||||
Start by adding a variable to keep track of the users, just before where you are currently listening for connections.
|
||||
Comece adicionando uma variável para manter o controle dos usuários, logo antes do local onde você está escutando as conexões no momento.
|
||||
|
||||
```js
|
||||
let currentUsers = 0;
|
||||
```
|
||||
|
||||
Now, when someone connects, you should increment the count before emitting the count. So, you will want to add the incrementer within the connection listener.
|
||||
Agora, quando alguém se conecta, você deve incrementar a contagem antes de enviá-la. Então, você vai querer adicionar o incrementador dentro do listener de conexões.
|
||||
|
||||
```js
|
||||
++currentUsers;
|
||||
```
|
||||
|
||||
Finally, after incrementing the count, you should emit the event (still within the connection listener). The event should be named 'user count', and the data should just be the `currentUsers`.
|
||||
Por fim, depois de incrementar a contagem, você deve enviar o evento (ainda dentro do listener de conexão). O evento deve ser nomeado 'user count' e o dado devem ser simplesmente `currentUsers`.
|
||||
|
||||
```js
|
||||
io.emit('user count', currentUsers);
|
||||
```
|
||||
|
||||
Now, you can implement a way for your client to listen for this event! Similar to listening for a connection on the server, you will use the `on` keyword.
|
||||
Agora, você pode implementar uma maneira de o client escutar este evento! De modo semelhante a escutar uma conexão no servidor, você usará a palavra-chave `on`.
|
||||
|
||||
```js
|
||||
socket.on('user count', function(data) {
|
||||
@@ -36,13 +36,13 @@ socket.on('user count', function(data) {
|
||||
});
|
||||
```
|
||||
|
||||
Now, try loading up your app, authenticate, and you should see in your client console '1' representing the current user count! Try loading more clients up, and authenticating to see the number go up.
|
||||
Agora, tente carregar o seu aplicativo, autentique-se e você deve ver no console do client '1', representando a contagem de usuários no momento! Tente carregar mais clients, e autenticar para ver o número subir.
|
||||
|
||||
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/28ef7f1078f56eb48c7b1aeea35ba1f5).
|
||||
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/28ef7f1078f56eb48c7b1aeea35ba1f5).
|
||||
|
||||
# --hints--
|
||||
|
||||
currentUsers should be defined.
|
||||
currentUsers deve estar definido.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -60,7 +60,7 @@ currentUsers should be defined.
|
||||
);
|
||||
```
|
||||
|
||||
Server should emit the current user count at each new connection.
|
||||
O servidor deve enviar o contador atual a cada nova conexão.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -78,7 +78,7 @@ Server should emit the current user count at each new connection.
|
||||
);
|
||||
```
|
||||
|
||||
Your client should be listening for 'user count' event.
|
||||
O client deve estar escutando o evento 'user count'.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5895f70df9fc0f352b528e6a
|
||||
title: Create New Middleware
|
||||
title: Criar um novo middleware
|
||||
challengeType: 2
|
||||
forumTopicId: 301551
|
||||
dashedName: create-new-middleware
|
||||
@@ -8,9 +8,9 @@ dashedName: create-new-middleware
|
||||
|
||||
# --description--
|
||||
|
||||
As is, any user can just go to `/profile` whether they have authenticated or not, by typing in the url. We want to prevent this, by checking if the user is authenticated first before rendering the profile page. This is the perfect example of when to create a middleware.
|
||||
Da forma como está no momento, qualquer usuário pode ir até `/profile`, já tendo sido autenticado ou não, digitando o url. Queremos evitar isso verificando se o usuário está autenticado primeiro antes de renderizar a página de perfil. Este é o exemplo perfeito de quando criar um middleware.
|
||||
|
||||
The challenge here is creating the middleware function `ensureAuthenticated(req, res, next)`, which will check if a user is authenticated by calling passport's `isAuthenticated` method on the `request` which, in turn, checks if `req.user` is defined. If it is, then `next()` should be called, otherwise, we can just respond to the request with a redirect to our homepage to login. An implementation of this middleware is:
|
||||
O desafio aqui é cria a função do middleware `ensureAuthenticated(req, res, next)`, que vai verificar se um usuário está autenticado chamando o método `isAuthenticated` do Passport na `request` (solicitação), que, por sua vez, verificará se `req.user` está definido. Se estiver, `next()` deverá ser chamado. Caso contrário, basta responder ao pedido com um redirecionamento à nossa página inicial para fazer o login. Uma implementação deste middleware é:
|
||||
|
||||
```js
|
||||
function ensureAuthenticated(req, res, next) {
|
||||
@@ -21,7 +21,7 @@ function ensureAuthenticated(req, res, next) {
|
||||
};
|
||||
```
|
||||
|
||||
Now add *ensureAuthenticated* as a middleware to the request for the profile page before the argument to the get request containing the function that renders the page.
|
||||
Agora, adicione *ensureAuthenticated* como um middleware para a página de perfil antes do argumento para a solicitação de GET que contém a função que renderiza a página.
|
||||
|
||||
```js
|
||||
app
|
||||
@@ -31,11 +31,11 @@ app
|
||||
});
|
||||
```
|
||||
|
||||
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/ae49b8778cab87e93284a91343da0959).
|
||||
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/ae49b8778cab87e93284a91343da0959).
|
||||
|
||||
# --hints--
|
||||
|
||||
Middleware ensureAuthenticated should be implemented and on our /profile route.
|
||||
O middleware ensureAuthenticated deve estar implementado e em nossa rota /profile.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -58,7 +58,7 @@ Middleware ensureAuthenticated should be implemented and on our /profile route.
|
||||
);
|
||||
```
|
||||
|
||||
A Get request to /profile should correctly redirect to / since we are not authenticated.
|
||||
Uma solicitação de GET para /profile deve redirecionar corretamente para /, já que não estamos autenticados.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 589fc831f9fc0f352b528e76
|
||||
title: Handle a Disconnect
|
||||
title: Tratar de uma desconexão
|
||||
challengeType: 2
|
||||
forumTopicId: 301552
|
||||
dashedName: handle-a-disconnect
|
||||
@@ -8,9 +8,9 @@ dashedName: handle-a-disconnect
|
||||
|
||||
# --description--
|
||||
|
||||
You may notice that up to now you have only been increasing the user count. Handling a user disconnecting is just as easy as handling the initial connect, except you have to listen for it on each socket instead of on the whole server.
|
||||
Você pode notar que até agora você só tem aumentado a contagem de usuários. Tratar da desconexão de um usuário é tão fácil quanto manipular a conexão inicial, exceto pelo fato de que você tem que escutar isso em cada socket em vez de em todo o servidor.
|
||||
|
||||
To do this, add another listener inside the existing `'connect'` listener that listens for `'disconnect'` on the socket with no data passed through. You can test this functionality by just logging that a user has disconnected to the console.
|
||||
Para fazer isso, adicione outro listener dentro do `'connect'` que já existe e que escute por `'disconnect'` no socket sem passar dados. Você pode testar essa funcionalidade apenas registrando no console que um usuário se desconectou.
|
||||
|
||||
```js
|
||||
socket.on('disconnect', () => {
|
||||
@@ -18,15 +18,15 @@ socket.on('disconnect', () => {
|
||||
});
|
||||
```
|
||||
|
||||
To make sure clients continuously have the updated count of current users, you should decrease the currentUsers by 1 when the disconnect happens then emit the 'user count' event with the updated count!
|
||||
Para garantir que os clients tenham a contagem atualizada dos usuários atuais continuamente, você deve diminuir os currentUsers em 1 quando a desconexão acontece, emitindo o evento 'user count' com a contagem atualizada!
|
||||
|
||||
**Note:** Just like `'disconnect'`, all other events that a socket can emit to the server should be handled within the connecting listener where we have 'socket' defined.
|
||||
**Observação:** assim como ocorre com `'disconnect'`, todos os outros eventos que um socket pode emitir para o servidor devem ser tratados dentro do listener que estiver conectando, onde 'socket' está definido.
|
||||
|
||||
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/ab1007b76069884fb45b215d3c4496fa).
|
||||
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/ab1007b76069884fb45b215d3c4496fa).
|
||||
|
||||
# --hints--
|
||||
|
||||
Server should handle the event disconnect from a socket.
|
||||
O servidor deve tratar do evento de desconexão a partir de um socket.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -40,7 +40,7 @@ Server should handle the event disconnect from a socket.
|
||||
);
|
||||
```
|
||||
|
||||
Your client should be listening for 'user count' event.
|
||||
Seu client deve estar escutando o evento 'user count'.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 58a25c98f9fc0f352b528e7f
|
||||
title: Hashing Your Passwords
|
||||
title: Fazer o hashing de senhas
|
||||
challengeType: 2
|
||||
forumTopicId: 301553
|
||||
dashedName: hashing-your-passwords
|
||||
@@ -8,13 +8,13 @@ dashedName: hashing-your-passwords
|
||||
|
||||
# --description--
|
||||
|
||||
Going back to the information security section, you may remember that storing plaintext passwords is *never* okay. Now it is time to implement BCrypt to solve this issue.
|
||||
Voltando à seção de segurança da informação, você poderá ver que armazenar senhas em texto simples (plain text) *nunca* é uma boa ideia. Agora é a hora de implementar o BCrypt para resolver este problema.
|
||||
|
||||
Add `bcrypt@~5.0.0` as a dependency, and require it in your server. You will need to handle hashing in 2 key areas: where you handle registering/saving a new account, and when you check to see that a password is correct on login.
|
||||
Adicione o `bcrypt@~5.0.0` como dependência e solicite-o no servidor. Você precisará lidar com hashing em 2 áreas principais: onde você trata do registro/salvamento de uma nova conta e onde você verifica se uma senha está correta no login.
|
||||
|
||||
Currently on our registration route, you insert a user's password into the database like so: `password: req.body.password`. An easy way to implement saving a hash instead is to add the following before your database logic `const hash = bcrypt.hashSync(req.body.password, 12);`, and replacing the `req.body.password` in the database saving with just `password: hash`.
|
||||
No momento, na rota de registro, você insere a senha de um usuário no banco de dados, da seguinte forma: `password: req.body.password`. Uma maneira fácil de implementar o salvamento de um hash, em vez disso, é adicionar a instrução `const hash = bcrypt.hashSync(req.body.password, 12);` antes da lógica do seu banco de dados e substituir o `req.body.password` no banco de dados, salvando apenas `password: hash`.
|
||||
|
||||
Finally, on our authentication strategy, we check for the following in our code before completing the process: `if (password !== user.password) { return done(null, false); }`. After making the previous changes, now `user.password` is a hash. Before making a change to the existing code, notice how the statement is checking if the password is **not** equal then return non-authenticated. With this in mind, your code could look as follows to properly check the password entered against the hash:
|
||||
Por fim, na estratégia de autenticação, verificamos o seguinte no código antes de concluir o processo: `if (password !== user.password) { return done(null, false); }`. Depois de fazer as alterações acima, `user.password` passa a ser um hash. Antes de fazer uma alteração no código existente, observe como a instrução está verificando se a senha **não** é igual. Se não for, deve retornar não autenticada. Com isso em mente, o código pode se parecer assim para verificar corretamente a senha inserida com relação ao hash:
|
||||
|
||||
```js
|
||||
if (!bcrypt.compareSync(password, user.password)) {
|
||||
@@ -22,13 +22,13 @@ if (!bcrypt.compareSync(password, user.password)) {
|
||||
}
|
||||
```
|
||||
|
||||
That is all it takes to implement one of the most important security features when you have to store passwords!
|
||||
Isso é tudo o que precisamos para implementar um dos mais importantes recursos de segurança quando você tem que armazenar senhas!
|
||||
|
||||
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/dc16cca09daea4d4151a9c36a1fab564).
|
||||
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/dc16cca09daea4d4151a9c36a1fab564).
|
||||
|
||||
# --hints--
|
||||
|
||||
BCrypt should be a dependency.
|
||||
O BCrypt deve ser uma dependência.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -47,7 +47,7 @@ BCrypt should be a dependency.
|
||||
);
|
||||
```
|
||||
|
||||
BCrypt should be correctly required and implemented.
|
||||
O BCrypt deverá ser corretamente solicitado e implementado.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5895f70ef9fc0f352b528e6b
|
||||
title: How to Put a Profile Together
|
||||
title: Compor um perfil
|
||||
challengeType: 2
|
||||
forumTopicId: 301554
|
||||
dashedName: how-to-put-a-profile-together
|
||||
@@ -8,27 +8,27 @@ dashedName: how-to-put-a-profile-together
|
||||
|
||||
# --description--
|
||||
|
||||
Now that we can ensure the user accessing the `/profile` is authenticated, we can use the information contained in `req.user` on our page!
|
||||
Agora que podemos garantir que o usuário que acessou o `/profile` está autenticado, podemos usar as informações contidas no `req.user` da página!
|
||||
|
||||
Pass an object containing the property `username` and value of `req.user.username` as the second argument for the render method of the profile view. Then, go to your `profile.pug` view, and add the following line below the existing `h1` element, and at the same level of indentation:
|
||||
Passe um objeto contendo a propriedade `username` e o valor `req.user.username` como o segundo argumento para o método de renderização da visualização do perfil. Em seguida, vá à visualização `profile.pug` e adicione a linha seguinte abaixo do elemento `h1` existente, no mesmo nível de indentação:
|
||||
|
||||
```pug
|
||||
h2.center#welcome Welcome, #{username}!
|
||||
```
|
||||
|
||||
This creates an `h2` element with the class '`center`' and id '`welcome`' containing the text '`Welcome,`' followed by the username.
|
||||
Isso criará um elemento `h2` com a classe '`center`' e com o id '`welcome`', contendo o texto '`Welcome,`' seguido do nome de usuário.
|
||||
|
||||
Also, in `profile.pug`, add a link referring to the `/logout` route, which will host the logic to unauthenticate a user.
|
||||
Além disso, em `profile.pug`, adicione um link referindo-se à rota `/logout`, que hospedará a lógica para cancelar a autenticação de um usuário.
|
||||
|
||||
```pug
|
||||
a(href='/logout') Logout
|
||||
```
|
||||
|
||||
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/136b3ad611cc80b41cab6f74bb460f6a).
|
||||
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/136b3ad611cc80b41cab6f74bb460f6a).
|
||||
|
||||
# --hints--
|
||||
|
||||
You should correctly add a Pug render variable to /profile.
|
||||
Você deve adicionar corretamente uma variável de renderização do Pug em /profile.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5895f70cf9fc0f352b528e67
|
||||
title: Implement the Serialization of a Passport User
|
||||
title: Implementar a serialização de um usuário do Passport
|
||||
challengeType: 2
|
||||
forumTopicId: 301556
|
||||
dashedName: implement-the-serialization-of-a-passport-user
|
||||
@@ -8,11 +8,11 @@ dashedName: implement-the-serialization-of-a-passport-user
|
||||
|
||||
# --description--
|
||||
|
||||
Right now, we're not loading an actual user object since we haven't set up our database. This can be done many different ways, but for our project we will connect to the database once when we start the server and keep a persistent connection for the full life-cycle of the app. To do this, add your database's connection string (for example: `mongodb+srv://:@cluster0-jvwxi.mongodb.net/?retryWrites=true&w=majority`) to the environment variable `MONGO_URI`. This is used in the `connection.js` file.
|
||||
No momento, não estamos carregando um objeto de usuário real, já que não configuramos nosso banco de dados. Isto pode ser feito de muitas maneiras diferentes. Para o nosso projeto, no entanto, conectaremos ao banco de dados quando iniciarmos o servidor e manteremos uma conexão persistente para todo o ciclo de vida da aplicação. Para fazer isso, adicione a string de conexão do banco de dados (por exemplo: `mongodb+srv://:@cluster0-jvwxi.mongodb.net/?retryWrites=true&w=majority`) à variável de ambiente `MONGO_URI`. Este é usado no arquivo `connection.js`.
|
||||
|
||||
*You can set up a free database on [MongoDB Atlas](https://www.mongodb.com/cloud/atlas).*
|
||||
*Você pode configurar um banco de dados gratuito no [MongoDB Atlas](https://www.mongodb.com/cloud/atlas).*
|
||||
|
||||
Now we want to connect to our database then start listening for requests. The purpose of this is to not allow requests before our database is connected or if there is a database error. To accomplish this, you will want to encompass your serialization and your app routes in the following code:
|
||||
Agora, queremos conectar ao nosso banco de dados. Em seguida, vamos começar a escutar pedidos. O objetivo é não permitir solicitações antes de nosso banco de dados estar conectado ou se houver um erro no banco de dados. Para fazer isso, você vai querer englobar a serialização e as rotas da aplicação no código a seguir:
|
||||
|
||||
```js
|
||||
myDB(async client => {
|
||||
@@ -38,13 +38,13 @@ myDB(async client => {
|
||||
// app.listen out here...
|
||||
```
|
||||
|
||||
Be sure to uncomment the `myDataBase` code in `deserializeUser`, and edit your `done(null, null)` to include the `doc`.
|
||||
Certifique-se de descomentar o código `myDataBase` em `deserializeUser` e de editar o seu `done(null, null)` para incluir o `doc`.
|
||||
|
||||
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/175f2f585a2d8034044c7e8857d5add7).
|
||||
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/175f2f585a2d8034044c7e8857d5add7).
|
||||
|
||||
# --hints--
|
||||
|
||||
Database connection should be present.
|
||||
A conexão do banco de dados deve estar presente.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -62,7 +62,7 @@ Database connection should be present.
|
||||
);
|
||||
```
|
||||
|
||||
Deserialization should now be correctly using the DB and `done(null, null)` should be called with the `doc`.
|
||||
A desserialização agora deve estar usando corretamente o banco de dados e `done(null, null)` deve ser chamado com o `doc`.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 589a69f5f9fc0f352b528e71
|
||||
title: Implementation of Social Authentication II
|
||||
title: Implementar a autenticação social II
|
||||
challengeType: 2
|
||||
forumTopicId: 301557
|
||||
dashedName: implementation-of-social-authentication-ii
|
||||
@@ -8,11 +8,11 @@ dashedName: implementation-of-social-authentication-ii
|
||||
|
||||
# --description--
|
||||
|
||||
The last part of setting up your GitHub authentication is to create the strategy itself. For this, you will need to add the dependency of `passport-github@~1.1.0` to your project and require it in your `auth.js` as `GithubStrategy` like this: `const GitHubStrategy = require('passport-github').Strategy;`. Do not forget to require and configure `dotenv` to use your environment variables.
|
||||
A última parte da configuração da autenticação no GitHub é criar a própria estratégia. Para isso, você precisará adicionar a dependência do `passport-github@~1.1.0` ao projeto e solicitá-la no `auth.js` como `GithubStrategy` assim: `const GitHubStrategy = require('passport-github').Strategy;`. Não se esqueça de solicitar e configurar o `dotenv` para usar as variáveis de ambiente.
|
||||
|
||||
To set up the GitHub strategy, you have to tell Passport to use an instantiated `GitHubStrategy`, which accepts 2 arguments: an object (containing `clientID`, `clientSecret`, and `callbackURL`) and a function to be called when a user is successfully authenticated, which will determine if the user is new and what fields to save initially in the user's database object. This is common across many strategies, but some may require more information as outlined in that specific strategy's GitHub README. For example, Google requires a *scope* as well which determines what kind of information your request is asking to be returned and asks the user to approve such access. The current strategy we are implementing has its usage outlined [here](https://github.com/jaredhanson/passport-github/), but we're going through it all right here on freeCodeCamp!
|
||||
Para configurar a estratégia do GitHub, você precisa dizer ao Passport para usar uma `GitHubStrategy` instanciada, que aceite 2 argumentos: um objeto (contendo `clientID`, `clientSecret` e `callbackURL`) e uma função a ser chamada quando um usuário é autenticado com sucesso, que determinará se o usuário é novo e quais campos salvar inicialmente no objeto do banco de dados do usuário. Isto é comum em muitas estratégias, mas algumas podem exigir mais informações, conforme descrito no README do GitHub da estratégia específica. Por exemplo, O Google também requer um *scope*, o qual determina que tipo de informação a solicitação está pedindo que seja devolvida e pede ao usuário que aprove esse acesso. A estratégia atual que estamos implementando tem seu uso delineado [aqui](https://github.com/jaredhanson/passport-github/), mas nós a examinaremos bem aqui, no freeCodeCamp!
|
||||
|
||||
Here's how your new strategy should look at this point:
|
||||
Saiba como a nova estratégia deve se parecer nesse momento:
|
||||
|
||||
```js
|
||||
passport.use(new GitHubStrategy({
|
||||
@@ -27,13 +27,13 @@ passport.use(new GitHubStrategy({
|
||||
));
|
||||
```
|
||||
|
||||
Your authentication won't be successful yet, and it will actually throw an error without the database logic and callback, but it should log your GitHub profile to your console if you try it!
|
||||
A autenticação ainda não será bem-sucedida e realmente lançará um erro sem a lógica e a função de callback do banco de dados, mas ela deverá fazer o login com o seu perfil do GitHub no console se você tentar!
|
||||
|
||||
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/ff3a1166684c1b184709ac0bee30dee6).
|
||||
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/ff3a1166684c1b184709ac0bee30dee6).
|
||||
|
||||
# --hints--
|
||||
|
||||
passport-github dependency should be added.
|
||||
A dependência do passport-github deve ser adicionada.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -52,7 +52,7 @@ passport-github dependency should be added.
|
||||
);
|
||||
```
|
||||
|
||||
passport-github should be required.
|
||||
O passport-github deve ser solicitado.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -70,7 +70,7 @@ passport-github should be required.
|
||||
);
|
||||
```
|
||||
|
||||
GitHub strategy should be setup correctly thus far.
|
||||
A estratégia do GitHub deve estar configurada corretamente até aqui.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 589a69f5f9fc0f352b528e70
|
||||
title: Implementation of Social Authentication
|
||||
title: Implementar a autenticação social
|
||||
challengeType: 2
|
||||
forumTopicId: 301559
|
||||
dashedName: implementation-of-social-authentication
|
||||
@@ -8,21 +8,21 @@ dashedName: implementation-of-social-authentication
|
||||
|
||||
# --description--
|
||||
|
||||
The basic path this kind of authentication will follow in your app is:
|
||||
O caminho básico que este tipo de autenticação vai seguir em sua aplicação é:
|
||||
|
||||
1. User clicks a button or link sending them to our route to authenticate using a specific strategy (e.g. GitHub).
|
||||
2. Your route calls `passport.authenticate('github')` which redirects them to GitHub.
|
||||
3. The page the user lands on, on GitHub, allows them to login if they aren't already. It then asks them to approve access to their profile from our app.
|
||||
4. The user is then returned to our app at a specific callback url with their profile if they are approved.
|
||||
5. They are now authenticated, and your app should check if it is a returning profile, or save it in your database if it is not.
|
||||
1. O usuário clica em um botão ou link que o envia para nossa rota de autenticação que usa uma estratégia específica (por exemplo, o GitHub).
|
||||
2. A rota chama `passport.authenticate('github')`, que os redireciona para o GitHub.
|
||||
3. A página que o usuário entra no GitHub permite que ele faça o login, se ainda não o fez. Em seguida, ela pede que eles aprovem o acesso ao seu perfil a partir de nossa aplicação.
|
||||
4. O usuário é então retornado para a nossa aplicação em um url específico de callback com seu perfil, se ele for aprovado.
|
||||
5. Agora que o usuário está autenticado. O aplicativo deve verificar se é um perfil que está retornando ou salvá-lo no banco de dados, se não for o caso.
|
||||
|
||||
Strategies with OAuth require you to have at least a *Client ID* and a *Client Secret* which is a way for the service to verify who the authentication request is coming from and if it is valid. These are obtained from the site you are trying to implement authentication with, such as GitHub, and are unique to your app--**THEY ARE NOT TO BE SHARED** and should never be uploaded to a public repository or written directly in your code. A common practice is to put them in your `.env` file and reference them like so: `process.env.GITHUB_CLIENT_ID`. For this challenge we're going to use the GitHub strategy.
|
||||
As estratégias com OAuth exigem que você tenha, pelo menos, um *ID de client* e um *segredo de client*, que é uma maneira de o serviço verificar de quem está vindo o pedido de autenticação e se ele é válido. Estes são obtidos do site com o qual você está tentando implementar a autenticação, como o GitHub, e são exclusivos do seu aplicativo. **ELES NÃO DEVEM SER COMPARTILHADOS** e nunca devem ser enviados para um repositório público ou escritos diretamente no código. Uma prática comum é colocá-los no seu arquivo `.env` e referenciá-los assim: `process.env.GITHUB_CLIENT_ID`. Para este desafio, vamos usar a estratégia do GitHub.
|
||||
|
||||
Obtaining your *Client ID and Secret* from GitHub is done in your account profile settings under 'developer settings', then '[OAuth applications](https://github.com/settings/developers)'. Click 'Register a new application', name your app, paste in the url to your Replit homepage (**Not the project code's url**), and lastly, for the callback url, paste in the same url as the homepage but with `/auth/github/callback` added on. This is where users will be redirected for us to handle after authenticating on GitHub. Save the returned information as `'GITHUB_CLIENT_ID'` and `'GITHUB_CLIENT_SECRET'` in your `.env` file.
|
||||
Obter seu *ID e segredo de client* do GitHub é feito nas configurações do perfil da conta, em 'Configurações do desenvolvedor'. Em seguida, '[Aplicações OAuth](https://github.com/settings/developers)'. Clique em 'Registrar uma nova aplicação', nomeie sua aplicação, cole o url da sua página inicial do Replit (**não o url do código do projeto**) e, finalmente, para o url de callback, cole o mesmo url da página inicial, mas com `/auth/github/callback` adicionado. É para cá que os usuários serão redirecionados para que possamos fazer o tratamento das informações após a autenticação no GitHub. Salve as informações retornadas como `'GITHUB_CLIENT_ID'` e `'GITHUB_CLIENT_SECRET'` no arquivo `.env`.
|
||||
|
||||
In your `routes.js` file, add `showSocialAuth: true` to the homepage route, after `showRegistration: true`. Now, create 2 routes accepting GET requests: `/auth/github` and `/auth/github/callback`. The first should only call passport to authenticate `'github'`. The second should call passport to authenticate `'github'` with a failure redirect to `/`, and then if that is successful redirect to `/profile` (similar to our last project).
|
||||
No seu arquivo `routes.js`, adicione `showSocialAuth: true` à rota da página inicial, após `showRegistration: true`. Agora, crie 2 rotas aceitando solicitações de GET: `/auth/github` e `/auth/github/callback`. O primeiro deve apenas chamar o Passport para autenticar o `'github'`. O segundo deve chamar o Passport para autenticar o `'github'` com um redirecionamento de falha para `/`. Então, se tiver sucesso, redirecionar para o `/profile` (semelhante ao nosso último projeto).
|
||||
|
||||
An example of how `/auth/github/callback` should look is similar to how we handled a normal login:
|
||||
Um exemplo de como `/auth/github/callback` deve parecer é semelhante a como nós manipulamos um login normal:
|
||||
|
||||
```js
|
||||
app.route('/login')
|
||||
@@ -31,11 +31,11 @@ app.route('/login')
|
||||
});
|
||||
```
|
||||
|
||||
Submit your page when you think you've got it right. If you're running into errors, you can check out the project up to this point [here](https://gist.github.com/camperbot/1f7f6f76adb178680246989612bea21e).
|
||||
Envie sua página quando você achar que ela está certa. Se você encontrar erros, pode conferir o projeto até este momento [aqui](https://gist.github.com/camperbot/1f7f6f76adb178680246989612bea21e).
|
||||
|
||||
# --hints--
|
||||
|
||||
Route /auth/github should be correct.
|
||||
A rota /auth/github deve estar correta.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -53,7 +53,7 @@ Route /auth/github should be correct.
|
||||
);
|
||||
```
|
||||
|
||||
Route /auth/github/callback should be correct.
|
||||
A rota /auth/github/callback deve estar correta.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 58965611f9fc0f352b528e6c
|
||||
title: Logging a User Out
|
||||
title: Fazer o logout do usuário
|
||||
challengeType: 2
|
||||
forumTopicId: 301560
|
||||
dashedName: logging-a-user-out
|
||||
@@ -8,9 +8,9 @@ dashedName: logging-a-user-out
|
||||
|
||||
# --description--
|
||||
|
||||
Creating the logout logic is easy. The route should just unauthenticate the user and redirect to the home page instead of rendering any view.
|
||||
Criar a lógica de logout é fácil. A rota deve apenas cancelar a autenticação do usuário e redirecionar para a página inicial em vez de renderizar qualquer visualização.
|
||||
|
||||
In passport, unauthenticating a user is as easy as just calling `req.logout();` before redirecting.
|
||||
No Passport, cancelar a autenticação de um usuário é fácil. Basta chamar `req.logout();` antes de redirecionar.
|
||||
|
||||
```js
|
||||
app.route('/logout')
|
||||
@@ -20,7 +20,7 @@ app.route('/logout')
|
||||
});
|
||||
```
|
||||
|
||||
You may have noticed that we're not handling missing pages (404). The common way to handle this in Node is with the following middleware. Go ahead and add this in after all your other routes:
|
||||
Você deve ter percebido que não estamos lidando com páginas ausentes (404). A maneira comum de lidar com isso no Node é com o middleware que veremos a seguir. Adicione-o isso depois de todas as suas outras rotas:
|
||||
|
||||
```js
|
||||
app.use((req, res, next) => {
|
||||
@@ -30,11 +30,11 @@ app.use((req, res, next) => {
|
||||
});
|
||||
```
|
||||
|
||||
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/c3eeb8a3ebf855e021fd0c044095a23b).
|
||||
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/c3eeb8a3ebf855e021fd0c044095a23b).
|
||||
|
||||
# --hints--
|
||||
|
||||
`req.Logout` should be called in your `/logout` route.
|
||||
`req.Logout` deve ser chamado na rota `/logout`.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -52,7 +52,7 @@ Submit your page when you think you've got it right. If you're running into erro
|
||||
);
|
||||
```
|
||||
|
||||
Logout should redirect to the home page.
|
||||
O logout deve redirecionar para a página inicial.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 589fc832f9fc0f352b528e79
|
||||
title: Send and Display Chat Messages
|
||||
title: Enviar e exibir mensagens de bate-papo
|
||||
challengeType: 2
|
||||
forumTopicId: 301562
|
||||
dashedName: send-and-display-chat-messages
|
||||
@@ -8,7 +8,7 @@ dashedName: send-and-display-chat-messages
|
||||
|
||||
# --description--
|
||||
|
||||
It's time you start allowing clients to send a chat message to the server to emit to all the clients! In your `client.js` file, you should see there is already a block of code handling when the message form is submitted.
|
||||
É hora de começar a permitir que os clients enviem uma mensagem de bate-papo ao servidor para que seja enviada a todos os outros clients! No arquivo `client.js`, você deve ver que já há um bloco de tratamento de código quando o formulário de mensagens é enviado.
|
||||
|
||||
```js
|
||||
$('form').submit(function() {
|
||||
@@ -16,23 +16,23 @@ $('form').submit(function() {
|
||||
});
|
||||
```
|
||||
|
||||
Within the form submit code, you should emit an event after you define `messageToSend` but before you clear the text box `#m`. The event should be named `'chat message'` and the data should just be `messageToSend`.
|
||||
Dentro do código de envio do formulário, você deve enviar um evento depois de definir `messageToSend`, mas antes de limpar a caixa de texto `#m`. O evento deve ser nomeado `'chat message'` e o dado devem ser simplesmente `messageToSend`.
|
||||
|
||||
```js
|
||||
socket.emit('chat message', messageToSend);
|
||||
```
|
||||
|
||||
Now, on your server, you should be listening to the socket for the event `'chat message'` with the data being named `message`. Once the event is received, it should emit the event `'chat message'` to all sockets `io.emit` with the data being an object containing `name` and `message`.
|
||||
Agora, no servidor, você deve estar escutando o socket para o evento `'chat message'` com os dados nomeados como `message`. Quando o evento for recebido, ele deve emitir o evento `'chat message'` para todos os sockets `io.emit` com os dados sendo um objeto contendo `name` e `message`.
|
||||
|
||||
In `client.js`, you should now listen for event `'chat message'` and, when received, append a list item to `#messages` with the name, a colon, and the message!
|
||||
No `client.js`, agora, você deve escutar o evento `'chat message'` e, quando ele for recebido, associe um item de lista a `#messages` com o nome, um sinal de dois-pontos e a mensagem!
|
||||
|
||||
At this point, the chat should be fully functional and sending messages across all clients!
|
||||
Neste ponto, o chat deve estar totalmente funcional e enviando mensagens para todos os clients!
|
||||
|
||||
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/d7af9864375207e254f73262976d2016).
|
||||
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/d7af9864375207e254f73262976d2016).
|
||||
|
||||
# --hints--
|
||||
|
||||
Server should listen for `'chat message'` and then emit it properly.
|
||||
O servidor deve escutar por `'chat message'` e, em seguida, emiti-la corretamente.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -50,7 +50,7 @@ Server should listen for `'chat message'` and then emit it properly.
|
||||
);
|
||||
```
|
||||
|
||||
Client should properly handle and display the new data from event `'chat message'`.
|
||||
O client deve manipular e exibir adequadamente os novos dados do evento `'chat message'`.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5895f700f9fc0f352b528e63
|
||||
title: Set up a Template Engine
|
||||
title: Configurar um mecanismo de modelo
|
||||
challengeType: 2
|
||||
forumTopicId: 301564
|
||||
dashedName: set-up-a-template-engine
|
||||
@@ -8,31 +8,31 @@ dashedName: set-up-a-template-engine
|
||||
|
||||
# --description--
|
||||
|
||||
Working on these challenges will involve you writing your code using one of the following methods:
|
||||
Trabalhar nesses desafios vai fazer com que você escreva seu código usando um dos seguintes métodos:
|
||||
|
||||
- Clone [this GitHub repo](https://github.com/freeCodeCamp/boilerplate-advancednode/) and complete these challenges locally.
|
||||
- Use [our Replit starter project](https://replit.com/github/freeCodeCamp/boilerplate-advancednode) to complete these challenges.
|
||||
- Use a site builder of your choice to complete the project. Be sure to incorporate all the files from our GitHub repo.
|
||||
- Clone [este repositório do GitHub](https://github.com/freeCodeCamp/boilerplate-advancednode/) e complete esses desafios localmente.
|
||||
- Use [nosso projeto inicial do Replit](https://replit.com/github/freeCodeCamp/boilerplate-advancednode) para completar esses desafios.
|
||||
- Use um construtor de site de sua escolha para completar o projeto. Certifique-se de incorporar todos os arquivos do nosso repositório no GitHub.
|
||||
|
||||
When you are done, make sure a working demo of your project is hosted somewhere public. Then submit the URL to it in the `Solution Link` field.
|
||||
Quando terminar, certifique-se de que uma demonstração funcional do seu projeto está hospedada em algum lugar público. Em seguida, envie o URL para ela no campo `Solution Link`.
|
||||
|
||||
A template engine enables you to use static template files (such as those written in *Pug*) in your app. At runtime, the template engine replaces variables in a template file with actual values which can be supplied by your server. Then it transforms the template into a static HTML file that is sent to the client. This approach makes it easier to design an HTML page and allows for displaying variables on the page without needing to make an API call from the client.
|
||||
Um mecanismo de templates (template engine) permite o uso de arquivos de modelo estáticos (como aqueles escritos no *Pug*) na aplicação. Em tempo de execução, o mecanismo de modelos substitui variáveis em um arquivo de modelo por valores reais que podem ser fornecidos pelo servidor. Em seguida, ele transforma o modelo em um arquivo HTML estático, que é enviado ao client. Esta abordagem torna mais fácil projetar uma página HTML e permite exibir variáveis na página sem precisar fazer uma chamada de API do client.
|
||||
|
||||
Add `pug@~3.0.0` as a dependency in your `package.json` file.
|
||||
Adicione `pug@~3.0.0` como uma dependência no arquivo `package.json`.
|
||||
|
||||
Express needs to know which template engine you are using. We will use the `set` method to assign `pug` as the `view engine` property's value: `app.set('view engine', 'pug')`
|
||||
O Express precisa saber qual mecanismo de modelos você está usando. Usaremos o método `set` para atribuir `pug` como o valor da propriedade `view engine`: `app.set('view engine', 'pug')`
|
||||
|
||||
Your page will not load until you correctly render the index file in the `views/pug` directory.
|
||||
A página não será carregada até que você renderize corretamente o arquivo de índice no diretório `views/pug`.
|
||||
|
||||
Change the argument of the `res.render()` declaration in the `/` route to be the file path to the `views/pug` directory. The path can be a relative path (relative to views), or an absolute path, and does not require a file extension.
|
||||
Altere o argumento da declaração `res.render()` na rota `/` para que seja o caminho de arquivo para o diretório `views/pug`. O caminho pode ser um caminho relativo (relativo às visualizações) ou um caminho absoluto e não necessita de uma extensão de arquivo.
|
||||
|
||||
If all went as planned, your app home page will stop showing the message "`Pug template is not defined.`" and will now display a message indicating you've successfully rendered the Pug template!
|
||||
Se tudo correu como planejado, sua página inicial vai parar de mostrar a mensagem "`Pug template is not defined.`" e agora exibirá uma mensagem indicando que você renderizou com sucesso o modelo do Pug!
|
||||
|
||||
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/3515cd676ea4dfceab4e322f59a37791).
|
||||
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/3515cd676ea4dfceab4e322f59a37791).
|
||||
|
||||
# --hints--
|
||||
|
||||
Pug should be a dependency.
|
||||
O Pug deve ser uma dependência.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -51,7 +51,7 @@ Pug should be a dependency.
|
||||
);
|
||||
```
|
||||
|
||||
View engine should be Pug.
|
||||
O mecanismo de visualização (view engine) deve ser o Pug.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -69,7 +69,7 @@ View engine should be Pug.
|
||||
);
|
||||
```
|
||||
|
||||
Use the correct ExpressJS method to render the index page from the response.
|
||||
Use o método correto do ExpressJS para processar a página do índice a partir da resposta.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -87,7 +87,7 @@ Use the correct ExpressJS method to render the index page from the response.
|
||||
);
|
||||
```
|
||||
|
||||
Pug should be working.
|
||||
O Pug deve funcionar.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5895f70cf9fc0f352b528e65
|
||||
title: Set up Passport
|
||||
title: Configurar o Passport
|
||||
challengeType: 2
|
||||
forumTopicId: 301565
|
||||
dashedName: set-up-passport
|
||||
@@ -8,15 +8,15 @@ dashedName: set-up-passport
|
||||
|
||||
# --description--
|
||||
|
||||
It's time to set up *Passport* so we can finally start allowing a user to register or login to an account! In addition to Passport, we will use Express-session to handle sessions. Using this middleware saves the session id as a cookie in the client and allows us to access the session data using that id on the server. This way we keep personal account information out of the cookie used by the client to verify to our server they are authenticated and just keep the *key* to access the data stored on the server.
|
||||
É hora de configurar o *Passport* para que possamos finalmente começar a permitir que um usuário se registre ou faça o login em uma conta! Além do Passport, usaremos Express-session para tratar das sessões. Usar este middleware salva o id da sessão como um cookie no client e nos permite acessar os dados da sessão usando esse id no servidor. Desta forma, mantemos as informações da conta pessoal fora do cookie usado pelo client para verificar para o servidor que o usuário está autenticado e, simplesmente, manter a *chave* para acessar os dados armazenados no servidor.
|
||||
|
||||
To set up Passport for use in your project, you will need to add it as a dependency first in your package.json. `passport@~0.4.1`
|
||||
Para configurar o Passport para uso no projeto, você precisará adicioná-lo primeiro como uma dependência em seu package.json. `passport@~0.4.1`
|
||||
|
||||
In addition, add Express-session as a dependency now as well. Express-session has a ton of advanced features you can use but for now we're just going to use the basics! `express-session@~1.17.1`
|
||||
Além disso, adicione também Express-session como uma dependência. Express-session tem dezenas de recursos avançados que você pode usar, mas, no momento, vamos usá-lo apenas para o básico! `express-session@~1.17.1`
|
||||
|
||||
You will need to set up the session settings now and initialize Passport. Be sure to first create the variables 'session' and 'passport' to require 'express-session' and 'passport' respectively.
|
||||
Você precisará configurar as definições de sessão agora e inicializar o Passport. Certifique-se de primeiro criar as variáveis "session" e "passport" para exigir "express-session" e "passport", respectivamente.
|
||||
|
||||
To set up your express app to use the session we'll define just a few basic options. Be sure to add 'SESSION_SECRET' to your .env file and give it a random value. This is used to compute the hash used to encrypt your cookie!
|
||||
Para configurar a aplicação com Express para que use o session, definiremos apenas algumas opções básicas. Certifique-se de adicionar 'SESSION_SECRET' ao seu arquivo .env e de dar a ele um valor aleatório. Isto é usado para calcular o hash usado para criptografar seu cookie!
|
||||
|
||||
```js
|
||||
app.use(session({
|
||||
@@ -27,13 +27,13 @@ app.use(session({
|
||||
}));
|
||||
```
|
||||
|
||||
As well you can go ahead and tell your express app to **use** 'passport.initialize()' and 'passport.session()'. (For example, `app.use(passport.initialize());`)
|
||||
Você também pode dizer à aplicação do Express para **usar** 'passport.initialize()' e 'passport.session()'. (Por exemplo, `app.use(passport.initialize());`)
|
||||
|
||||
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/4068a7662a2f9f5d5011074397d6788c).
|
||||
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/4068a7662a2f9f5d5011074397d6788c).
|
||||
|
||||
# --hints--
|
||||
|
||||
Passport and Express-session should be dependencies.
|
||||
O Passport e o Express-session devem ser dependências.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -57,7 +57,7 @@ Passport and Express-session should be dependencies.
|
||||
);
|
||||
```
|
||||
|
||||
Dependencies should be correctly required.
|
||||
As dependências devem ser solicitados corretamente.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -80,7 +80,7 @@ Dependencies should be correctly required.
|
||||
);
|
||||
```
|
||||
|
||||
Express app should use new dependencies.
|
||||
A aplicação do Express deve usar novas dependências.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -103,7 +103,7 @@ Express app should use new dependencies.
|
||||
);
|
||||
```
|
||||
|
||||
Session and session secret should be correctly set up.
|
||||
Session e session secret devem estar definidos corretamente.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -111,7 +111,7 @@ Session and session secret should be correctly set up.
|
||||
(data) => {
|
||||
assert.match(
|
||||
data,
|
||||
/secret:( |)process.env.SESSION_SECRET/gi,
|
||||
/secret:( |)process\.env(\.SESSION_SECRET|\[(?<q>"|')SESSION_SECRET\k<q>\])/g,
|
||||
'Your express app should have express-session set up with your secret as process.env.SESSION_SECRET'
|
||||
);
|
||||
},
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 589fc830f9fc0f352b528e74
|
||||
title: Set up the Environment
|
||||
title: Configure o ambiente
|
||||
challengeType: 2
|
||||
forumTopicId: 301566
|
||||
dashedName: set-up-the-environment
|
||||
@@ -8,20 +8,20 @@ dashedName: set-up-the-environment
|
||||
|
||||
# --description--
|
||||
|
||||
The following challenges will make use of the `chat.pug` file. So, in your `routes.js` file, add a GET route pointing to `/chat` which makes use of `ensureAuthenticated`, and renders `chat.pug`, with `{ user: req.user }` passed as an argument to the response. Now, alter your existing `/auth/github/callback` route to set the `req.session.user_id = req.user.id`, and redirect to `/chat`.
|
||||
Os desafios a seguir farão uso do arquivo `chat.pug`. Assim, em seu arquivo `routes.js`, adicione uma rota de GET apontando para `/chat`, que faz uso de `ensureAuthenticated` e renderiza `chat.pug`, com `{ user: req.user }` passado como argumento para a resposta. Agora, altere a rota `/auth/github/callback` existente para definir `req.session.user_id = req.user.id`e redirecione para `/chat`.
|
||||
|
||||
Add `socket.io@~2.3.0` as a dependency and require/instantiate it in your server defined as follows, with `http` (comes built-in with Nodejs):
|
||||
Adicione `socket.io@~2.3.0` como uma dependência e solicite/instancie-o no servidor definido como `http` (que vem integrado ao Node.js), conforme segue:
|
||||
|
||||
```javascript
|
||||
const http = require('http').createServer(app);
|
||||
const io = require('socket.io')(http);
|
||||
```
|
||||
|
||||
Now that the *http* server is mounted on the *express app*, you need to listen from the *http* server. Change the line with `app.listen` to `http.listen`.
|
||||
Agora que o servidor *http* está montado na aplicação do *Express*, você precisa escutar o servidor *http*. Altere a linha com `app.listen` para `http.listen`.
|
||||
|
||||
The first thing needing to be handled is listening for a new connection from the client. The <dfn>on</dfn> keyword does just that- listen for a specific event. It requires 2 arguments: a string containing the title of the event that's emitted, and a function with which the data is passed though. In the case of our connection listener, we use *socket* to define the data in the second argument. A socket is an individual client who is connected.
|
||||
A primeira coisa que precisa ser tratada é escutar uma nova conexão do client. A palavra-chave <dfn>on</dfn> faz isso - escuta um evento específico. Ela requer 2 argumentos: uma string contendo o título do evento que é emitido e uma função com a qual os dados são passados. No caso do nosso listener de conexão, usamos o *socket* para definir os dados no segundo argumento. Um socket é um client individual que está conectado.
|
||||
|
||||
To listen for connections to your server, add the following within your database connection:
|
||||
Para escutar as conexões do servidor, adicione o seguinte na sua conexão do banco de dados:
|
||||
|
||||
```javascript
|
||||
io.on('connection', socket => {
|
||||
@@ -29,24 +29,24 @@ io.on('connection', socket => {
|
||||
});
|
||||
```
|
||||
|
||||
Now for the client to connect, you just need to add the following to your `client.js` which is loaded by the page after you've authenticated:
|
||||
Agora, para o client se conectar, basta adicionar o seguinte ao `client.js` que é carregado pela página após a autenticação:
|
||||
|
||||
```js
|
||||
/*global io*/
|
||||
let socket = io();
|
||||
```
|
||||
|
||||
The comment suppresses the error you would normally see since 'io' is not defined in the file. We've already added a reliable CDN to the Socket.IO library on the page in chat.pug.
|
||||
O comentário suprime o erro que você normalmente veria, já que 'io' não está definido no arquivo. Já adicionamos um CDN confiável à biblioteca socket.io na página em chat.pug.
|
||||
|
||||
Now try loading up your app and authenticate and you should see in your server console 'A user has connected'!
|
||||
Agora, tente carregar o aplicativo e autentique-se. Você deve ver no console do servidor a frase 'A user has connected'!
|
||||
|
||||
**Note:**`io()` works only when connecting to a socket hosted on the same url/server. For connecting to an external socket hosted elsewhere, you would use `io.connect('URL');`.
|
||||
**Observação:** `io()` só funciona ao se conectar a um socket hospedado no mesmo url/servidor. Para se conectar a um socket externo hospedado em outro lugar, você usaria `io.connect('URL');`.
|
||||
|
||||
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/aae41cf59debc1a4755c9a00ee3859d1).
|
||||
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/aae41cf59debc1a4755c9a00ee3859d1).
|
||||
|
||||
# --hints--
|
||||
|
||||
`socket.io` should be a dependency.
|
||||
`socket.io` deve ser uma dependência.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -65,7 +65,7 @@ Submit your page when you think you've got it right. If you're running into erro
|
||||
);
|
||||
```
|
||||
|
||||
You should correctly require and instantiate `http` as `http`.
|
||||
Você deve solicitar e instanciar corretamente `http` como `http`.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -83,7 +83,7 @@ You should correctly require and instantiate `http` as `http`.
|
||||
);
|
||||
```
|
||||
|
||||
You should correctly require and instantiate `socket.io` as `io`.
|
||||
Você deve solicitar e instanciar corretamente `socket.io` como `io`.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -101,7 +101,7 @@ You should correctly require and instantiate `socket.io` as `io`.
|
||||
);
|
||||
```
|
||||
|
||||
Socket.IO should be listening for connections.
|
||||
Socket.IO deve estar escutando as conexões.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -119,7 +119,7 @@ Socket.IO should be listening for connections.
|
||||
);
|
||||
```
|
||||
|
||||
Your client should connect to your server.
|
||||
O client deve se conectar ao servidor.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5895f70bf9fc0f352b528e64
|
||||
title: Use a Template Engine's Powers
|
||||
title: Usar as capacidades de um mecanismo de modelos
|
||||
challengeType: 2
|
||||
forumTopicId: 301567
|
||||
dashedName: use-a-template-engines-powers
|
||||
@@ -8,23 +8,23 @@ dashedName: use-a-template-engines-powers
|
||||
|
||||
# --description--
|
||||
|
||||
One of the greatest features of using a template engine is being able to pass variables from the server to the template file before rendering it to HTML.
|
||||
Uma das maiores características do uso de um mecanismo de modelos (template engine) é poder passar variáveis do servidor para o arquivo de modelo antes de renderizá-lo em HTML.
|
||||
|
||||
In your Pug file, you're able to use a variable by referencing the variable name as `#{variable_name}` inline with other text on an element or by using an equal sign on the element without a space such as `p=variable_name` which assigns the variable's value to the p element's text.
|
||||
No seu arquivo Pug, você pode usar uma variável fazendo referência ao nome da variável como `#{variable_name}` em linha com outro texto em um elemento ou usando um sinal de igual no elemento sem um espaço, como em `p=variable_name`, que atribui o valor da variável ao texto do elemento p.
|
||||
|
||||
We strongly recommend looking at the syntax and structure of Pug [here](https://github.com/pugjs/pug) on GitHub's README. Pug is all about using whitespace and tabs to show nested elements and cutting down on the amount of code needed to make a beautiful site.
|
||||
É altamente recomendável examinar a sintaxe e a estrutura do Pug [aqui](https://github.com/pugjs/pug) no LEIAME do GitHub. O Pug tem a ver com usar o espaço em branco e as tabulações para mostrar elementos aninhados e diminuir a quantidade de código necessária para fazer um belo site.
|
||||
|
||||
Looking at our pug file 'index.pug' included in your project, we used the variables *title* and *message*.
|
||||
Olhando para nosso arquivo pug 'index.pug', incluído em seu projeto, podemos ver as variáveis *title* e *message*.
|
||||
|
||||
To pass those along from our server, you will need to add an object as a second argument to your *res.render* with the variables and their values. For example, pass this object along setting the variables for your index view: `{title: 'Hello', message: 'Please login'}`
|
||||
Para passar esses dados de nosso servidor, você precisará adicionar um objeto como um segundo argumento para *res.render* com as variáveis e seus valores. Para exemplificar, passe este objeto e configure as variáveis para sua visualização do índice: `{title: 'Hello', message: 'Please login'}`
|
||||
|
||||
It should look like: `res.render(process.cwd() + '/views/pug/index', {title: 'Hello', message: 'Please login'});` Now refresh your page and you should see those values rendered in your view in the correct spot as laid out in your index.pug file!
|
||||
Deve se parecer como o seguinte: `res.render(process.cwd() + '/views/pug/index', {title: 'Hello', message: 'Please login'});` Em seguida, atualize a página e você deve ver esses valores renderizados em sua visualização no ponto correto conforme descrito no arquivo index.pug!
|
||||
|
||||
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/4af125119ed36e6e6a8bb920db0c0871).
|
||||
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/4af125119ed36e6e6a8bb920db0c0871).
|
||||
|
||||
# --hints--
|
||||
|
||||
Pug should correctly render variables.
|
||||
O Pug deve renderizar as variáveis corretamente.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
Reference in New Issue
Block a user