Node js Keeps redirecting - Middleware

不问归期 提交于 2020-01-07 04:18:07

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/45144678/node-js-keeps-redirecting-middleware

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!