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

5

当我尝试在我的Node应用程序中验证用户的现有密码时,出现了[错误:需要数据和哈希参数]错误。 这种情况下,我要求用户在更改用户配置文件页面中的密码之前验证其现有密码。 我的技术栈是使用passport-local与bcrypt的node + mondodb(通过mongoose)。

相关代码如下:

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

req.user 引用当前用户对象,而 `req.body.password' 是从用户的 POST 获得的密码。我正在使用来自 passport-local 示例 这里 的 UserSchema、passport 策略和 Bcrypt 配置。

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

1个回答

6

所以bcrypt.compare提示缺少其中一个参数,可能是data或者hash。这意味着this.password返回了nullundefined。检查用户的数据库记录,确保它存储了有效的哈希值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接