Skip to content

Commit 85c6738

Browse files
feat(produtos): implementado rotas restantes e autenticação
1 parent 00352a8 commit 85c6738

File tree

9 files changed

+125
-128
lines changed

9 files changed

+125
-128
lines changed

src/controllers/auth-controller.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
'use strict'
2+
3+
const authService = require('../services/auth-service')
4+
const constant = require('../utils/constants')
5+
const usuariosService = require('../services/usuarios-service')
6+
const { tokenValido } = require('../utils/authentication')
7+
8+
exports.checkAdm = async (req, res, next) => {
9+
try {
10+
if (!tokenValido(req.headers)) {
11+
return res.status(401).send({ message: constant.TOKEN_INVALID })
12+
}
13+
const tokenDecodificado = authService.verifyToken(req.headers.authorization)
14+
if (!await usuariosService.usuarioEhAdministrador(tokenDecodificado)) {
15+
return res.status(403).send({ message: constant.NECESSARIO_ADM })
16+
}
17+
next()
18+
} catch (error) {
19+
res.status(500).send({ message: constant.INTERNAL_ERROR, error })
20+
}
21+
}

src/controllers/produtos-controller.js

Lines changed: 27 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -13,35 +13,33 @@ exports.get = async (req, res) => {
1313
}
1414

1515
exports.post = async (req, res) => {
16-
console.log(req.body)
17-
18-
// try {
19-
// if (await service.existeUsuarioComEsseEmail(req.body.email)) {
20-
// return res.status(400).send({ message: EMAIL_JA_USADO })
21-
// }
22-
// const dadosCadastrados = await service.createUser(req.body)
23-
res.status(201).send({ message: constant.POST_SUCESS })
24-
// } catch (error) {
25-
// res.status(500).send({ message: constant.INTERNAL_ERROR, error })
26-
// }
16+
try {
17+
if (await service.existeProdutoComEsseNome(req.body.nome)) {
18+
return res.status(400).send({ message: constant.NOME_JA_USADO })
19+
}
20+
const dadosCadastrados = await service.criarProduto(req.body)
21+
res.status(201).send({ message: constant.POST_SUCESS, _id: dadosCadastrados._id })
22+
} catch (error) {
23+
res.status(500).send({ message: constant.INTERNAL_ERROR, error })
24+
}
2725
}
2826

29-
// exports.delete = async (req, res) => {
30-
// try {
31-
// const quantidadeRegistrosExcluidos = await service.deleteById(req.params.id)
32-
// const message = quantidadeRegistrosExcluidos === 0 ? constant.DELETE_NONE : constant.DELETE_SUCESS
33-
// res.status(200).send({ message })
34-
// } catch (error) {
35-
// res.status(500).send({ message: constant.INTERNAL_ERROR, error })
36-
// }
37-
// }
27+
exports.delete = async (req, res) => {
28+
try {
29+
const quantidadeRegistrosExcluidos = await service.deleteById(req.params.id)
30+
const message = quantidadeRegistrosExcluidos === 0 ? constant.DELETE_NONE : constant.DELETE_SUCESS
31+
res.status(200).send({ message })
32+
} catch (error) {
33+
res.status(500).send({ message: constant.INTERNAL_ERROR, error })
34+
}
35+
}
3836

39-
// exports.put = async (req, res) => {
40-
// try {
41-
// const registroCriado = await service.createOrUpdateById(req.params.id, req.body)
42-
// if (registroCriado) { return res.status(201).send({ message: constant.POST_SUCESS, _id: registroCriado._id }) }
43-
// res.status(200).send({ message: constant.PUT_SUCESS })
44-
// } catch (error) {
45-
// res.status(500).send({ message: constant.INTERNAL_ERROR, error })
46-
// }
47-
// }
37+
exports.put = async (req, res) => {
38+
try {
39+
const registroCriado = await service.createOrUpdateById(req.params.id, req.body)
40+
if (registroCriado) { return res.status(201).send({ message: constant.POST_SUCESS, _id: registroCriado._id }) }
41+
res.status(200).send({ message: constant.PUT_SUCESS })
42+
} catch (error) {
43+
res.status(500).send({ message: constant.INTERNAL_ERROR, error })
44+
}
45+
}

src/routes/produtos-route.js

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,15 @@
22

