Skip to content

Instantly share code, notes, and snippets.

@JesusMurF
Created November 16, 2016 10:21
Show Gist options
  • Save JesusMurF/9d206738aa54131a6e7ac88ab2d9084e to your computer and use it in GitHub Desktop.
Save JesusMurF/9d206738aa54131a6e7ac88ab2d9084e to your computer and use it in GitHub Desktop.
How to encrypt password in Sequelize
import Sequelize from 'sequelize'
import bcrypt from 'bcrypt-nodejs'
import connection from '../config/db'
require('sequelize-isunique-validator')(Sequelize)
let User = connection.define('user', {
firstName: {
type: Sequelize.STRING(50),
allowNull: false,
validate: {
len: {
args: [0, 50],
msg: 'El nombre tiene demasiados carácteres'
}
}
},
lastName: {
type: Sequelize.STRING(100),
allowNull: false,
validate: {
len: {
args: [0, 100],
msg: 'Los apellidos tienen demasiados carácteres'
}
}
},
email: {
type: Sequelize.STRING(100),
allowNull: false,
unique: true,
validate: {
isEmail: {
msg: 'No es una dirección de correo electrónico.'
},
isUnique: connection.validateIsUnique(
'email',
'Esta dirección de correo electrónico ya existe.'
)
}
},
password: {
type: Sequelize.STRING,
allowNull: false
}
}, {
instanceMethods: {
generateHash: function (password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null)
},
validPassword: function (password) {
return bcrypt.compareSync(password, this.password)
}
}
})
User.sync()
export default User
@Aditya94A
Copy link

Node is single threaded + Bcrypt is slow => This will make the server unresponsive for the duration of the synchronous functions. Do not do this in production.

Go async instead.

  User.beforeCreate(function(user, options) {
    return cryptPassword(user.password)
      .then(success => {
        user.password = success;
      })
      .catch(err => {
        if (err) console.log(err);
      });
  });

function cryptPassword(password) {
  console.log("cryptPassword" + password);
  return new Promise(function(resolve, reject) {
    bcrypt.genSalt(10, function(err, salt) {
      // Encrypt password using bycrpt module
      if (err) return reject(err);

      bcrypt.hash(password, salt, null, function(err, hash) {
        if (err) return reject(err);
        return resolve(hash);
      });
    });
  });

@hansaliyad1
Copy link

This works with beforeCreate but not for beforeBulkUpdate. Not sure why.

@KielD-01
Copy link

@hansaliyad1, because You need to specify the hook correctly and map all the array of the users.
In the map function, You will be able to crypt a password.

@hevilp
Copy link

hevilp commented Mar 18, 2018

@AdityaAnand1 can u provide the full example please?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment