2016-01-13 13 views
1

我有一個小問題與護照,一旦我成功登錄總是默認去「/索引」,而不是「/」< ---這是登錄頁。一旦身份驗證總是去索引頁面,而不是登錄

因爲默認情況下用戶會去「/」,如果他們已經有一個會議,他們將被自動重定向到「/指數」

我有幾分那裏,如果用戶沒有通過驗證,他們不能訪問「 /索引「,但不斷得到重定向循環與我試圖阻止這一切,我只用了護照的最後一天左右,並有這個問題的問題。

我有幾分那裏,如果用戶沒有通過驗證,他們不能訪問「/指數」

任何人有任何建議,我是什麼不見了?

//Gets the login route and renders the page. 
    app.get('/', function (req, res) { 
    res.render('login'); 
    }); 

    //The index page, isLoggedIn function always called to check to see if user is authenticated or in a session, if they are they can access the index route, if they are not they will be redirected to the login route instead. 
    app.get('/index', checkLoggedIn, function (req, res) { 
    res.render('index.ejs', { 
     isAuthenticated : req.isAuthenticated(), 
     user : req.user 
    }); 
    }); 

    //This is where the users log in details are posted to, if they are successfull then redirect to index otherwise keep them on the login route. 
    app.post('/login', passport.authenticate('local', { 
     successRedirect : '/index', 
     failureRedirect : '/', 
     failureFlash : 'Invalid username or password.' 
    })); 

    //When logout is clicked it gets the user, logs them out and deletes the session, session cookie included then redirects the user back to the login route. 
    app.get('/logOut', function (req, res) { 
    req.logOut(); 
    req.session.destroy(); 
    res.redirect('/') 
    }); 

    //Check to see if logged in, if so carry on otherwise go back to login. 
    function checkLoggedIn(req, res, next) { 

    // if user is authenticated in the session, carry on 
    if (req.isAuthenticated()) 
     return next(); 

    // if they aren't redirect them to the index page 
    res.redirect('/'); 
    } 

親切的問候

+0

你可以做一個'redirectToIndexIfLoggedIn'中間件... – joaumg

回答

1

至於評論,你可以做一箇中間件像這樣:

app.get('/', redirectToIndexIfLoggedIn, function (req, res) { 
    res.render('login'); 
}); 

function redirectToIndexIfLoggedIn(req, res, next) { 
    if (req.isAuthenticated()) 
    res.redirect('/index'); 

    return next(); 
} 
+1

謝謝你的幫助,它的一個簡單問題,但我仍然要抓住護照! :)感謝您花時間幫助。 – Studento919