33
const express = require('express')
44

5+
const authController = require('../controllers/auth-controller')
56
const controller = require('../controllers/produtos-controller')
67
const model = require('../models/produtos-model')
78
const validateSchema = require('../services/validateSchema-service')
89

910
const router = express.Router()
1011
router.get('/', validateSchema(model.schemaGet), controller.get)
11-
router.post('/', validateSchema(model.schemaPost), controller.post)
12-
// router.delete('/:id', validateSchema(model.schemaDelete), controller.delete)
13-
// router.put('/:id', validateSchema(model.schemaPut), controller.put)
12+
router.post('/', authController.checkAdm, validateSchema(model.schemaPost), controller.post)
13+
router.delete('/:id', authController.checkAdm, validateSchema(model.schemaDelete), controller.delete)
14+
router.put('/:id', authController.checkAdm, validateSchema(model.schemaPut), controller.put)
1415

1516
module.exports = router

src/services/auth-service.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,11 @@ function createToken (emailSenha) {
88
return jwt.sign(emailSenha, PRIVATE_KEY, { noTimestamp: true }, { expiresIn: '1000ms' })
99
}
1010

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

1515
module.exports = {
1616
createToken,
1717
verifyToken
18-
}
18+
}

src/services/produtos-service.js

Lines changed: 41 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -14,56 +14,48 @@ exports.getAll = queryString => {
1414
})
1515
}
1616

17-
// exports.existeUsuarioComEsseEmail = email => {
18-
// return new Promise((resolve, reject) => {
19-
// datastore.count({ email }, (err, count) => {
20-
// if (err) reject(err)
21-
// else resolve(count !== 0)
22-
// })
23-
// })
24-
// }
25-
26-
// exports.existeUsuarioComEsseEmailESenha = emailSenha => {
27-
// return new Promise((resolve, reject) => {
28-
// datastore.count(emailSenha, (err, count) => {
29-
// if (err) reject(err)
30-
// else resolve(count !== 0)
31-
// })
32-
// })
33-
// }
17+
exports.existeProdutoComEsseNome = nome => {
18+
nome = nome.trim()
19+
return new Promise((resolve, reject) => {
20+
datastore.count({ nome }, (err, count) => {
21+
if (err) reject(err)
22+
else resolve(count !== 0)
23+
})
24+
})
25+
}
3426

35-
// exports.createUser = async body => {
36-
// return new Promise((resolve, reject) => {
37-
// datastore.insert(body, (err, novoUsuario) => {
38-
// if (err) reject(err)
39-
// else resolve(novoUsuario)
40-
// })
41-
// })
42-
// }
27+
exports.criarProduto = async body => {
28+
body = formatarValores(body)
29+
return new Promise((resolve, reject) => {
30+
datastore.insert(body, (err, novoProduto) => {
31+
if (err) reject(err)
32+
else resolve(novoProduto)
33+
})
34+
})
35+
}
4336

44-
// exports.deleteById = async id => {
45-
// return new Promise((resolve, reject) => {
46-
// datastore.remove({ _id: id }, {}, (err, quantidadeRegistrosExcluidos) => {
47-
// if (err) reject(err)
48-
// else resolve(quantidadeRegistrosExcluidos)
49-
// })
50-
// })
51-
// }
37+
exports.deleteById = async id => {
38+
return new Promise((resolve, reject) => {
39+
datastore.remove({ _id: id }, {}, (err, quantidadeRegistrosExcluidos) => {
40+
if (err) reject(err)
41+
else resolve(quantidadeRegistrosExcluidos)
42+
})
43+
})
44+
}
5245

53-
// exports.existeRegistroComEsseID = _id => {
54-
// return new Promise((resolve, reject) => {
55-
// datastore.count({ _id }, (err, count) => {
56-
// if (err) reject(err)
57-
// else resolve(count !== 0)
58-
// })
59-
// })
60-
// }
46+
exports.createOrUpdateById = async (idDoUsuarioQueSeraAlterado, body) => {
47+
body = formatarValores(body)
48+
return new Promise((resolve, reject) => {
49+
datastore.update({ _id: idDoUsuarioQueSeraAlterado }, body, { upsert: true }, (err, quantidadeRegistrosAlterados, registroCriado) => {
50+
if (err) reject(err)
51+
else resolve(registroCriado)
52+
})
53+
})
54+
}
6155

