如何在更改为新护照之前检查密码是否匹配



我正在构建一个应用程序,我正在努力使用passport和MongoDB更新密码。在设置新密码之前,我想检查用户是否输入了他的实际密码,并且它与数据库中存储的密码相匹配。

这就是我目前所掌握的:

if (req.body.password == req.user.password) {
if (req.body.newPassword.normalize() == req.body.confirmPassword.normalize()) {
// Verifying if the new password matches the confirmation one
// before actually changing the password (This part works)
}
} else {
// Handling if the old password does not match the DB
}
res.redirect('/profile')

我一直在尝试这样的东西:

passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({
username: req.user.email
}, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false);
}
if (!user.verifyPassword(req.body.password)) {
return done(null, false);
}
return done(null, user);
});
}

尽管如此,不起作用。。。有什么提示吗?:(

编辑

我一直在atempt中使用crypto来获得与存储在MongoDB中的哈希相同的哈希。要注册新用户,我使用passport。

let hash = crypto.createHmac('sha256', secret)
.update('I love cupcakes') // I have no idea of what this this line does, actually...
.digest('hex');
console.log(hash);

我想,在某个时候,我应该将DB存储的salt传递给一个动作,以验证他提交的密码与存储的密码相同,我只是不知道如何做到…

尝试使用机密对接收到的req.body.password进行散列,并查看它是否与保存在DB中的已散列密码匹配。如果是,那就是原来的密码。

通过大量的互联网搜索,我想出了这个:

async function fooChangePW(req,res){
req.user.changePassword(req.body.password, req.body.newPassword)
.then(() => {
console.log('password changed');
})
.catch((error) => {
console.log(error);
})
res.redirect('/profile')
}

由于用户已经通过了身份验证,所以whe可以使用req.user.changePassword(oldPassword, newPassword)

相关内容

最新更新