2016-01-13 76 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