2014-10-16 102 views
4

我正在執行護照驗證到我的節點應用程序,我無法理解爲什麼在訪問響應(res)屬性之前需要重定向?護照節點驗證成功

app.get('/api/loginFailure', function(req, res) { 
    res.status(401).json({message: 'Login Failed', success: true}); 
}); 

app.get('/api/loginSuccess', function(req, res) { 
    res.status(200).json({message:'Welcome!', success: true}); 

}); 


// process the login form 
app.post('/api/login', passport.authenticate('local-login', { 
    successRedirect: '/api/loginSuccess', 
    failureRedirect: '/api/loginFailure'})); 

正如您所看到的,我使用successRedirect訪問不同的路由以發回一個json響應。我不希望節點api重定向實際的應用程序,因爲它的目的是爲了與前端無關。

本地登錄策略如下。我懷疑我的困難可能在於我如何從方法中迴歸;

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 
     User.findOne({ 
       'local.email': email 
      }, 

      function(err, user) { 
       // if there are any errors, return the error before anything else 
       if (err) 
        return done(err); 

       // if no user is found, return the message 
       if (!user) { 
        return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash 
       } 

       // if the user is found but the password is wrong 
       if (!user.validPassword(password)) { 
        return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata 
       } 

       // all is well, return successful user 
       return done(null, user); 
      }); 

    })); 

我打算刪除所有flashdata,什麼不是,但現在只能夠在2條額外的API路線收縮到/ API /登錄將是巨大的。

回答

3

我無法理解爲什麼在訪問響應(res)屬性之前需要重定向?

如果檢查passport documentation,而不是複製從this guide你的代碼,這意味着另一種類型的使用,你會發現它並不總是需要重定向。

您也可以通過以下方式來使用它:

app.post('/login', 
    passport.authenticate('local'), 
    function(req, res) { 
    // If this function gets called, authentication was successful. 
    // `req.user` contains the authenticated user. 
    res.redirect('/users/' + req.user.username); 
    } 
); 
+0

這正是指南爲沒有?起點?我明白我可以做你上面強調的內容,但我不明白的是如何從定製策略中返回,以便可以應用上述相同的邏輯。 – Dean 2014-10-17 13:43:12

+0

你已經嘗試過使用相同的'passport.use()'塊嗎? – t0mppa 2014-10-17 20:55:31

+0

我試過app.post('/ login',passport.authenticate('local-login'),function(req,res){});但屬性res不可用。這就是爲什麼我認爲我在本地戰略中的回報陳述是不正確的。 – Dean 2014-10-20 11:50:42