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
isnull
) - 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 setreq.session
, but will not start a new session. (req.session
could have a value or benull
) - 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?