【发布时间】:2017-10-05 20:28:51
【问题描述】:
我有一个 MEAN 应用程序正在尝试为“/changepassword”实现 GET 请求。该文件位于“/users/changepassword”中。我正在使用 Mongoose 和 bcryptjs 进行密码散列。请看我下面的代码。
这是 /users/changepassword
// Change Password
router.post('/changepassword', function(req, res){
var username = req.body.username;
var password = req.body.oldPassword;
var newPassword = req.body.newPassword;
User.getUserByUserName(username, function(err, user){
if(err) throw err;
if(user === null){
res.json({success: false, msg: "The given username does not exist."});
}else{
User.comparePassword(password, user.password, function(err, isMatch){
if(err) throw err;
if(isMatch)
{
User.changePassword(user, newPassword,function(err, changedPassword){
if(err) throw err;
else{
if(changedPassword === true){
res.json({success: true, msg: "Your password has been changed."});
}
else {
res.json({success: false, msg: "Your password was unable to be changed."});
}
}
});
}
});
}
});
});
这是位于 /models/user 中的 Mongoose 更改密码功能
module.exports.changePassword = function(user, newPassword, callback){
var query = {username: user.username};
bcrypt.genSalt(10, function(err, salt){
bcrypt.hash(user.password, salt, function(err, hash){
if (err) throw err;
else{
user.password = hash;
User.findOneAndUpdate(query, { $set: { password: user.password }}, {new: true}, function(err, newUser){
if(err) throw err;
else{
bcrypt.compare(newPassword, newUser.password, function(err, isMatch){
if(err) throw err;
console.log(isMatch);
callback(null, isMatch);
});
}
});
}
});
});
};
这是 /models/user 中使用的所有其他函数
module.exports.getUserByUserName = function(username, callback){
var query = {username: username};
User.findOne(query, callback);
};
module.exports.comparePassword = function(candidatePassword, hash, callback){
bcrypt.compare(candidatePassword, hash, function(err, isMatch){
if(err) throw err;
callback(null, isMatch);
});
};
当我使用邮递员时,这是我收到的输出
{
"success": false,
"msg": "Your password was unable to be changed."
}
非常感谢任何帮助! :)
【问题讨论】:
标签: node.js mongodb express mongoose postman