0

In my ExpressJS app, several of my urls handlers have the following logic:

  1. See if the user has permission to access a resource
  2. If so, continue
  3. Else, redirect to the main handler.

Is there a way to insert a pre-handler for certain url handlers, via ConnectJS or ExpressJS?

I know I can do it globally, for all handlers, (which I do to insert missing headers as a result from IE's broken XDR).

But, can I do this for a subset of handlers?

Alan
  • 45,915
  • 17
  • 113
  • 134

2 Answers2

3

I do something like this:

lib/auth.js

exports.checkPerm = function(req, res, next){
  //do some permission checks
  if ( authorized ) {
     next();
  } else {
     res.render('/401');
     return;
  }
};

app.js

var auth = require('./lib/auth');
...
app.get('/item/:itemid', auth.checkPerm, routes.item.get);

You can stack middleware before your final route handler like the above line has. It has to have same function signature and call next();

chovy
  • 72,281
  • 52
  • 227
  • 295
  • Is there a way to pass data inside the `next()` routine? – Alan Nov 15 '12 at 19:27
  • 1
    Hmmm...you can, but i would keep the signature the same. I usually set `res.locals.foo = foo;` if i want to pass data down the middleware chain. – chovy Nov 15 '12 at 22:44
  • Oh yeah derp, it's javacsript. You can add to objects. – Alan Nov 16 '12 at 05:26
2

If I understand this question correctly, you know about:

// This is too general
app.use(myAuthMiddleware());

And you are aware that you can add it manually to certain url-handlers:

app.get('/user/profile/edit', myAuthMiddleware(), function(req,res){
  /* handle stuff */ });
// but doing this on all your routes is too much work.

What you might not know about express' mounting feature:

// Matches everything under /static/** Cool.
app.use('/static', express.static(__dirname + '/public'));

Or app.all():

// requireAuthentication can call next() and let a more specific
// route handle the non-auth "meat" of the request when it's done.
app.all('/api/*', requireAuthentication);
rdrey
  • 9,379
  • 4
  • 40
  • 52