How can I run model checks before setterMethod in Sequelize?

I want to save a hashed password. I am using setterMethod for this:

module.exports = (sequelize, DataTypes) -> sequelize.define 'User', # other model fields [...] password: type: DataTypes.STRING validate: notEmpty: msg: 'You need to set a password.' set: (pw) -> salt = bcrypt.genSaltSync(10) hash = bcrypt.hashSync(pw, salt) @setDataValue('password', hash) 

The setter starts first. An empty string password ( '' ) is placed in a non-empty one (say $2a$10$pDDIGnV.r47i9YOv0Fls/euQ0yYvfyq8T1SyP9VRQsTUAqptNmxXO ).

When the validator checks, the password is no longer empty.

How to check the password before the installer?

I looked at hooks , but they also do not mention installers.

I am using sequelize@2.1.3 .

+5
source share
1 answer

I solved this problem using two fields: one of them is the VIRTUAL type, which handles input and verification, and one is the STRING type, which contains the hashed password.

This example is not coffeescript , but you can easily translate it.

 password_hash: { type: DatabaseTypes.STRING, allowNull: false, validate: { notEmpty: true, }, }, password: { type: DatabaseTypes.VIRTUAL, allowNull: false, // note that arrow functions cannot access "this", so use the form: set: function setPassword(val) { // trigger validation on "password" field this.setDataValue('password', val); // hash the password, this can be done in one step by passing the // number of salt rounds instead of the salt string. this.setDataValue('password_hash', bcrypt.hashSync(val, 10)); }, validate: { notEmpty: { message: 'You need to set a password.', }, }, }, 

When authenticating a user, compare the entered password with User.password_hash , not User.password .

 instanceMethods: { // authenticate user given a password authenticate(password) { return bcrypt.compareSync(password, this.password_hash); }, }, 

You can then call this instance method to authenticate User .

 User.findById(userId) .then((user) => { if (user.authenticate(password)) { console.log('Authenticated'); } else { console.log('Not authenticated'); } }); 
0
source

All Articles