62-
// exports.createOrUpdateById = async (idDoUsuarioQueSeraAlterado, body) => {
63-
// return new Promise((resolve, reject) => {
64-
// datastore.update({ _id: idDoUsuarioQueSeraAlterado }, body, { upsert: true }, (err, quantidadeRegistrosAlterados, registroCriado) => {
65-
// if (err) reject(err)
66-
// else resolve(registroCriado)
67-
// })
68-
// })
69-
// }
56+
function formatarValores (body) {
57+
body.nome = body.nome.trim()
58+
body.preco = parseInt(body.preco)
59+
body.quantidade = parseInt(body.quantidade)
60+
return body
61+
}

src/services/usuarios-service.js

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,15 @@ exports.existeUsuarioComEsseEmail = email => {
2323
})
2424
}
2525

26+
exports.usuarioEhAdministrador = ({ email, password }) => {
27+
return new Promise((resolve, reject) => {
28+
datastore.find({ email, password }, (err, resultado) => {
29+
if (err) reject(err)
30+
else resolve(JSON.parse(resultado[0].administrador))
31+
})
32+
})
33+
}
34+
2635
exports.existeUsuarioComEsseEmailESenha = emailSenha => {
2736
return new Promise((resolve, reject) => {
2837
datastore.count(emailSenha, (err, count) => {
@@ -50,15 +59,6 @@ exports.deleteById = async id => {
5059
})
5160
}
5261

53-
exports.existeRegistroComEsseID = _id => {
54-
return new Promise((resolve, reject) => {
55-
datastore.count({ _id }, (err, count) => {
56-
if (err) reject(err)
57-
else resolve(count !== 0)
58-
})
59-
})
60-
}
61-
6262
exports.createOrUpdateById = async (idDoUsuarioQueSeraAlterado, body) => {
6363
return new Promise((resolve, reject) => {
6464
datastore.update({ _id: idDoUsuarioQueSeraAlterado }, body, { upsert: true }, (err, quantidadeRegistrosAlterados, registroCriado) => {

src/utils/authentication.js

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,25 @@
11
'use strict'
22

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

5-
function autenticacao (req, res) {
6-
if (req.headers.authorization === undefined) {
7-
res.status(401).json({ message: 'Autenticação necessária' })
8-
return
9-
}
10-
if (req.headers.authorization.split(' ')[0] !== 'Bearer') {
11-
res.status(401).json({ message: 'Tipo de autenticação deve ser Bearer' })
12-
return
13-
}
14-
const token = req.headers.authorization.split(' ')[1]
15-
if (token === undefined) {
16-
res.status(401).json({ message: 'Token de acesso vazio' })
17-
return
5+
function tokenValido ({ authorization }) {
6+
if (authorization === undefined) return false
7+
8+
const semBearer = authorization.split(' ')[0] !== 'Bearer'
9+
const semToken = authorization.split(' ')[1] === undefined
10+
11+
if (semBearer || semToken) {
12+
return false
1813
}
19-
if (verifyToken(token) instanceof Error) {
20-
res.status(401).json({ message: 'Token de acesso não é válido' })
14+
15+
const tokenDecodificado = authService.verifyToken(authorization)
16+
if(tokenDecodificado.email === undefined || tokenDecodificado.password === undefined) {
17+
return false
2118
}
19+
20+
return true
2221
}
2322

2423
module.exports = {
25-
autenticacao
24+
tokenValido
2625
}

src/utils/constants.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,5 +8,8 @@ module.exports = {
88
PUT_SUCESS: 'Registro alterado com sucesso',
99
LOGIN_SUCESS: 'Login realizado com sucesso',
1010
LOGIN_FAIL: 'Email e/ou senha inválidos',
11-
EMAIL_JA_USADO: 'Este email já está sendo usado'
11+
EMAIL_JA_USADO: 'Este email já está sendo usado',
12+
NOME_JA_USADO: 'Já existe produto com esse nome',
13+
NECESSARIO_ADM: 'Rota exclusiva para administradores',
14+
TOKEN_INVALID: 'Token de acesso inválido'
1215
}

src/utils/token.js

Lines changed: 0 additions & 17 deletions
This file was deleted.

0 commit comments

Comments
 (0)