From 4b2285e4b3e0e6890cabdda6e7765c1aa43787d3 Mon Sep 17 00:00:00 2001 From: Divyanshu Rathore Date: Wed, 26 Sep 2018 00:05:34 +0530 Subject: [PATCH] Hash password before saving user --- package.json | 1 + server/middleware/authenticate.js | 2 +- server/models/user.js | 17 +++++++++++++++++ 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 3871ee5..9f38ce3 100644 --- a/package.json +++ b/package.json @@ -14,6 +14,7 @@ "author": "", "license": "ISC", "dependencies": { + "bcryptjs": "^2.4.3", "body-parser": "^1.18.3", "crypto-js": "^3.1.9-1", "expect": "^23.6.0", diff --git a/server/middleware/authenticate.js b/server/middleware/authenticate.js index 4a96c9a..df3d924 100644 --- a/server/middleware/authenticate.js +++ b/server/middleware/authenticate.js @@ -1,6 +1,6 @@ const { User } = require("./../models/user"); -var authenticate = (res, res, next) => { +var authenticate = (req, res, next) => { var token = req.header('x-auth'); User.findByToken(token).then((user) => { diff --git a/server/models/user.js b/server/models/user.js index b4935f9..c94dfb6 100644 --- a/server/models/user.js +++ b/server/models/user.js @@ -2,6 +2,7 @@ const mongoose = require('mongoose'); const validator = require('validator'); const jwt = require('jsonwebtoken'); const _ = require('lodash'); +const bcrypt = require('bcryptjs'); var UserSchema = new mongoose.Schema({ email: { @@ -73,6 +74,22 @@ UserSchema.statics.findByToken = function (token) { }); }; +UserSchema.pre('save', function(next) { + var user = this; + + if (user.isModified('password')) { + bcrypt.genSalt(10, (err, salt) =>{ + bcrypt.hash(user.password, salt, (err, hash) => { + user.password = hash; + next(); + }); + }); + } else { + next(); + } + +}); + var User = mongoose.model('User', UserSchema); module.exports = { User }; \ No newline at end of file