Jamie Hutber
Jamie Hutber

Reputation: 28126

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()?

Upvotes: 4

Views: 1782

Answers (1)

royhowie
royhowie

Reputation: 11171

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' })
})

Upvotes: 3

Related Questions