Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect and then stop in node.js

I am trying to stop users accessing certain pages whilst logged in and not logged in with node.js.

So far I have this idea:

exports.blockIfLoggedIn = function (req, res) {
    if (req.isAuthenticated()) { //passport
        req.flash('error', 'Sorry but you can\'t access this page');
        res.redirect('/');
    }
};

MA.f.auth.blockIfLoggedIn(req, res, next);
res.render('users/login', {
    title: 'Login'
});

This will redirect the page and but it will also error in the console with:

 Error: Can't set headers after they are sent.

I understand that this is trying to do res.render('users/login') function but as I've already set the page to redirect(/) so it can't.

There must be some way that if req.isAuthenticated() is true it will redirect and then essentially do something similar to php's exit()?

like image 511
Jamie Hutber Avatar asked Sep 06 '25 03:09

Jamie Hutber


1 Answers

You should use middleware. Here's an example:

// you can include this function elsewhere; just make sure you have access to it
var blockIfLoggedIn = function (req, res, next) {
    if (req.isAuthenticated()) {
        req.flash('error', 'Sorry, but you cannot access this page.')
        return res.redirect('/')
    } else {
        return next()
    }
}

// in your routes file (or wherever you have access to the router/app)
// set up your route
app.get('/users/login', blockIfLoggedIn, function (req, res) {
    res.render('somePage.ext', { title: 'Login' })
})
like image 178
royhowie Avatar answered Sep 07 '25 21:09

royhowie