2017-03-03 143 views
2

这是我的散列密码和比较现有的密码与密码现有的模块已sended对身体要求代码:BCrypt哈希错误

 //hash password of document that use this schema 
    bcrypt.hash(user.password, null, null, function (err, hashed) { 

     if (err) { 
      throw err; 
     } else { 
      user.password = hashed; 

      //next api 
      next(); 
     } 
    }) 
}); 

userSchema.methods.comparePassword = function (password) { 

    //refer at userSchema 
    var user = this; 

    //return method of bcryot library that compare two string: original password and password hashed 
    return bcrypt.compareSync(password, user.password); 

}; 

但是比较这错误信息:

Uncaught, unspecified "error" event. (Not a valid BCrypt hash.) 

回答

1

您正在使用null两次。我敢打赌,你已经将这个函数包含在bcrypt.genSalt函数中(如果你没有这样做的话)。您需要将bcrypt salt传递给写入第一个null的地方。

这里有一个完整的例子:

userSchema.pre('save', function (next) { 
    const SALTROUNDS = 10; // or another integer in that ballpark 
    const user = this; 
    if(!user.isModified('password')) { 
    return next(); 
    } 

    bcrypt.genSalt(SALTROUNDS, (err, salt) => { 
    if (err) { return next(err); } 

    bcrypt.hash(user.password, salt, null, (error, hash) => { 
     if (error) { return next(error); } 

     user.password = hash; 
     next(); 
    }); 
    }); 
}); 
+0

不幸的是不工作! – DevWeb

2

解决!进入数据库我有很多用户的密码没有被哈希,当我尝试登录,与bcrypt.compareSync (password, user.password);它预期已被哈希密码。