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
.
/protected
without a session cookie, the middleware will NOT start a new session. (req.session
is null
)/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
)/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?
The session middleware handles all things for us, i.e., creating the session, setting the session cookie and creating the session object in req object. Whenever we make a request from the same client again, we will have their session information stored with us (given that the server was not restarted).
Cookie session is basically used for lightweight session applications where the session data is stored in a cookie but within the client [browser], whereas, Express Session stores just a mere session identifier within a cookie in the client end, whilst storing the session data entirely on the server.
saveUninitialized : When an empty session object is created and no properties are set, it is the uninitialized state.
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) { ... });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With