Reputation: 31
I'm working with expressjs and want to authenticate users for a login using sessions. The site/app should on one hand allow the user to browse and investigate different products and information in a stateless webpage allowing caching of these pages, but should on the other hand have the functionality to let the user login and access different content acquired using sessions.
Thus for a subset of my routes I want session state activated, while for the complementary subset (the rest of my routes) express sessions should be deactivated, allowing caching of these pages.
How can I do this in a clean way?
Say the routes for which I want to activate sessions are '/kj%C3%B8p', '/bibliotek' and '/register'.
I tried something like
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
var pageName = 'somepage';
var oneYear = 1000*60*60*24*365;
app.use(express.bodyParser());
app.use('/kj%C3%B8p', express.cookieParser());
app.use('/kj%C3%B8p', express.session({key: pageName, secret: 'someCode', store: new RedisStore, cookie: {path:'/', maxAge: (5*oneYear), httpOnly: true}}));
app.use('/bibliotek', express.cookieParser());
app.use('/bibliotek', express.session({key: pageName, secret: 'someCode', store: new RedisStore, cookie: {path: '/', maxAge: (5*oneYear), httpOnly: true}}));
app.use('/registrer', express.cookieParser());
app.use('/registrer', express.session({key: pageName, secret: 'someCode', store: new RedisStore, cookie: {path:'/', maxAge: (5*oneYear), httpOnly: true}}));
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
but this regenerates the session object for each of the three routes, and seems quite messy. Any tips?
Upvotes: 3
Views: 1029
Reputation: 34630
You can wrap middleware in a function to black or whitelist certain urls. This is a whitelist example:
function allow(paths, fn) {
return function(req, res, next) {
if (~paths.indexOf(req.url)) {
return fn(req, res, next);
}
next();
}
}
You wrap it around your middleware like:
app.use(allow(['/bibliotek', '/registrer'], express.cookieParser()));
You can use the same technique for other middleware as well. This was based on a gist that the express author showed in irc.
Upvotes: 5