3

I am trying to configure my express application to redirect to a login page based on some logic. I have the following:

  app.use('/', function(req, res, next){
    if(!req.session.accessToken){
      //do something here
    }
    next();
  });

I have a login.html file located in the root of the directory my application is being served from, I am just unsure what I need to call on the res object e.g. redirect, send

Also, I know the above will actually cause an infinite loop.

What's the correct approach here?

mindparse
  • 6,115
  • 27
  • 90
  • 191

2 Answers2

1

You'll want to be careful of your handler order, what you want (if you really want to do this on your own and not use something like Passport) is something like (the somewhat skeleton);

app.use('/login', function(req, res) {   // Allows access to login page
    res.send('displaying login page');   // before access token check
});

app.use(function(req, res, next) {       // Catches access to all other pages
    if(!req.session.accessToken) {       // requiring a valid access token
        res.redirect('/login');
    } else {
        next();
    }
});

// the rest of your routes go here, they should not be called unless authenticated
Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
0

The most obvious answer is to simply call res.redirect('/login.html'), but that would return a 301 (moved permanently) code to the browser. A more semantically correct solution might be to return a 401 (unauthorized) and render the login.html file to the response.

See Is it possible to send a 401 Unauthorized AND redirect (with a Location)?

So a solution might look something like this:

app.use('/', function(req, res, next){
  if(!req.session.accessToken)
    res.status(401).sendFile(path.join(__dirname+'/login.html'));
  else
    next()
});
Community
  • 1
  • 1
Adam Brown
  • 1,056
  • 10
  • 13