Manage session start with express connection and middleware

Is there a way to control when a session starts with session middleware?

For example, if I have an express config application:

var app = express(); app.configure(function(){ app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.cookieParser('secret')); app.use(express.session({ store:sessionStore, ... })); }); 

Then, with each request, if no cookie session is specified, the session begins. What if I wanted to start a session only after user authentication?

For example, let's say I have two routes /protected and /login .

  • If someone clicked /protected without a session cookie, the middleware will NOT start a new session. ( req.session - null )
  • If someone clicked /protected with a session cookie, the middleware will CHECK to see if there is a corresponding active session for the cookie and req.session set, but a new session will not start, ( req.session may be or null )
  • If someone clicked on /login with the correct parameters, then the session starts explicitly , and the cookie is set only then.

The only way to start a session should be explicit:

 app.post('/login', function(req, res, next) { // connect to database and validate user... db.authenticate( req.body.user, req.body.pass, function(allow) { if (allow) { // START SESSION HERE // this will send set the cookie } }); } 

Is there a way to accomplish this using the existing session middleware?

+7
source share
2 answers

What you want to do is delete this line:

 app.use(express.session({ store:sessionStore, ... })) 

Now the sessions are disabled by default, and you decide which controller will use them:

 var useSessions = express.session({ store:sessionStore, ... }); var preCb = function (req, res, next) { // authenticate and stuff // .... if (authenticated === true) { next(); } }; app.post('/login', useSessions, function(req, res, next) { ... }); app.post('/protected', preCb, useSessions, function(req, res, next) { ... }); 
+2
source

Even if the session starts every time, it does not matter much because it will be empty. If you are trying to use it to authenticate access (which seems to be the case), the easiest solution is to set an attribute in your session (for example, req.session.authenticated = true;) and verify this. Thus, technically, a visitor ever has a session, however you will only use the session if req.session.authenticated == true. This may not be exactly what you are looking for, but it is the easiest way to do this.

0
source

All Articles