From cfcabe048201ade03e1d3bb49ea030655d7a594a Mon Sep 17 00:00:00 2001 From: Vipul Chaudhary Date: Tue, 4 Jun 2019 16:02:13 +0545 Subject: [PATCH 1/6] Added route for changing password --- index.js | 6 +++++- routes/account.js | 6 ++++++ 2 files changed, 11 insertions(+), 1 deletion(-) create mode 100644 routes/account.js diff --git a/index.js b/index.js index 1964125..efa4730 100644 --- a/index.js +++ b/index.js @@ -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' @@ -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) diff --git a/routes/account.js b/routes/account.js new file mode 100644 index 0000000..9d595ab --- /dev/null +++ b/routes/account.js @@ -0,0 +1,6 @@ +const router = require('express').Router(); +const account = require('../controller/accountController'); + +router.put('/password', account.changePassword); + +module.exports = router; \ No newline at end of file From 4206d74d5c8e58f3d5cbb3100ad269457e040dd7 Mon Sep 17 00:00:00 2001 From: Vipul Chaudhary Date: Tue, 4 Jun 2019 16:02:40 +0545 Subject: [PATCH 2/6] Added route for changing password --- package-lock.json | 62 ++++++++++++++++++++++++++++++++++++++--------- package.json | 1 + 2 files changed, 52 insertions(+), 11 deletions(-) diff --git a/package-lock.json b/package-lock.json index e38f1e3..f2c9c18 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1580,7 +1580,8 @@ }, "ansi-regex": { "version": "2.1.1", - "bundled": true + "bundled": true, + "optional": true }, "aproba": { "version": "1.2.0", @@ -1598,11 +1599,13 @@ }, "balanced-match": { "version": "1.0.0", - "bundled": true + "bundled": true, + "optional": true }, "brace-expansion": { "version": "1.1.11", "bundled": true, + "optional": true, "requires": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -1615,15 +1618,18 @@ }, "code-point-at": { "version": "1.1.0", - "bundled": true + "bundled": true, + "optional": true }, "concat-map": { "version": "0.0.1", - "bundled": true + "bundled": true, + "optional": true }, "console-control-strings": { "version": "1.1.0", - "bundled": true + "bundled": true, + "optional": true }, "core-util-is": { "version": "1.0.2", @@ -1726,7 +1732,8 @@ }, "inherits": { "version": "2.0.3", - "bundled": true + "bundled": true, + "optional": true }, "ini": { "version": "1.3.5", @@ -1736,6 +1743,7 @@ "is-fullwidth-code-point": { "version": "1.0.0", "bundled": true, + "optional": true, "requires": { "number-is-nan": "^1.0.0" } @@ -1748,17 +1756,20 @@ "minimatch": { "version": "3.0.4", "bundled": true, + "optional": true, "requires": { "brace-expansion": "^1.1.7" } }, "minimist": { "version": "0.0.8", - "bundled": true + "bundled": true, + "optional": true }, "minipass": { "version": "2.3.5", "bundled": true, + "optional": true, "requires": { "safe-buffer": "^5.1.2", "yallist": "^3.0.0" @@ -1775,6 +1786,7 @@ "mkdirp": { "version": "0.5.1", "bundled": true, + "optional": true, "requires": { "minimist": "0.0.8" } @@ -1847,7 +1859,8 @@ }, "number-is-nan": { "version": "1.0.1", - "bundled": true + "bundled": true, + "optional": true }, "object-assign": { "version": "4.1.1", @@ -1857,6 +1870,7 @@ "once": { "version": "1.4.0", "bundled": true, + "optional": true, "requires": { "wrappy": "1" } @@ -1932,7 +1946,8 @@ }, "safe-buffer": { "version": "5.1.2", - "bundled": true + "bundled": true, + "optional": true }, "safer-buffer": { "version": "2.1.2", @@ -1962,6 +1977,7 @@ "string-width": { "version": "1.0.2", "bundled": true, + "optional": true, "requires": { "code-point-at": "^1.0.0", "is-fullwidth-code-point": "^1.0.0", @@ -1979,6 +1995,7 @@ "strip-ansi": { "version": "3.0.1", "bundled": true, + "optional": true, "requires": { "ansi-regex": "^2.0.0" } @@ -2017,11 +2034,13 @@ }, "wrappy": { "version": "1.0.2", - "bundled": true + "bundled": true, + "optional": true }, "yallist": { "version": "3.0.3", - "bundled": true + "bundled": true, + "optional": true } } }, @@ -3005,6 +3024,27 @@ } } }, + "method-override": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/method-override/-/method-override-3.0.0.tgz", + "integrity": "sha512-IJ2NNN/mSl9w3kzWB92rcdHpz+HjkxhDJWNDBqSlas+zQdP8wBiJzITPg08M/k2uVvMow7Sk41atndNtt/PHSA==", + "requires": { + "debug": "3.1.0", + "methods": "~1.1.2", + "parseurl": "~1.3.2", + "vary": "~1.1.2" + }, + "dependencies": { + "debug": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", + "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", + "requires": { + "ms": "2.0.0" + } + } + } + }, "methods": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", diff --git a/package.json b/package.json index 0fcd679..0577e48 100644 --- a/package.json +++ b/package.json @@ -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", From 16d9b5a7b99d61f54ce553b5126863696f3d935e Mon Sep 17 00:00:00 2001 From: Vipul Chaudhary Date: Tue, 4 Jun 2019 16:04:02 +0545 Subject: [PATCH 3/6] feat: verify jwt token --- middleware/jwtValidation.js | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/middleware/jwtValidation.js b/middleware/jwtValidation.js index 948fcb7..29874db 100644 --- a/middleware/jwtValidation.js +++ b/middleware/jwtValidation.js @@ -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); } } \ No newline at end of file From ed01f6749ce7c43858ecbdce11c44535f7e79957 Mon Sep 17 00:00:00 2001 From: Vipul Chaudhary Date: Wed, 5 Jun 2019 13:03:22 +0545 Subject: [PATCH 4/6] fix: changed logout function as per new jwt verificationfunction --- controller/loginController.js | 11 ++++++----- routes/account.js | 8 +++++++- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/controller/loginController.js b/controller/loginController.js index 0a78bea..d22ac94 100644 --- a/controller/loginController.js +++ b/controller/loginController.js @@ -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, diff --git a/routes/account.js b/routes/account.js index 9d595ab..e53ebd7 100644 --- a/routes/account.js +++ b/routes/account.js @@ -1,6 +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'); -router.put('/password', account.changePassword); +const app = express(); +app.use(expressValidator()); + +router.put('/password', password.validate(), account.changePassword); module.exports = router; \ No newline at end of file From c4b8bd3c2234737cac4307244bba007aa53aab7f Mon Sep 17 00:00:00 2001 From: Vipul Chaudhary Date: Wed, 5 Jun 2019 22:51:00 +0545 Subject: [PATCH 5/6] feat: password change --- controller/accountController.js | 51 ++++++++++++++++++++++++++++++++ middleware/errorHandler.js | 4 +-- middleware/passwordValidation.js | 17 +++++++++++ routes/account.js | 2 +- 4 files changed, 71 insertions(+), 3 deletions(-) create mode 100644 controller/accountController.js create mode 100644 middleware/passwordValidation.js diff --git a/controller/accountController.js b/controller/accountController.js new file mode 100644 index 0000000..678c558 --- /dev/null +++ b/controller/accountController.js @@ -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); + } + } +} \ No newline at end of file diff --git a/middleware/errorHandler.js b/middleware/errorHandler.js index f30d12e..c08953c 100644 --- a/middleware/errorHandler.js +++ b/middleware/errorHandler.js @@ -38,7 +38,7 @@ exports.errorHandler = (err, req, res, next) => { "payload": "", "error": { "code": http.FORBIDDEN, - "message": statusMsg.error.msg + "message": http.getStatusText(http.FORBIDDEN) } }) } @@ -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) } }) } diff --git a/middleware/passwordValidation.js b/middleware/passwordValidation.js new file mode 100644 index 0000000..c5fc113 --- /dev/null +++ b/middleware/passwordValidation.js @@ -0,0 +1,17 @@ +const { body } = require('express-validator/check'); +const User = require('../models/user'); +const SALTING = 10; +const bcrypt = require('bcrypt'); + +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; + }) + ] +}; \ No newline at end of file diff --git a/routes/account.js b/routes/account.js index e53ebd7..493d92d 100644 --- a/routes/account.js +++ b/routes/account.js @@ -7,6 +7,6 @@ const expressValidator = require('express-validator'); const app = express(); app.use(expressValidator()); -router.put('/password', password.validate(), account.changePassword); +router.route('/password').put(password.validate(), account.changePassword); module.exports = router; \ No newline at end of file From 36596d709c19f8658cd9d8c83cadee816351861f Mon Sep 17 00:00:00 2001 From: Vipul Chaudhary Date: Thu, 6 Jun 2019 11:04:22 +0545 Subject: [PATCH 6/6] fix: removed unnecessary modules --- middleware/passwordValidation.js | 3 --- 1 file changed, 3 deletions(-) diff --git a/middleware/passwordValidation.js b/middleware/passwordValidation.js index c5fc113..6ec1d02 100644 --- a/middleware/passwordValidation.js +++ b/middleware/passwordValidation.js @@ -1,7 +1,4 @@ const { body } = require('express-validator/check'); -const User = require('../models/user'); -const SALTING = 10; -const bcrypt = require('bcrypt'); module.exports.validate = () => { return [