Skip to content

Commit

Permalink
feat(produtos): implementado rotas restantes e autenticação
Browse files Browse the repository at this point in the history
  • Loading branch information
PauloGoncalvesBH committed May 2, 2020
1 parent 00352a8 commit 85c6738
Show file tree
Hide file tree
Showing 9 changed files with 125 additions and 128 deletions.
21 changes: 21 additions & 0 deletions src/controllers/auth-controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
'use strict'

const authService = require('../services/auth-service')
const constant = require('../utils/constants')
const usuariosService = require('../services/usuarios-service')
const { tokenValido } = require('../utils/authentication')

exports.checkAdm = async (req, res, next) => {
try {
if (!tokenValido(req.headers)) {
return res.status(401).send({ message: constant.TOKEN_INVALID })
}
const tokenDecodificado = authService.verifyToken(req.headers.authorization)
if (!await usuariosService.usuarioEhAdministrador(tokenDecodificado)) {
return res.status(403).send({ message: constant.NECESSARIO_ADM })
}
next()
} catch (error) {
res.status(500).send({ message: constant.INTERNAL_ERROR, error })
}
}
56 changes: 27 additions & 29 deletions src/controllers/produtos-controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,35 +13,33 @@ exports.get = async (req, res) => {
}

exports.post = async (req, res) => {
console.log(req.body)

// try {
// if (await service.existeUsuarioComEsseEmail(req.body.email)) {
// return res.status(400).send({ message: EMAIL_JA_USADO })
// }
// const dadosCadastrados = await service.createUser(req.body)
res.status(201).send({ message: constant.POST_SUCESS })
// } catch (error) {
// res.status(500).send({ message: constant.INTERNAL_ERROR, error })
// }
try {
if (await service.existeProdutoComEsseNome(req.body.nome)) {
return res.status(400).send({ message: constant.NOME_JA_USADO })
}
const dadosCadastrados = await service.criarProduto(req.body)
res.status(201).send({ message: constant.POST_SUCESS, _id: dadosCadastrados._id })
} catch (error) {
res.status(500).send({ message: constant.INTERNAL_ERROR, error })
}
}

// exports.delete = async (req, res) => {
// try {
// const quantidadeRegistrosExcluidos = await service.deleteById(req.params.id)
// const message = quantidadeRegistrosExcluidos === 0 ? constant.DELETE_NONE : constant.DELETE_SUCESS
// res.status(200).send({ message })
// } catch (error) {
// res.status(500).send({ message: constant.INTERNAL_ERROR, error })
// }
// }
exports.delete = async (req, res) => {
try {
const quantidadeRegistrosExcluidos = await service.deleteById(req.params.id)
const message = quantidadeRegistrosExcluidos === 0 ? constant.DELETE_NONE : constant.DELETE_SUCESS
res.status(200).send({ message })
} catch (error) {
res.status(500).send({ message: constant.INTERNAL_ERROR, error })
}
}

// exports.put = async (req, res) => {
// try {
// const registroCriado = await service.createOrUpdateById(req.params.id, req.body)
// if (registroCriado) { return res.status(201).send({ message: constant.POST_SUCESS, _id: registroCriado._id }) }
// res.status(200).send({ message: constant.PUT_SUCESS })
// } catch (error) {
// res.status(500).send({ message: constant.INTERNAL_ERROR, error })
// }
// }
exports.put = async (req, res) => {
try {
const registroCriado = await service.createOrUpdateById(req.params.id, req.body)
if (registroCriado) { return res.status(201).send({ message: constant.POST_SUCESS, _id: registroCriado._id }) }
res.status(200).send({ message: constant.PUT_SUCESS })
} catch (error) {
res.status(500).send({ message: constant.INTERNAL_ERROR, error })
}
}
7 changes: 4 additions & 3 deletions src/routes/produtos-route.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@

const express = require('express')

const authController = require('../controllers/auth-controller')
const controller = require('../controllers/produtos-controller')
const model = require('../models/produtos-model')
const validateSchema = require('../services/validateSchema-service')

const router = express.Router()
router.get('/', validateSchema(model.schemaGet), controller.get)
router.post('/', validateSchema(model.schemaPost), controller.post)
// router.delete('/:id', validateSchema(model.schemaDelete), controller.delete)
// router.put('/:id', validateSchema(model.schemaPut), controller.put)
router.post('/', authController.checkAdm, validateSchema(model.schemaPost), controller.post)
router.delete('/:id', authController.checkAdm, validateSchema(model.schemaDelete), controller.delete)
router.put('/:id', authController.checkAdm, validateSchema(model.schemaPut), controller.put)

module.exports = router
6 changes: 3 additions & 3 deletions src/services/auth-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ function createToken (emailSenha) {
return jwt.sign(emailSenha, PRIVATE_KEY, { noTimestamp: true }, { expiresIn: '1000ms' })
}

function verifyToken (token) {
return jwt.verify(token, PRIVATE_KEY, (err, decode) => (decode !== undefined ? decode : err))
function verifyToken (authorization) {
return jwt.verify(authorization.split(' ')[1], PRIVATE_KEY, (err, decode) => (decode === undefined ? err : decode))
}

module.exports = {
createToken,
verifyToken
}
}
90 changes: 41 additions & 49 deletions src/services/produtos-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,56 +14,48 @@ exports.getAll = queryString => {
})
}

// exports.existeUsuarioComEsseEmail = email => {
// return new Promise((resolve, reject) => {
// datastore.count({ email }, (err, count) => {
// if (err) reject(err)
// else resolve(count !== 0)
// })
// })
// }

