Adam K Dean
Adam K Dean

Reputation: 7475

Disable session in Express app config

I am using Express with Passport for an Node.js API app, and I can disable sessions by passing {session:false} to passport.authenticate, but is there a way I can do this in one place so I don't repeat myself 600 times?

var app = express();

app.configure(function() {
    app.use(express.bodyParser());
    app.use(passport.initialize());
});

app.get('/users', passport.authenticate('hash', {session:false}), controllers.users.getAll);
app.get('/users/me', passport.authenticate('hash', {session:false}), controllers.users.getCurrentUser);
// and so on...

It would be great if I could just do:

app.donotuse(sessions).thanks();

Upvotes: 3

Views: 4754

Answers (3)

robertklep
robertklep

Reputation: 203286

Just save the result in a variable and re-use it:

var PassportAuthenticateMiddleware = passport.authenticate('hash', {session:false});
...
app.get('/users',    PassportAuthenticateMiddleware, controllers.users.getAll);
app.get('/users/me', PassportAuthenticateMiddleware, controllers.users.getCurrentUser);

(or do as @hexacyanide suggests and use the middleware globally, if that's an option in your setup)

Alternatively, you can use something similar to this:

app.all('/users*',   passport.authenticate('hash', {session:false}));
app.get('/users',    controllers.users.getAll);
app.get('/users/me', controllers.users.getCurrentUser);

This will filter all requests (instead of .all you can use .get too) whose URL starts with /users to be run through the authentication middleware.

Upvotes: 5

Krasimir
Krasimir

Reputation: 13529

I guess that you have some routes which need session. It is possible to set this globally, but this will not work in your case. What you can do is to improve the code a bit:

var controller = function(controller) {
    return function(req, res, next) {
        passport.authenticate('hash', {session:false})(req, res, next);
        controller(req, res, next);
    }
}
app.get('/users', controller(controllers.users.getAll));
app.get('/users/me', controller(controllers.users.getCurrentUser));

Upvotes: 1

hexacyanide
hexacyanide

Reputation: 91639

The authenticator itself is middleware. Therefore, you can assign it globally.

app.use(express.bodyParser());
app.use(passport.initialize());
app.use(passport.authenticate('hash', {session:false}));

Upvotes: 3

Related Questions