-
Notifications
You must be signed in to change notification settings - Fork 42
Implementa a sessão #70
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,4 @@ | ||
| NODE_ENV=development | ||
| DATABASE_URL=mysql://nodebr:nodebr@localhost/nodebr | ||
| PORT=8080 | ||
| COOKIE_SECRET=here_be_dragons |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| const co = require('co') | ||
|
|
||
| /** | ||
| * Um helper para registrar handlers assíncronos | ||
| * @todo Implementar funcionalidade para Promises | ||
| * @param {Function} handler Um generator que irá receber a requisição | ||
| * @return {Function} Uma função que pode ser usada como handler no Express | ||
| */ | ||
| module.exports = handler => (req, res, next) => { | ||
| co(handler.bind(null, req, res, next)) | ||
| .catch(err => next(err)) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| /* $lab:coverage:off$ */ | ||
| const co = require('co') | ||
|
|
||
| /** | ||
| * Cria uma função no Bookshelf para zerar o banco de dados | ||
| * @param {Object} bookshelf Uma instância do Bookshelf | ||
| */ | ||
| module.exports = bookshelf => { | ||
| const { knex } = bookshelf | ||
|
|
||
| bookshelf.dropDatabase = co.wrap(function * () { | ||
| // Desabilita este comando em qualquer outro ambiante que não seja desenvolvimento | ||
| if (process.env.NODE_ENV === 'production') { | ||
| return Promise.reject(new Error('Você não pode executar o dropDatabase neste ambiente')) | ||
| } | ||
|
|
||
| // Pega todas as tabelas no nosso banco de dados | ||
| const result = yield knex.raw('SHOW TABLES;') | ||
| const tables = result[0].map(table => table[Object.keys(table)[0]]) | ||
|
|
||
| yield knex.transaction(co.wrap(function * (trx) { | ||
| yield knex.raw('SET FOREIGN_KEY_CHECKS = 0;') | ||
| yield Promise.all(tables.map(table => knex.raw(`DROP TABLE ${table};`))) | ||
| yield knex.raw('SET FOREIGN_KEY_CHECKS = 1;') | ||
| })) | ||
| }) | ||
| } | ||
| /* $lab:coverage:on$ */ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| const cookieSession = require('cookie-session') | ||
|
|
||
| /** | ||
| * Um middleware para checagem de sessão | ||
| * @param {Object} [config] Configurações da sessão | ||
| * @param {Boolean} [config.restrict=true] Deixar que apenas usuários logados | ||
| * acessem o handler | ||
| * @return {Function} Uma função que serve de middleware | ||
| */ | ||
| module.exports = (config = { | ||
| restrict: true | ||
| }) => { | ||
| const session = cookieSession({ | ||
| name: 'session', | ||
| keys: [process.env.COOKIE_SECRET], | ||
| maxAge: 7 * 24 * 60 * 60 * 1000, // Uma semana | ||
| secure: process.env.NODE_ENV === 'production', | ||
| httpOnly: true, | ||
| signed: true, | ||
| overwrite: true | ||
| }) | ||
|
|
||
| return (req, res, next) => { | ||
| // Checa a sessão utilizando o middleware cookie-session | ||
| session(req, res, err => { | ||
| if (err) { | ||
| return next(err) | ||
| } | ||
|
|
||
| // Caso o acesso seja restrito à usuários logados precisamos verificar | ||
| // se a sessão foi lida com sucesso | ||
| if ((!req.session || !req.session.user_id) && config.restrict) { | ||
| return res.status(401).send({ error: 'Unauthorized' }) | ||
| } | ||
|
|
||
| // Tudo sob controle, podemos executar o handler | ||
| next() | ||
| }) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| const Boom = require('boom') | ||
|
|
||
| const db = require('../../lib/db') | ||
| const User = db.model('User') | ||
|
|
||
| exports.create = function * (req, res) { | ||
| // Verifica se o usuário já está logado | ||
| if (req.session && req.session.user_id) { | ||
| throw Boom.badData('Você já está logado') | ||
| } | ||
|
|
||
| // Pega no banco de dados o usuário que precisamos | ||
| const user = yield User.findOne({ username: req.body.username }) | ||
| .catch(User.NotFoundError, () => { | ||
| throw Boom.badData('Não foi possível encontrar o usuário') | ||
| }) | ||
|
|
||
| // Verifica se a senha está ok | ||
| if (!(yield user.compare(req.body.password))) { | ||
| throw Boom.badData('Sua senha está incorreta') | ||
| } | ||
|
|
||
| // Seta a sessão e retorna sucesso | ||
| req.session.user_id = user.id | ||
| res.send({ success: true }) | ||
| } | ||
|
|
||
| exports.findOne = (req, res) => { | ||
| User.findById(req.session.user_id) | ||
| .then((user) => res.send(user)) | ||
| } | ||
|
|
||
| exports.remove = (req, res) => { | ||
| req.session = null | ||
| res.send({ success: true }) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| const router = require('express').Router() | ||
|
|
||
| const handlers = require('./handlers') | ||
| const schemas = require('./schemas') | ||
| const validator = require('../../lib/validator') | ||
| const session = require('../../lib/session') | ||
| const asyncHandler = require('../../lib/async-handler') | ||
| const bodyParser = require('body-parser') | ||
|
|
||
| router.post('/sessions', | ||
| session({ restrict: false }), | ||
| bodyParser.json(), | ||
| validator({ body: schemas.create }), | ||
| asyncHandler(handlers.create)) | ||
|
|
||
| router.get('/sessions', | ||
| session(), | ||
| handlers.findOne) | ||
|
|
||
| router.delete('/sessions', | ||
| session(), | ||
| handlers.remove) | ||
|
|
||
| module.exports = router |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| const Joi = require('joi') | ||
|
|
||
| exports.create = Joi.object({ | ||
| username: Joi.string().token().min(3).max(20).required(), | ||
| password: Joi.string().min(8).max(120).required() | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| const db = require('../lib/db') | ||
|
|
||
| db.dropDatabase() | ||
| .then(() => process.exit(0)) | ||
| .catch(err => { | ||
| console.error(err.stack) | ||
| process.exit(1) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| const server = require('../../lib/server') | ||
| const request = require('supertest') | ||
|
|
||
| /** | ||
| * Cria um cookie compatível com a header Cookie para ser usado com o supertest | ||
| * @param {String} username O nome do usuário | ||
| * @param {String} password A senha do usuário | ||
| * @return {Promise} Uma promise que resolve com o cookie de autenticação | ||
| */ | ||
| exports.cookie = (username, password) => request(server) | ||
| .post('/sessions') | ||
| .send({ username, password }) | ||
| .then(res => res.header['set-cookie'] | ||
| .map(e => e.split(';')[0]) | ||
| .join(';')) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Acho que faz mais sentido checar se não tem password e devolver um throw. Dai estar a sessão caso tudo esteja correto e seguir a vida.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@thebergamo não entendi
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Tipo isso ^