diff --git a/server/src/app.js b/server/src/app.js index bedf66a3cc55c242e60518d0558abafb94cc3163..8b86bbe0fd5f95fc603b763680ef4769df8d20fc 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 0b2fe527e5d4c97de1686e379abd7d6e92f5844e..117cd07114b175270dceeefbe760a49960abcf9f 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 0da0bd6f1ade60bb247fa34ee46ad895b7133cde..e36ca96b8051927219bd2ee667f77fab6f0cc0f5 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 +}