Bcrypt比较总是返回false [英] Bcrypt compare always returns false
问题描述
bcrypt.compare()
始终使用此代码返回false.这是与bcrypt-nodejs一起使用的.
bcrypt.compare()
always comes back false with this code in the user model. This is with bcrypt-nodejs.
User.pre('save', function (callback) {
this.password = bcrypt.hashSync(this.password, bcrypt.genSaltSync(10))
this.token = jwt.sign(this.email, process.env.JWT_SECRET)
callback()
})
User.methods.verifyPassword = function ( password ) {
const self = this
return Q.Promise( (resolve, reject) => {
bcrypt.compare( password, self.password, (error, isMatch) => {
if (error) reject( new Error("Error checking user password."))
resolve(isMatch)
})
})
}
我可以看到哈希显示在数据库中.我可以看到正确的密码进入了verifyPassword
函数.
I can see that a hash appears in the database. I can see the that right password comes into the verifyPassword
function.
问题似乎是.pre('save', ...
连续出现两次.因此,新哈希的密码将再次被哈希.
The issue seems to be that .pre('save', ...
occurs twice in a row. So the newly hashed password gets hashed again.
推荐答案
解决方案为if (!this.isModified('password')) return callback()
,如下所示.
The solution was if (!this.isModified('password')) return callback()
, shown below in full.
User.pre('save', function (callback) {
if (!this.isModified('password')) return callback()
this.password = bcrypt.hashSync(this.password, bcrypt.genSaltSync(10))
this.token = jwt.sign(this.email, process.env.JWT_SECRET)
callback()
})
这是因为这在保存过程中触发了多次.因此,它实际上是对密码进行哈希处理,然后在第二轮中对哈希进行哈希处理.
This is because this fires more than once in the save process. So it was effectively hashing the password, then on the second round, hashing the hash.
这篇关于Bcrypt比较总是返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!