简体   繁体   中英

mongoose and bcrypt-nodejs not hashing and saving password

I'm using a bcrypt-node and mongoose to hash a users password and save that user to a mongo database. When I debug the code below it appears to be working correctly, when you log the password in the code it shows it hashed, but when you check the database it's still plain text. I'm relatively new to node and mongoose/mongodb so I'm not sure how to troubleshoot. I've tried changing calling next(); to be return next(user); as suggested in another post but that didn't help. Any help would be greatly appreciated.

I'm using node version 6.9.5, mongoose 4.7.0, bcrypt-nodejs 0.0.3 and mongo 3.2.10

 UserSchema.pre('save', function (next) {  
      var user = this;
      if (user.password != "") {
        if (this.isModified('password') || this.isNew) {
          bcrypt.genSalt(10, function (err, salt) {
            if (err) {
          return next(err);
        }
        bcrypt.hash(user.password, salt, null, function(err, hash) {
          if (err) {
            return next(err);
          }
          console.log(hash);
          user.password = hash;
          console.log(user.password);
          next();
        });
      });
    } else {
      return next();
    }
  }
  return next();
});

You placed the hash function outside the genSalt() function. Also, you used some nesting and conditionals that made it hard to follow. Try the following and see how it works.

UserSchema.pre('save', function(next) {
  const user = this;
  if (!user.isModified('password')) {
    return next();
  }
  bcrypt.genSalt(10, (err, salt) => {
    if (err) {
      return next(err);
    }
    bcrypt.hash(user.password, salt, null, (error, hash) => {
      if (error) {
        return next(error);
      }
      console.log('HASH: ', hash);
      user.password = hash;
      console.log('USER.PASSWORD: ', user.password);
      next();
    });
  });
});

A lot more readable, right?

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