NodeJS 更新用户 Bcrypt - 密码未经过哈希处理

Jef*_*uel 2 updates bcrypt node.js passport-local passport.js

我正在尝试使用 bcrypt-nodejs 模块为具有哈希密码的 Node.JS 应用程序上的用户配置文件设置更新功能。它在登录时有效,但是当我更新配置文件时,它会使用纯文本更新用户对象(即:我输入“文本”作为密码,数据库显示“文本”)。我想在更新配置文件时对密码进行哈希处理。我该如何解决这个问题?

下面是我的控制器代码:

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 }); 
 });
};
Run Code Online (Sandbox Code Playgroud)

作为参考,这是适用于新用户注册的用户模型代码:

 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);
     });
  });
 }
));
Run Code Online (Sandbox Code Playgroud)

lag*_*lex 5

User.findByIdAndUpdate({...}, req.body, function(err,...
Run Code Online (Sandbox Code Playgroud)

在这里,您将收到密码req.body并告诉它直接按原样更新(纯文本)。

您需要对其进行哈希处理,然后更新

// 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
});     
Run Code Online (Sandbox Code Playgroud)