Skip to content

Commit 594ba05

Browse files
committed
Refactor Code
1 parent 457eacc commit 594ba05

File tree

7 files changed

+86
-56
lines changed

7 files changed

+86
-56
lines changed

controllers/auth.controller.js

Lines changed: 28 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,60 +1,53 @@
1-
const UserModel = require('../models/user.model');
1+
const AuthService = require('../services/auth.service');
22
const jwtConfig = require('../config/jwt.config');
3-
const cache = require('../utils/cache.util');
4-
const jwt = require('../utils/jwt.util');
5-
const bcrypt = require('bcrypt');
3+
const bcryptUtil = require('../utils/bcrypt.util');
4+
const jwtUtil = require('../utils/jwt.util');
65

7-
exports.register = async (req, res) => {
8-
const isExist = await UserModel.findOne({
9-
where:{
10-
email: req.body.email
11-
}
12-
})
6+
exports.register = async (req, res) => {
7+
const isExist = await AuthService.findUserByEmail(req.body.email);
138
if(isExist) {
14-
return res.status(400).json({ message: 'Email already exists.' });
9+
return res.status(400).json({
10+
message: 'Email already exists.'
11+
});
1512
}
16-
const hashedPassword = await bcrypt.hash(req.body.password, 10);
17-
18-
const user = await UserModel.create({
13+
const hashedPassword = await bcryptUtil.createHash(req.body.password);
14+
const userData = {
1915
name: req.body.name,
2016
email: req.body.email,
2117
password: hashedPassword
18+
}
19+
const user = await AuthService.createUser(userData);
20+
return res.json({
21+
data: user,
22+
message: 'User registered successfully.'
2223
});
23-
return res.json(user);
2424
}
2525

26-
exports.login = async (req, res) => {
27-
const user = await UserModel.findOne({
28-
where: {
29-
email: req.body.email
30-
}
31-
});
26+
exports.login = async (req, res) => {
27+
const user = await AuthService.findUserByEmail(req.body.email);
3228
if (user) {
33-
const isMatched = await bcrypt.compare(req.body.password, user.password);
29+
const isMatched = await bcryptUtil.compareHash(req.body.password, user.password);
3430
if (isMatched) {
35-
const token = await jwt.createToken({ id: user.id });
31+
const token = await jwtUtil.createToken({ id: user.id });
3632
return res.json({
3733
access_token: token,
3834
token_type: 'Bearer',
3935
expires_in: jwtConfig.ttl
4036
});
4137
}
4238
}
43-
return res.status(400).json({ message: 'Unauthorized' });
39+
return res.status(400).json({ message: 'Unauthorized.' });
4440
}
4541

4642
exports.getUser = async (req, res) => {
47-
const user = await UserModel.findByPk(req.user.id);
48-
return res.json(user);
43+
const user = await AuthService.findUserById(req.user.id);
44+
return res.json({
45+
data: user,
46+
message: 'Success.'
47+
});
4948
}
5049

51-
exports.logout = async (req, res) => {
52-
const token = req.token;
53-
const now = new Date();
54-
const expire = new Date(req.user.exp);
55-
const milliseconds = now.getTime() - expire.getTime();
56-
/* ----------------------------- BlackList Token ---------------------------- */
57-
await cache.set(token, token, milliseconds);
58-
59-
return res.json({ message: 'Logged out successfully' });
50+
exports.logout = async (req, res) => {
51+
await AuthService.logoutUser(req.token, req.user.exp);
52+
return res.json({ message: 'Logged out successfully.' });
6053
}

middleware/auth.middleware.js

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
const cache = require('../utils/cache.util');
2-
const jwt = require('../utils/jwt.util');
1+
const cacheUtil = require('../utils/cache.util');
2+
const jwtUtil = require('../utils/jwt.util');
33

44
module.exports = async (req, res, next) => {
5-
5+
66
let token = req.headers.authorization;
77
if (token && token.startsWith('Bearer ')) {
88
token = token.slice(7, token.length);
@@ -12,17 +12,16 @@ module.exports = async (req, res, next) => {
1212
try {
1313
token = token.trim();
1414
/* ---------------------- Check For Blacklisted Tokens ---------------------- */
15-
const isBlackListed = await cache.get(token);
15+
const isBlackListed = await cacheUtil.get(token);
1616
if (isBlackListed) {
1717
return res.status(401).json({ message: 'Unauthorized' });
1818
}
1919

20-
const decoded = await jwt.verifyToken(token);
20+
const decoded = await jwtUtil.verifyToken(token);
2121
req.user = decoded;
2222
req.token = token;
2323
next();
24-
25-
} catch (error) {
24+
} catch (error) {
2625
return res.status(401).json({ message: 'Unauthorized' });
2726
}
2827
} else {

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "node-mysql-jwt",
3-
"version": "1.1.0",
3+
"version": "2.0.0",
44
"private": true,
55
"scripts": {
66
"start": "node ./bin/www"

services/auth.service.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
const UserModel = require('../models/user.model');
2+
const cacheUtil = require('../utils/cache.util');
3+
4+
exports.createUser = (user) => {
5+
return UserModel.create(user);
6+
}
7+
8+
exports.findUserByEmail = (email) => {
9+
return UserModel.findOne({
10+
where: {
11+
email: email
12+
}
13+
})
14+
}
15+
16+
exports.findUserById = (id) => {
17+
return UserModel.findByPk(id);
18+
}
19+
20+
exports.logoutUser = (token, exp) => {
21+
const now = new Date();
22+
const expire = new Date(exp * 1000);
23+
const milliseconds = expire.getTime() - now.getTime();
24+
/* ----------------------------- BlackList Token ---------------------------- */
25+
return cacheUtil.set(token, token, milliseconds);
26+
}

utils/bcrypt.util.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
const bcrypt = require('bcrypt');
2+
3+
exports.compareHash = (plainPassword, hashedPassword) => bcrypt.compare(plainPassword, hashedPassword);
4+
5+
exports.createHash = (plainPassword) => bcrypt.hash(plainPassword, 10);

utils/validator.util.js

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
1-
module.exports = (schema) => (req, res, next) => {
1+
module.exports = (schema) => async (req, res, next) => {
22
if (schema) {
3-
const options = {
4-
errors: {
5-
wrap: { label: '' }
6-
},
7-
abortEarly: false
8-
}
9-
const result = schema.validate((req.method == 'GET' ? req.query : req.body), options);
10-
if (result.error) {
11-
const { details } = result.error;
12-
const message = details.length ? details[0].message : 'Invalid payload.'
13-
return res.status(400).json({ message });
3+
try {
4+
const options = {
5+
errors: {
6+
wrap: { label: '' }
7+
},
8+
abortEarly: true
9+
}
10+
const body = (req.method == 'GET') ? req.query : req.body;
11+
await schema.validateAsync(body, options);
12+
} catch (error) {
13+
return res.status(400).json({ message: error.message });
1414
}
1515
}
1616
next();

validatons/auth.validation.js

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,17 @@
11
const Joi = require('joi');
2+
const passwordRegex = new RegExp(/(?=.*\d)(?=.*[a-z])(?=.*[A-Z])/);
3+
4+
const validatePassword = (value, helper) => {
5+
if(!passwordRegex.test(String(value))) {
6+
throw new Error('Password should contains a lowercase, a uppercase character and a digit.')
7+
}
8+
}
29

310
module.exports = {
411
register: Joi.object().keys({
512
name: Joi.string().required(),
613
email: Joi.string().email().required(),
7-
password: Joi.string().required()
14+
password: Joi.string().min(8).max(16).required().external(validatePassword)
815
}),
916
login: Joi.object().keys({
1017
email: Joi.string().email().required(),

0 commit comments

Comments
 (0)