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

标签 node.js passport.js updates bcrypt passport-local

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

下面是我的 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 }); 
 });
};

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

 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);
     });
  });
 }
));

最佳答案

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

在这里,您将在 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
});     

关于node.js - NodeJS 更新用户 Bcrypt - 密码未经过哈希处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34326162/

相关文章:

node.js - 即使目录可写,全局安装时也会出现 NPM 错误

javascript - ldapjs - LDAP 连接错误处理

javascript - Sequelize - 使用 MySQL 选择所有超过 5 分钟的记录的抽象查询

node.js - 在 ExpressJS 中从 Req.User() 获取信息到 Req.params()

node.js - 使用 Node Js 更新 Dynamo 数据库中的集合

visual-studio-2012 - 如何通过命令行检查Visual Studio更新?

node.js - Angular运行错误Object Prototype may only be an Object or null : undefined

node.js - 如何在使用 passport-google-oauth 成功验证后重定向到原始页面

node.js - 使用 Passport.js 将 facebook 数据链接到当前登录的用户

javascript - 如何使用自动增量键更新 IndexedDB 项?