Noman Ali
Noman Ali

Reputation: 3340

Node js Keeps redirecting - Middleware

I am trying to write a middleware using node js and express. If user is not authenticated it will redirect him to login page.

That's working, but once redirected to login page, it keeps redirecting to login page again and again.

app.get('/profile',function(req,res){
   if (isAuthenticated()) {
       res.sendFile(path.join(__dirname+'/site/profile.html'));
   }else{
       console.log('not authenticated user at profile');
       res.redirect('/login');
   }
});

For login

app.get('/login',function(req,res){
   if (isAuthenticated()) {
       res.redirect('/profile');
   }else{
       res.sendFile(path.join(__dirname+'/login.html'));
   }

});

EDIT:

Console(loop): not authenticated user at profile

Firebase method for authentication

function isAuthenticated(){
   var user = firebase.auth().currentUser;
   console.log(user);
   if(user && user !== null){
       return true;
   }else{
       return false;
   }
}

It is returning null

Upvotes: 0

Views: 534

Answers (1)

t.niese
t.niese

Reputation: 40872

I wouldn't use a redirect, but write an authenticationRequired middleware. This middleware would either send a 401 status code and display the login page, or pass the the request forward to the next callback.

function authenticationRequired(req, res, next) {
   if( isAuthenticated() ) {
       next()
   } else {
       res.status(401).sendFile(path.join(__dirname, 'login.html'));
   } 
}


// register the middleware for only one route
app.get('/profile', authenticationRequired, function(req,res) {
    res.sendFile(path.join(__dirname, 'site/profile.html'));
});

// or register the middleware for all routes that follow 
app.use(authenticationRequired)

app.get('/profile', function(req,res) {
    res.sendFile(path.join(__dirname+'/site/profile.html'));
});

This way you would not need to manually keep track of the url the user tried to open in the first case and after login the user will stay on the correct url.

Beside that you would use the correct status codes, instead of the 302 which tells the browser that the resource is temporary at another places you send the 401 which tells the browser that an authentication is required to display the requested resource.

Upvotes: 2

Related Questions