2017-03-03 145 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);它預期已被哈希密碼。