bcrypt-nodejs.compare总是返回false

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

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

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

encryptPassword函数:

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

我的控制器在哪里创build用户:

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

这很好,用户存储在我的数据库与散列密码。

现在我尝试使用护照login用户

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

但是,无论密码是否匹配,callback总是假的。 有没有人有任何想法我做错了? 我试图切换到bcrypt,但我无法得到它安装,因为node-gyp重build总是失败,抱怨它无法find我安装的Python的envvariables。 另外,我不想在屁股上有一个巨大的痛苦,试图让服务器开发人员build立一个具有正常bcrypt的所有依赖和东西的服务器。

当encryption密码时,我使用了未定义的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) { ... ^^^^^^^^ });` 

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

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

您将不得不访问从.findAll()查询中返回的对象中的数据。

希望这可以帮助。