繁体   English   中英

bcrypt-nodejs.compare总是返回false

[英]bcrypt-nodejs.compare always returns false

我正在使用node.js,bcrypt,sequelize和passport设置登录名,并且已在线关注文档,但由于某些原因,即使我知道密码匹配,.compare函数也始终返回false。

在我的模型中,我添加了一个beforCreate挂钩来加密密码:

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

cryptoPassword函数:

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

我创建用户的控制器:

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,这是我的用户模型的instanceMethod。

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

您实际上并没有将密码传递给verifyPassword函数。

user.verifyPassword(password, function(err, isMatch) {
   ...              ^^^^^^^^
});`

该密码变量实际上并未定义。 当您使用.then()函数时,您可以访问从数据库返回的对象。 无论是单个结果还是结果集。

user.verifyPassword(user.password, function(err, isMatch) { ... });
                    ^^^^^^^^^^^^^

您必须访问从.findAll()查询返回的对象中的数据。

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM