From 2f047a37252a5c71bade3970618fa5b88fd67adc Mon Sep 17 00:00:00 2001 From: V S Tharunika <1vstharu279@gmail.com> Date: Sat, 2 Jan 2021 19:36:46 +0530 Subject: [PATCH] adding encryption/decryption to password --- server/src/app.js | 2 +- .../controllers/AuthenticationController.js | 2 +- server/src/models/user.js | 30 +++++++++++++++++-- 3 files changed, 30 insertions(+), 4 deletions(-) diff --git a/server/src/app.js b/server/src/app.js index bedf66a3..8b86bbe0 100644 --- a/server/src/app.js +++ b/server/src/app.js @@ -12,7 +12,7 @@ app.use(cors()) require('./routes')(app) -sequelize.sync({force: true}) +sequelize.sync() .then (() =>{ app.listen(config.port) console.log('server started on port ${config.port}') diff --git a/server/src/controllers/AuthenticationController.js b/server/src/controllers/AuthenticationController.js index 0b2fe527..117cd071 100644 --- a/server/src/controllers/AuthenticationController.js +++ b/server/src/controllers/AuthenticationController.js @@ -35,7 +35,7 @@ module.exports={ error: 'The login information was incorrect' }) } - const isPasswordValid = password === user.password + const isPasswordValid = await user.comparePassword(password) if(!isPasswordValid) { return res.status(403).send({ error: 'The login information was incorrect' diff --git a/server/src/models/user.js b/server/src/models/user.js index 0da0bd6f..e36ca96b 100644 --- a/server/src/models/user.js +++ b/server/src/models/user.js @@ -1,13 +1,39 @@ const Promise = require('bluebird') const bcrypt = Promise.promisifiyAll(require('bcrypt-nodejs')) -module.exports =(sequelize, DataTypes) => - sequelize.define('user',{ +function hashPassword (user, options) { + const SALT_FACTOR = 8 + + if(!user.changed('password')){ + return; + } + + return bcrypt + .genSaltAsync(SALT_FACTOR) + .then(salt => bcrypt.hashAsync(user.password, salt, null)) + .then(hash => { + user.setDataValue('password', hash) + }) + } + +module.exports =(sequelize, DataTypes) =>{ + const User = sequelize.define('user',{ email:{ type:DataTypes.STRING, unique: true }, password: DataTypes.STRING + }, { + hooks: { + beforeCreate: hashPassword, + beforeUpdate: hashPassword, + beforeSave: hashPassword + } }) + User.prototype.comparePassword = function (password) { + return bcrypt.compareAsync(password, this.password) + } + return User +} -- GitLab