Skip to content

Commit 39bd446

Browse files
Merge pull request #9 from Bubbles-Org/ISSUE8-FEATURE
Adicionando autenticação de usuário
2 parents 2164e29 + 9f18f93 commit 39bd446

10 files changed

+107
-53
lines changed

.env.example

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# Authentication
2+
3+
JWT_SECRET=
4+
JWT_EXPIRATION_DAYS=7

app/config/enviroment.js

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
require('dotenv').config();
2+
3+
const environment = {
4+
development: {
5+
JWT: {
6+
secret: process.env.JWT_SECRET,
7+
expiration_days: process.env.JWT_EXPIRATION_DAYS
8+
}
9+
},
10+
11+
staging: {
12+
JWT: {
13+
secret: process.env.JWT_SECRET,
14+
expiration_days: process.env.JWT_EXPIRATION_DAYS
15+
}
16+
},
17+
18+
production: {
19+
JWT: {
20+
secret: process.env.JWT_SECRET,
21+
expiration_days: process.env.JWT_EXPIRATION_DAYS
22+
}
23+
}
24+
}
25+
26+
module.exports = environment[process.env.NODE_ENV || 'development'];

app/controllers/auth.controller.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,10 @@ const login = async (req, res) => {
99
log.info('Iniciando login', { email });
1010

1111
const result = await service.login(email, password);
12-
if (!result)
12+
if (!result){
1313
return http.notFound(res, 'E-mail ou senha inválido(a)');
14-
14+
}
15+
1516
log.info('Login finalizado', { email });
1617

1718
const { user, token } = result;

app/controllers/user.controller.js

+13-13
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ const create = async (req,res) => {
88

99
const data = req.body;
1010
const email = data.email;
11+
const password = data.password;
1112
/* Dá erro aqui, investigar
1213
const user = await UserService.findByEmail(email)
1314
.then(userData => {
@@ -16,10 +17,12 @@ const create = async (req,res) => {
1617
}
1718
})
1819
*/
20+
1921
const createdUser = await UserService.create(data)
2022
.then(userData => {
2123
return http.ok(res,userData);
2224
});
25+
2326
return createdUser;
2427

2528
} catch (error) {
@@ -34,14 +37,13 @@ const get = async (req,res) => {
3437

3538
const id = req.params.id;
3639

37-
const user = await UserService.get(id)
38-
.then(userData => {
39-
if(!userData){
40-
return http.notFound(res, "Nenhum usuário encontrado");
41-
}
42-
return http.ok(res,userData);
43-
});
44-
return user;
40+
const user = await UserService.get(id);
41+
42+
if(!user){
43+
return http.notFound(res, "Usuário não encontrado");
44+
}
45+
46+
return http.ok(res, user);
4547
} catch(error){
4648
log.error("Erro obter usuário", req.originalUrl, error);
4749
http.internalServerError(res);
@@ -52,11 +54,9 @@ const getAll = async (req,res) => {
5254
try {
5355
log.info("Iniciando obtenção de todos os usuários");
5456

55-
const user = await UserService.getAll()
56-
.then(userData => {
57-
return http.ok(res,userData);
58-
});
59-
return user;
57+
const user = await UserService.getAll();
58+
59+
return http.ok(res, user);
6060
} catch(error){
6161
log.error("Erro obter usuários", req.originalUrl, error);
6262
http.internalServerError(res);

app/models/user.model.js

+32-22
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,38 @@
11
const bcrypt = require('bcryptjs');
2+
const config = require('../config/enviroment');
23
const jwt = require('jsonwebtoken');
4+
const mongoose = require('mongoose');
5+
const { Schema } = require('mongoose');
36
const { getDateTime } = require('../services/util.service');
7+
const SALT_WORK_FACTOR = 10;
48

5-
module.exports = mongoose => {
6-
const User = mongoose.model(
7-
"user",
8-
mongoose.Schema(
9-
{
10-
name: String,
11-
email: String,
12-
password: String
13-
},
14-
{ timestamps: true }
15-
)
16-
);
17-
18-
User.prototype.checkPassword = function (password) {
19-
return bcrypt.compare(password, this.passwordHash);
20-
}
9+
const UserSchema = new Schema({
10+
name: String,
11+
email: String,
12+
password: String
13+
});
14+
15+
16+
UserSchema.pre('save', async function save(next) {
17+
if (!this.isModified('password')) return next();
18+
try {
19+
const salt = await bcrypt.genSalt(SALT_WORK_FACTOR);
20+
this.password = await bcrypt.hash(this.password, salt);
21+
return next();
22+
} catch (err) {
23+
return next(err);
24+
}
25+
});
2126

22-
User.prototype.generateAuthToken = function () {
23-
const { secret, expiration_days } = config.JWT;
24-
return jwt.sign({ id: this.id }, secret, { expiresIn: `${expiration_days}d` });
25-
}
27+
UserSchema.methods.validatePassword = async function validatePassword(data) {
28+
return await bcrypt.compareSync(data, this.password);
29+
};
2630

27-
return User;
28-
};
31+
UserSchema.methods.generateAuthToken = function () {
32+
const { secret, expiration_days } = config.JWT;
33+
return jwt.sign({ id: this.id }, secret, { expiresIn: `${expiration_days}d` });
34+
}
35+
36+
const model = mongoose.model('User', UserSchema);
37+
38+
module.exports = model;

app/services/auth.service.js

+17-9
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,32 @@
1-
const { User } = require('../models');
1+
const UserService = require('../services/user.service');
2+
const User = require("../models/user.model");
23

3-
async function login(email, password) {
4+
async function login(mail, password) {
45
try {
5-
const user = await User.find({},{ email });
6-
if (!user)
6+
let token = null;
7+
const user = await User.findOne({ email: mail });
8+
9+
if (!user){
710
return null;
11+
}
812

9-
const validPassword = await user.checkPassword(password);
10-
if (!validPassword)
13+
const validPassword = await user.validatePassword(password);
14+
console.log(validPassword);
15+
if (!validPassword){
1116
return null;
17+
}
1218

13-
const {id, name, email} = user;
19+
token = user.generateAuthToken();
20+
21+
const {_id, name, email} = user;
1422

1523
return {
1624
user: {
17-
id,
25+
_id,
1826
name,
1927
email,
2028
},
21-
token: user.generateAuthToken()
29+
token: token
2230
};
2331
} catch (error) {
2432
throw error;

app/services/user.service.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
const db = require("../models");
2-
const User = db.user;
2+
const User = require("../models/user.model");
33

44
async function create(data){
55
try {
@@ -32,7 +32,7 @@ async function get(id){
3232
const user = await User.findById(id);
3333

3434
if(!user){
35-
return null
35+
return null;
3636
}
3737

3838
return user

package-lock.json

+5
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

+1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
"bcryptjs": "^2.4.3",
2222
"body-parser": "^1.19.0",
2323
"cors": "^2.8.5",
24+
"dotenv": "^8.2.0",
2425
"express": "^4.17.1",
2526
"express-validator": "^6.6.1",
2627
"jsonwebtoken": "^8.5.1",

routes.js

+4-5
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,19 @@
11
const express = require("express");
22
const router = express.Router();
33

4-
//const authMiddleware = require('./app/middlewares/auth');
5-
6-
//const auth = require('./app/routes/auth.route');
4+
const authMiddleware = require('./app/middlewares/auth');
75

6+
const auth = require('./app/routes/auth.route');
87
const user = require('./app/routes/user.route');
98

109
router.get('/', (req, res) => {
1110
return res.send('Bubbles API');
1211
});
1312

1413
router.use('/user', user);
15-
14+
router.use('/auth', auth);
1615
// Private routes
17-
//router.use(authMiddleware);
16+
router.use(authMiddleware);
1817

1918

2019

0 commit comments

Comments
 (0)