1

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

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

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

我创建用户的控制器:

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

但是,无论密码是否匹配,回调始终为假。有谁知道我做错了什么?我试图切换到 bcrypt,但我无法安装它,因为 node-gyp 重建总是失败,抱怨它找不到我安装的 python 的 env 变量。另外,我不想在试图让服务器开发人员设置一个具有所有依赖项和正常 bcrypt 的东西的服务器时感到非常痛苦。

4

2 回答 2

2

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

bcrypt.hash(user.password, null, null, function(err, hash) {
    if (err) return fn(err);
    user.password = hash;
    fn();
});
于 2015-04-02T19:56:30.940 回答
0

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

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

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

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

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

希望这可以帮助。

于 2015-04-02T11:25:26.087 回答