Node.js redirect to login if user is not logged in

Refresh

December 2018

Views

6.4k time

1

I am using the node-login module to login on my website. Ok, after the user logs in I render my dashboard.html website:

app.get('/', function(req, res){
// check if the user's credentials are saved in a cookie //
    if (req.cookies.user == undefined || req.cookies.pass == undefined){
        res.render(req.locale+'/login', { title: 'Hello - Please Login To Your Account' });
    }   else{
// attempt automatic login //
        AM.autoLogin(req.cookies.user, req.cookies.pass, function(o){
            if (o != null){
                req.session.user = o;
                res.redirect('/home');
            }   else{
                res.render('/login', { title: 'Hello - Please Login To Your Account' });
            }
        });
    }
});

After that, all other html websites are linked from within dashboard.html, so there are no other app.get methods called.

If a user tries to navigate to http://www.example.com/news.html (or any other html page that is not the login page ), if the user is not logged in, I need to redirect him to the login page.

I first thought somehting like this but I don't know if this is possible:

app.get('I-don't-know-what-to-insert-here', function(req, res) {
    if (req.session.user == null){
// if user is not logged-in redirect back to login page //
        res.redirect('/');
    }   else{
        res.redirect('redirect-here-to-the-requested-html-page')  
    }
});

Regards,

1 answers

7

Вы хотите написать промежуточное программное обеспечение, а не обработчик маршрута:

app.use(function(req, res, next) {
    if (req.session.user == null){
// if user is not logged-in redirect back to login page //
        res.redirect('/');
    }   else{
        next();
    }
});