// exports.existeUsuarioComEsseEmailESenha = emailSenha => {
// return new Promise((resolve, reject) => {
// datastore.count(emailSenha, (err, count) => {
// if (err) reject(err)
// else resolve(count !== 0)
// })
// })
// }
exports.existeProdutoComEsseNome = nome => {
nome = nome.trim()
return new Promise((resolve, reject) => {
datastore.count({ nome }, (err, count) => {
if (err) reject(err)
else resolve(count !== 0)
})
})
}

// exports.createUser = async body => {
// return new Promise((resolve, reject) => {
// datastore.insert(body, (err, novoUsuario) => {
// if (err) reject(err)
// else resolve(novoUsuario)
// })
// })
// }
exports.criarProduto = async body => {
body = formatarValores(body)
return new Promise((resolve, reject) => {
datastore.insert(body, (err, novoProduto) => {
if (err) reject(err)
else resolve(novoProduto)
})
})
}

// exports.deleteById = async id => {
// return new Promise((resolve, reject) => {
// datastore.remove({ _id: id }, {}, (err, quantidadeRegistrosExcluidos) => {
// if (err) reject(err)
// else resolve(quantidadeRegistrosExcluidos)
// })
// })
// }
exports.deleteById = async id => {
return new Promise((resolve, reject) => {
datastore.remove({ _id: id }, {}, (err, quantidadeRegistrosExcluidos) => {
if (err) reject(err)
else resolve(quantidadeRegistrosExcluidos)
})
})
}

// exports.existeRegistroComEsseID = _id => {
// return new Promise((resolve, reject) => {
// datastore.count({ _id }, (err, count) => {
// if (err) reject(err)
// else resolve(count !== 0)
// })
// })
// }
exports.createOrUpdateById = async (idDoUsuarioQueSeraAlterado, body) => {
body = formatarValores(body)
return new Promise((resolve, reject) => {
datastore.update({ _id: idDoUsuarioQueSeraAlterado }, body, { upsert: true }, (err, quantidadeRegistrosAlterados, registroCriado) => {
if (err) reject(err)
else resolve(registroCriado)
})
})
}

// exports.createOrUpdateById = async (idDoUsuarioQueSeraAlterado, body) => {
// return new Promise((resolve, reject) => {
// datastore.update({ _id: idDoUsuarioQueSeraAlterado }, body, { upsert: true }, (err, quantidadeRegistrosAlterados, registroCriado) => {
// if (err) reject(err)
// else resolve(registroCriado)
// })
// })
// }
function formatarValores (body) {
body.nome = body.nome.trim()
body.preco = parseInt(body.preco)
body.quantidade = parseInt(body.quantidade)
return body
}
18 changes: 9 additions & 9 deletions src/services/usuarios-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,15 @@ exports.existeUsuarioComEsseEmail = email => {
})
}

exports.usuarioEhAdministrador = ({ email, password }) => {
return new Promise((resolve, reject) => {
datastore.find({ email, password }, (err, resultado) => {
if (err) reject(err)
else resolve(JSON.parse(resultado[0].administrador))
})
})
}

exports.existeUsuarioComEsseEmailESenha = emailSenha => {
return new Promise((resolve, reject) => {
datastore.count(emailSenha, (err, count) => {
Expand Down Expand Up @@ -50,15 +59,6 @@ exports.deleteById = async id => {
})
}

exports.existeRegistroComEsseID = _id => {
return new Promise((resolve, reject) => {
datastore.count({ _id }, (err, count) => {
if (err) reject(err)
else resolve(count !== 0)
})
})
}

exports.createOrUpdateById = async (idDoUsuarioQueSeraAlterado, body) => {
return new Promise((resolve, reject) => {
datastore.update({ _id: idDoUsuarioQueSeraAlterado }, body, { upsert: true }, (err, quantidadeRegistrosAlterados, registroCriado) => {
Expand Down
33 changes: 16 additions & 17 deletions src/utils/authentication.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,25 @@
'use strict'

const { verifyToken } = require('./utils/token.js')
const authService = require('../services/auth-service')

function autenticacao (req, res) {
if (req.headers.authorization === undefined) {
res.status(401).json({ message: 'Autenticação necessária' })
return
}
if (req.headers.authorization.split(' ')[0] !== 'Bearer') {
res.status(401).json({ message: 'Tipo de autenticação deve ser Bearer' })
return
}
const token = req.headers.authorization.split(' ')[1]
if (token === undefined) {
res.status(401).json({ message: 'Token de acesso vazio' })
return
function tokenValido ({ authorization }) {
if (authorization === undefined) return false

const semBearer = authorization.split(' ')[0] !== 'Bearer'
const semToken = authorization.split(' ')[1] === undefined

if (semBearer || semToken) {
return false
}
if (verifyToken(token) instanceof Error) {
res.status(401).json({ message: 'Token de acesso não é válido' })

const tokenDecodificado = authService.verifyToken(authorization)
if(tokenDecodificado.email === undefined || tokenDecodificado.password === undefined) {
return false
}

return true
}

module.exports = {
autenticacao
tokenValido
}
5 changes: 4 additions & 1 deletion src/utils/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,8 @@ module.exports = {
PUT_SUCESS: 'Registro alterado com sucesso',
LOGIN_SUCESS: 'Login realizado com sucesso',
LOGIN_FAIL: 'Email e/ou senha inválidos',
EMAIL_JA_USADO: 'Este email já está sendo usado'
EMAIL_JA_USADO: 'Este email já está sendo usado',
NOME_JA_USADO: 'Já existe produto com esse nome',
NECESSARIO_ADM: 'Rota exclusiva para administradores',
TOKEN_INVALID: 'Token de acesso inválido'
}
17 changes: 0 additions & 17 deletions src/utils/token.js

This file was deleted.

0 comments on commit 85c6738

Please sign in to comment.