0

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.

Paul
  • 139,544
  • 27
  • 275
  • 264
Andre Coetzee
  • 1,260
  • 3
  • 20
  • 34
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Paul Feb 07 '16 at 19:53
  • You handle it like any normal async call by adding a callback. ``generateHash: function (password, callback) {`` then return the hash by invoking the callback function. – Andrew Eddie Feb 09 '16 at 03:25

1 Answers1

1

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
tergd1
  • 557
  • 6
  • 19