node.js - bcrypt-nodejs.compare 总是返回 false

标签 node.js bcrypt passport-local

我正在使用node.js、bcrypt、sequelize 和passport 设置登录,并且已按照在线文档进行操作,但由于某种原因,即使我知道密码匹配,.compare 函数也始终返回 false。

在我的模型中,我添加了一个 beforeCreate Hook 来加密密码:

beforeUpdate: function(user, options, fn) {
    encryptPassword(user, options, fn);
}

加密密码函数:

encryptPassword = function(user, options, fn) {
    if (!user.changed('password'))
        return fn();

    bcrypt.hash(this.password, null, null, function(err, hash) {
        if (err) return fn(err);
        user.password = hash;
        fn();
    });
}

我在其中创建用户的 Controller :

User
    .create({
        username: req.body.username,
        password: req.body.password
    })
    .then(function() {
        res.json({
            message: 'New beer drinker added to the locker room!'
        });
    });

效果很好,用户使用散列密码存储在我的数据库中。

现在我尝试使用护照登录用户

passport.use(new BasicStrategy(
    function(username, password, callback) {
        User
            .find({
                where: {
                    username: username
                }
            })
            .then(function(user) {
                // No user found with that username
                if(!user) return callback(null, false);

                // Make sure the password is correct
                user.verifyPassword(password, function(err, isMatch) {
                    if(err) return callback(err);

                    // Password did not match
                    if(!isMatch) return callback(null, false);

                    // Success
                    return callback(null, user);
                });
            })
            .catch(function(err) {
                return callback(err);
            });
    }
));

此过程调用 user.verifyPassword,它是我的用户模型的实例方法。

verifyPassword: function(password, callback) {
    bcrypt.compare(password, this.password, callback);
}

但是,无论密码是否匹配,回调始终为 false。有人知道我做错了什么吗?我尝试切换到 bcrypt,但无法安装它,因为 node-gyp 重建总是失败,提示它找不到我已安装的 python 的 env 变量。另外,我不想让服务器开发人员建立一个具有所有依赖项和普通 bcrypt 内容的服务器,这是一个巨大的痛苦。

最佳答案

在加密密码时,我使用的是未定义的 this.password 。我需要使用 user.password 来获取当前密码。

bcrypt.hash(user.password, null, null, function(err, hash) {
    if (err) return fn(err);
    user.password = hash;
    fn();
});

关于node.js - bcrypt-nodejs.compare 总是返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29398832/

相关文章:

mysql - 序列化原始 mysql 查询返回空字段

encryption - 使用弱密码,bcrypt或SHA-256 + AES-256加密文件?

go - Bcrypt 为相同的密码生成不同的散列

node.js - 快速 session 和 Passport : req. isAuthenticated() 登录后返回 false

node.js - passport.js 是否支持 ajax?

javascript - Express Passport.js 成功重定向不加载页面,请求保持挂起

node.js - 在 Node.js 中管理嵌套异步 foreach 循环

node.js - Node 前 gyp 错误!堆栈错误: Failed to execute '/usr/local/bin/node/usr/local/lib/node_modules

node.js - 配置winstonjs以在大型expressjs应用程序中使用的最佳方法是什么?

node.js - 无法在 Ubuntu 14.04.1 x64 上为 Nodejs 安装 bcrypt