我正在嘗試使用mongoose,passport-local和bcrypt-nodejs登錄我的應用程序。bcrypt-nodejs比較方法每次返回false
userSchema pre('save')函數正常工作並保存散列密碼。但是bcrypt比較方法每次都會返回false。
這裏是我的userSchema
var userSchema = mongoose.Schema({
login:{
local:{
email: {type: String, unique: true, required: true},
password: {type: String, unique: true, required: true}
}
}
userSchema.pre('save', function(next) {
bcrypt.hash('user.login.local.password', null, null, function(err, hash){
if(err){
next(err);
}
console.log('hash', hash);
user.login.local.password = hash;
next();
})
});
userSchema.methods.validPassword = function(password, cb){
bcrypt.compare(password, this.login.local.password, function(err, isMatch){
if(err) return cb(err);
cb(null, isMatch);
})
module.exports = mongoose.model('User', userSchema);
這工作得很好,並保存新的用戶使用散列密碼
這裏是我的我的登錄策略
不管用戶輸入什麼信息,這將始終返回錯誤
passport.use('local-login', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallBack: true
},
function(email, password, done){
User.findOne({ 'login.local.email' : email }, function(err, user){
if(err){
console.log(err);
return done(err);
}
if(!user){
console.log('no user found');
return done(err);
}
user.validPassword(password, function(err,match){
if(err){
console.log(err);
throw err;
}
console.log(password, match);
})
})
}))
最後我的路線
app.post('/user/login', passport.authenticate('local-login'{
successRedirect: '/#/anywhereBUThere'
failureRedirect: '/#/'
}))
唉唉的人,我覺得自己像個白癡!非常感謝Marco runnin現在順利!問題在於引號。我從來沒有抓到它,因爲我註銷了它找到的用戶,它顯示了哈希密碼,所以我想它是哈希我輸入的密碼...還有什麼會哈希?任何方式感謝您的幫助,我現在是1 for 1使用stackoverflow! – shay