7
votes

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

For example, if I have express app config:

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 on every request, if no session cookie is given, a session is started. What if I wanted to start a session only when the user has been authenticated?

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

  • If someone hits /protected without a session cookie, the middleware will NOT start a new session. (req.session is null)
  • If someone hits /protected with a session cookie, the middleware will CHECK to see if there is a matching active session for the cookie and set req.session, but will not start a new session. (req.session could have a value or be null)
  • If someone hits /login with the correct params, then a session is started explicitly and a cookie is set only then.

The only way to start a session should be explicitly:

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 any way of accomplishing this with the existing connect session middleware?

2

2 Answers

2
votes

What you want to do is to remove this line:

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

Now sessions are disabled by default and it's up to you to decide which controller is going to 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) { ... });
0
votes

Even if a session is started every time, it does not really matter because it will be empty. If you are attempting to use it to authenticate access (which seems to be the case), the simplest solution is to set an attribute in your session (such as req.session.authenticated = true;), and check that. This way technically ever visitor has a session, however you will only utilize the session if req.session.authenticated == true. It may not be exactly what you're looking for, but it is the easiest way to get this done.