Skip to content
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

Feature/change password #10

Open
wants to merge 6 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions controller/accountController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
require('dotenv').config({
path: '../config/.env'
});
const User = require('../models/user');
const httpStatus = require('http-status-codes');
const statusMsg = require('../config/statusMsg');
const bcrypt = require('bcrypt');
const { validationResult } = require('express-validator/check');

const errorJson = {
"success": statusMsg.fail.msg,
"payload": {},
"error": {
"code": httpStatus.UNPROCESSABLE_ENTITY
}
}

exports.changePassword = async(req, res, next) => {
const errors = validationResult(req)
if (!errors.isEmpty()) {
errorJson.error.message = errors.array();
return res.status(httpStatus.UNPROCESSABLE_ENTITY).json(errorJson);
} else {
try {
const account = await User.findOne({
email: res.locals.email
});

passwordMatch = account.password?
await bcrypt.compare(req.body.current_password, account.password): //compare only if password already exists in the db
true;

if (passwordMatch) {
const newPassword = await bcrypt.hash(req.body.new_password, Number(process.env.SALTING));
account.password = newPassword;
await account.save();
return res.status(httpStatus.OK).json({
success: statusMsg.success.msg,
payload: {}
});
} else {
errorJson.error.message = 'Incorrect password';
return res.status(httpStatus.UNPROCESSABLE_ENTITY).json(errorJson);
}
} catch (error) {
console.log(error);
error.status = httpStatus.INTERNAL_SERVER_ERROR;
next(error);
}
}
}
11 changes: 6 additions & 5 deletions controller/loginController.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,11 +102,12 @@ exports.refreshToken = async (req, res, next) => {

exports.logout = async (req, res, next) => {
try {
let user = await User.findOne({ refresh_token: req.body.refresh_token })
let decoded = await jwt.verify(req.token, secretKey.token.key)
if (decoded) {
await user.refresh_token.pull(req.body.refresh_token)
await user.save()
if (res.locals.email) {
let user = await User.findOne({
email: res.locals.email
})
await user.refresh_token.pull(req.body.refresh_token)
await user.save()
}
res.status(http.OK).json({
"success": statusMsg.success.msg,
Expand Down
6 changes: 5 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
const express = require('express')
const app = express()
const signup = require('../mentors/routes/signUpRoute')
const account = require('../mentors/routes/account')
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
const dotenv = require('dotenv')
const cors = require('cors')
const morgan = require('morgan')
const errorHandler = require('./middleware/errorHandler')
const methodOverride = require('method-override')
const jwtValidate = require('./middleware/jwtValidation')

dotenv.config({
path: './config/.env'
Expand All @@ -22,9 +25,10 @@ app.get('/', (req, res) => {
res.json({ msg: "HELLO MENTORS" })
})


app.use(methodOverride('X-HTTP-Method-Override'))
app.use(bodyParser.json())
app.use(cors())
app.use(morgan('combined'))
app.use('/v1/mentors/', signup)
app.use('/v1/account/', jwtValidate.verifyToken, account)
app.use(errorHandler.errorHandler)
4 changes: 2 additions & 2 deletions middleware/errorHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ exports.errorHandler = (err, req, res, next) => {
"payload": "",
"error": {
"code": http.FORBIDDEN,
"message": statusMsg.error.msg
"message": http.getStatusText(http.FORBIDDEN)
}
})
}
Expand All @@ -48,7 +48,7 @@ exports.errorHandler = (err, req, res, next) => {
"payload": "",
"error": {
"code": http.INTERNAL_SERVER_ERROR,
"message": statusMsg.error.msg
"message": http.getStatusText(http.INTERNAL_SERVER_ERROR)
}
})
}
Expand Down
28 changes: 22 additions & 6 deletions middleware/jwtValidation.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,25 @@
const jwt = require('jsonwebtoken');
const httpStatus = require('http-status-codes');
const secret = require('../config/secretKey');

exports.verifyToken = (req, res, next) => {
const bearerHeader = req.headers['authorization'];
if (typeof bearerHeader !== 'undefined') {
const bearer = bearerHeader.split(' ');
const bearerToken = bearer[1];
req.token = bearerToken;
next();
let token = req.headers['authorization'];
if (token) {
if (token.startsWith('Bearer')) {
token = token.split(' ')[1];
}
jwt.verify(token, secret.token.key, (error, decoded) => {
if (error) {
error.status = httpStatus.UNAUTHORIZED;
next(error);
} else {
res.locals.email = decoded.email;
next();
}
});
} else {
error = Error("A valid bearer token must be sent in the header.");
error.status = httpStatus.UNAUTHORIZED;
next(error);
}
}
14 changes: 14 additions & 0 deletions middleware/passwordValidation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const { body } = require('express-validator/check');

module.exports.validate = () => {
return [
body('new_password', 'Password field should not be empty').not().isEmpty(),
body('new_password', 'New password is not strong enough.').matches('^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})'),
body('new_password').custom((value, { req }) => {
if (value !== req.body.confirmation_password) {
throw new Error('Password confirmation does not match');
}
return true;
})
]
};
62 changes: 51 additions & 11 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"express-validator": "^5.3.1",
"http-status-codes": "^1.3.2",
"jsonwebtoken": "^8.5.1",
"method-override": "^3.0.0",
"mongo": "^0.1.0",
"mongoose": "^5.5.7",
"morgan": "^1.9.1",
Expand Down
12 changes: 12 additions & 0 deletions routes/account.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const router = require('express').Router();
const express = require('express');
const account = require('../controller/accountController');
const password = require('../middleware/passwordValidation');
const expressValidator = require('express-validator');

const app = express();
app.use(expressValidator());

router.route('/password').put(password.validate(), account.changePassword);

module.exports = router;