0

I am developing Node.js application with express. I am checking session in every route. But I want to separate this checking from my routes. Need idea.

Here is my route:

app.get('/Management', function(req, res) {
    if (!req.session.email) {
        return res.render(__dirname + "../../../views/management/accessdenied.jade", {
            title: 'dont have access',
            stylesheet: 'accessdenied',
            error: 'forbidden'
        });
    }
    return res.render(__dirname + "/views/index", {
        title: 'Management',
        stylesheet: 'managementindex'
    });
});

And here is my session check:

if (!req.session.email) {
    return res.render(__dirname + "../../../views/management/accessdenied.jade", {
        title: 'dont have access',
        stylesheet: 'accessdenied',
        error: 'forbidden'
    });
}
vbo
  • 13,583
  • 1
  • 25
  • 33
ftdeveloper
  • 1,053
  • 3
  • 26
  • 50
  • 2
    Looks like you need a middleware. Check this out: http://stackoverflow.com/questions/18700729/how-to-use-the-middleware-to-check-the-authorization-before-entering-each-route – vbo Dec 27 '13 at 12:41
  • You can either use `app.use` which fires on each request, or `app.get('*')` which fire on all GET requests etc. or something similar, there are many ways to do this. – adeneo Dec 27 '13 at 12:44

1 Answers1

2

Make your own middleware. This will respond to all get & post requests. You will want it at the bottom of all your other 'app.use()' calls (bodyParse, cookieParser, etc)

app.use(function(req, res, next) {
    if (!req.session.email) {
        res.render(__dirname + "../../../views/management/accessdenied.jade", {
            title: 'dont have access',
            stylesheet: 'accessdenied',
            error: 'forbidden'
        });
    } else {
        next();
    }
});
vbo
  • 13,583
  • 1
  • 25
  • 33
Chris
  • 1,611
  • 12
  • 11
  • But i dont need authorization for all routes. People should be able to visit without authorization in same routes. – ftdeveloper Dec 27 '13 at 13:52
  • Then instead of sending them an 'accessdenied' page, set a flag so your templates can render different things depending their login status, or ignore the flag all together if login status doesn't matter. With EJS (don't know about jade) you can put the check inside the actual template .ejs file, and leave your routing code simple. – Chris Dec 27 '13 at 14:00