4

I'm writing an application based on Express.js, while using Everyauth for authentication.

To initialize everyauth, I use:

app.use(everyauth.middleware());

I'd like to bypass authentication for certain routes. Specifically, I noticed findUserById is called for every request, and I'd like to skip it for certain routes (e.g. no authentication for /getImage).

Is that possible?

Lior Grossman
  • 315
  • 3
  • 9

2 Answers2

3

You could wrap the everyauth.middleware() callback manually.

var auth = everyauth.middleware();
app.use(function(req, res, next) {
  if (shouldAuthRequest(req)) {
    // call auth, as if it was part of the route
    auth(req, res, next);
  } else {
    // ignore auth
    next();
  }
});

This is nothing but a wrapped middleware.

Tharabas
  • 3,402
  • 1
  • 30
  • 29
  • Thanks Tharabas. Unfortunately, that doesn't work. It says auth() is not a function. I tried calling everyauth.middleware() directly instead, but it doesn't call next(), and therefore it doesn't handle any request. – Lior Grossman Feb 14 '12 at 10:29
1

As of 0.4.5, everyauth.middleware must be called with Express's app object. You can therefore create a wrapped middleware this way:

var my_auth_middleware = function(app) {
  var auth = everyauth.middleware(app);
  // a custom middleware wrapping everyauth
  var middleware = function(req, res, next) {
    if (shouldAuthRequest(req)) {
      // go through the everyauth middleware
      auth(req, res, next);
    } else {
      // bypass everyauth
      next();
    }
  };
  // these allow the middleware to be "mounted" by Express
  middleware.set = true;
  middleware.handle = middleware;
  middleware.emit = auth.emit;
  // return our custom middleware
  return middleware;
};

and then add your wrapped middleware to the stack with

app.use(my_auth_middleware(app));
davb
  • 339
  • 2
  • 7
  • kiddorails, I'm using the [#express3](https://github.com/bnoguchi/everyauth/tree/express3) branch of everyauth, and the source of the `everyauth.middleware` method is [here](https://github.com/bnoguchi/everyauth/blob/express3/index.js#L24-52). I'm not sure how the `app` object is used, but both READMEs of the `master` and `express3` branches suggest that it should be passed to `everyauth.middleware` – davb Oct 06 '13 at 10:45