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

how to check if the password matches before changing to new one passport

我正在构建一个应用程序,但我正在努力使用 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);
    });
  }

还是不行……有什么提示吗? :)

编辑

我一直在尝试使用加密来获得与 MongoDB 中存储的相同的哈希值。要注册新用户,我使用护照。

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

我想在某些时候我应该将数据库存储的盐传递给一个函数来验证他提交的密码是否与存储的密码相同,我只是不知道该怎么做...

尝试使用密钥对收到的 req.body.password 进行散列处理,看看它是否与数据库中保存的已散列密码相匹配。 如果是,则为相同的旧密码。

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

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

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