Search code examples
node.jspassport.jsupdatesbcryptpassport-local

NodeJS Updating User Bcrypt - Password doesn't get hashed


I'm trying to set set up an update function for user profiles on a Node.JS application with hash passwords using the bcrypt-nodejs module. It works when signing in, but when I am updating the profile it updates the user object with the plain text (i.e.: I type "text" for the password, the db shows "text"). I would like to hash the password when the profile is updated. How would I fix this?

Below is my code for the controller:

exports.editUser = function(req, res) {
 // user edit form set to findonendupdate
 User.findByIdAndUpdate({ _id: req.params.user_id, randString: req.body.randString }, req.body, function(err, user) { 

   if (err) 
    res.send(err); 
   res.json({ data: user }); 
 });
};

For reference this is the user model code that works with a new user registration:

 passport.use('local', new LocalStrategy(
  function(username, password, callback) {
   User.findOne({ username: username } , function (err, user) {
     if (err) { return callback(err); }

     // No user found with that username
     if (!user) { return callback(null, false); }

     // Make sure the password is correct
     user.verifyPassword(password, function(err, isMatch) {
       if (err) { return callback(err); }

     // Password did not match
       if (!isMatch) { return callback(null, false); }

     // Success
       return callback(null, user);
     });
  });
 }
));

Solution

  • User.findByIdAndUpdate({...}, req.body, function(err,...
    

    Here you're receiving the password in req.body and telling it to update it directly as it is (plain text).

    You need to hash it and then update

    // retrieve the password field
    var password = req.body.password
    
    // update it with hash
    bcrypt.hash(password, (hash) => {
      req.body.password = hash
    
      // then update
      User.findByIdAndUpdate({...}, req.body, function(err,... // then update
    });