我正在尝试使用 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/