2015-05-27 28 views
2

我正在嘗試使用mongoose,passport-local和bcrypt-nodejs登錄我的應用程序。bcrypt-nodejs比較方法每次返回false

userSchema pre('save')函數正常工作並保存散列密碼。但是bcrypt比較方法每次都會返回false。

看到bcrypt-nodejs

這裏是我的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: '/#/' 
    })) 

回答

1

很可能是問題的根源是比較函數返回false,因爲你確實比較兩個不相同的哈希值。

你出現在你userSchema前要傳遞一個字符串「user.login.local.password」,而不是實際的密碼保存功能:

例如這 bcrypt.hash('user.login.local.password', null, null, function(err, hash){應該bcrypt.hash(user.login.local.password, null, null, function(err, hash){(在密碼沒有單引號傳遞作爲第一個參數。)

此外,你那麼生成的哈希設置到這似乎生活之外的「用戶」的對象用戶模型。我看不到那個代碼,但我懷疑你沒有更新保存到mongoDB的用戶模型上的散列值。

例如 user.login.local.password = hash; 大概應該是 this.login.local.password = hash;

+0

唉唉的人,我覺得自己像個白癡!非常感謝Marco runnin現在順利!問題在於引號。我從來沒有抓到它,因爲我註銷了它找到的用戶,它顯示了哈希密碼,所以我想它是哈希我輸入的密碼...還有什麼會哈希?任何方式感謝您的幫助,我現在是1 for 1使用stackoverflow! – shay