简体   繁体   中英

Can't get the Hash password to save with bcrypt

I am trying to persist a hashed password using sequelize, bcrypt and express. The hash does generate but it looks like the db entry happend before the hash value is generated. I am new to NodeJS, so my knowledge is not as good on this yet.

user.js

var bcrypt = require('bcrypt');

module.exports = function(sequelize, DataType){

  var User = sequelize.define('User', {
    name: DataType.STRING,
    localPassword: DataType.STRING,
    lastName: DataType.STRING,
    localEmail: DataType.STRING,
    cellNumber: DataType.INTEGER
  },
      {
        instanceMethods: {
          validPassword: function(password){
              return bcrypt.compareSync(password, this.password);
          }
        },
          classMethods: {
              generateHash: function (password) {
                  return bcrypt.hash(password, 8, function(err, hash){
                      if(err){
                          console.log('error'+err)
                      }else{
                          return hash;
                      }
                  });
              }
          }
      }

  );

    return User;
};

routes/index.js

router.post('/register', function(req, res){
  var name = req.body.name;
  var lastName = req.body.lastName;
  var email = req.body.email;
  var cellNumber = req.body.cellNumber;
  var password = model.User.generateHash(req.body.password);
  model.User.build({name: name, lastName: lastName, localEmail: email, cellNumber: cellNumber, localPassword: password}).save();

});

All the values persist in the db except the hashed password. Any help would be greatly appreciated.

The problem here is that you are using an asynchronous bcrypt.hash and model.User.build executes before bcrypt hashed the password. You have several options here, you can use a synchronous bcrypt.hashSync; or perform model.User.build call as a promise

model.User.generateHash(req.body.password).then(function(data){
   ...
})

You can use bcrypt-then for that.

npm install bcrypt-then

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM