在node.js中使用passport-local和bcrypt检查和更新密码

sur*_*rth 5 authentication bcrypt mongoose node.js passport.js

[Error: data and hash arguments required]尝试在我的节点应用程序中验证用户的现有密码时出现错误.上下文是我要求我的用户在用户个人资料页面中更改之前验证他们的现有密码.我的堆栈是node + mondodb(通过mongoose)使用passport-local和bcrypt.

相关代码是:

// code trying to match that returns the aforementioned error
req.user.comparePassword(req.body.password, function (err, isMatch) {
    if (err) {
        return console.error(err);
    }
    if (isMatch) {
        console.log('passwords match');
        // now save new password

        // Password verification
        userSchema.methods.comparePassword = function (candidatePassword, cb) {
            bcrypt.compare(candidatePassword, this.password, function (err, isMatch) {
                if (err) return cb(err);
                cb(null, isMatch);
            });
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

req.user引用当前用户对象,`req.body.password'是从用户的POST获得的密码.我在这里使用护照本地示例中的UserSchema,护照策略和Bcrypt配置.

有人可以提供有关如何在更新之前验证密码是否匹配的指导?

Pet*_*ons 6

所以bcrypt.compare抱怨其中一个论点,无论是datahash缺失.所以这意味着可能this.password正在回归nullundefined.检查该用户的数据库记录,并确保它存储了有效的哈希.