2017-10-06 36 views
0

我遇到問題,如果我嘗試登錄時沒有用戶名或密碼,我的passport.use函數根本沒有被調用。Passport.js不調用LocalStrategy如果字段爲空

以下是我運行passport.authenticate的快遞郵寄路線。

app.post('/login', passport.authenticate('local-login', { 
     failureRedirect: '/login', // redirect back to the login page if there is an error 
     failureFlash: true // allow flash messages 
    }) 

而下面是我的passport.use應打印GOT HERE每當有一個POST請求/login

passport.use('local-login', new LocalStrategy({ 
     // by default, local strategy uses username and password, we will override with email 
     usernameField: 'email', 
     passwordField: 'password', 
     passReqToCallback: true // allows us to pass back the entire request to the callback 
    }, 
    function(req, email, password, done) { // callback with email and password from our form 
     // find a user whose email is the same as the forms email 
     // we are checking to see if the user trying to login already exists 
     console.log("GOT HERE"); 

此工作正常,如果emailpassword有某種類型的值。但是我希望即使emailpassword沒有任何值,也可以調用此函數,以便我可以自定義錯誤處理。

我該如何做到這一點?

回答

2

您可以添加被調用的中間件befure認證策略。事情是這樣的:

app.post('/login', function(req, res, next) { 
    // do custom error handling 
    }, passport.authenticate('local-login', { 
     failureRedirect: '/login', // redirect back to the login page if there is an error 
     failureFlash: true // allow flash messages 
}) 

而在這個中間件,你可以做一些自定義錯誤處理

+0

那真的是做到這一點的最好方法是什麼?目前我所有的錯誤處理都在護照功能中。所以分離它似乎不直觀。 –

+1

你可以從這裏查看源代碼: https://github.com/jaredhanson/passport-local/blob/f82655aa220ad7d0fcd8b114a0303d3cf94b8d06/lib/strategy.js#L71 'authenticate'函數做的第一件事就是檢查是否有passowrd和用戶名字段。所以我會說這是最簡單的方法。 –

+1

@CharlieFish這就是'護照本地'的工作原理。如果你想要自定義行爲,你可以使用類似['passport-custom'](https://github.com/mbell8903/passport-custom)的策略。 – robertklep

相關問題