Search code examples
node.jsexpresspassport.jspassport-local

Once authenticated always go to index page and not login


I am having a small issue with passport where once I have successfully logged in always by default go to "/index" rather than "/" <--- which is the login page.

As by default users will go to "/" and if they already have a session they will be automatically redirected to "/index"

I have it somewhat where if the user is not authenticated they cannot access "/index" but keep getting redirect loops with everything I have tried preventing this and I have only been using passport for the last day or so and am having issues with this problem.

I have it somewhat where if the user is not authenticated they cannot access "/index"

Anyone have any suggestions as to what am missing?

    //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('/');
  }

Kind Regards


Solution

  • As commented, you can do a middleware as so:

    app.get('/', redirectToIndexIfLoggedIn, function (req, res) {
      res.render('login');
    });
    
    function redirectToIndexIfLoggedIn(req, res, next) {
      if (req.isAuthenticated())
        res.redirect('/index');
    
      return next();
    }