我很抱歉再次发布这个问题,因为之前已被问过。但这些解决方案都不适合我。 我正在哈希密码,然后将其保存到数据库。 (保存,如果我比较密码和哈希,则返回true)
UserSchema.pre(' save',function(next){ console.log(" Unhashed Password:" + this.password);
if (this.password && this.password.length > 6) {
var password = this.password;
console.log("User password is valid");
bcrypt.hash(password, 10, function (err, hash) {
if (err) {
var err = new Error("Error hashing password");
next(err);
} else {
this.hashed_password = hash;
console.log("Hash: " + hash);
bcrypt.compare(password, this.hashed_password, function (err, result) {
console.log("Checking hash and password. Result is" + result);
console.log("Checking hash and password. Error is" + err);
next();
});
}
});
}
});
记录:
Unhashed Password: kashifLatif
User password is okay
Hash: $2a$10$fOuyx0XlTQ2Rwvc1jhn.EuC4UXt5oCrgTkhT.GviQh2Ftjtkuzy1C
Checking hash and password. Result istrue
Checking hash and password. Error isundefined
但是当我尝试使用相同的凭据登录时,bcrypt compare函数返回false: (认证功能): User.load(选项,函数(错误,用户){
User.load(options, function (err, user) {
console.log("Load user callback");
if (err) return done(err);
console.log("Db didn't return error");
if (!user) {
console.log("User didn't exist error");
return done(null, false, { message: 'Unknown user' });
}
console.log("Password sent from client: "+ password)
console.log("Email: "+ user.email)
console.log("Hashed: "+ user.hashed_password)
bcrypt.compare(password, user.hashed_password,function(err, result){
console.log("Bycrpt compared didn't exist error. Result is" + result);
if(result)
return done(null, user);
else
return done(null, false, { message: 'Invalid password' });
});
}
);
记录:
Load user callback
Db didn't return error
Password sent from client: kashifLatif
Email: usmann@gmail.com
Hashed: ad9da4c72ed234220315af53fb113f1f7716a8a0
Bycrpt compared didn't exist error. Result isfalse
保存时的哈希值与检索时的哈希值不同。为什么会这样?