This is a bit in-depth so I'll start with the background:
I am working on adapting an existing web application with a NodeJS + Express backend, to a PhoneGap / Steroids app. Currently authentication for this is handled by Passport (http://passportjs.org/) using sessions. The authorization middleware I use on non-public routes looks mostly like this:
var isAuthorized = function( req, res, next ) {
if ( req.isAuthenticated() ) {
return next();
} else {
return next(new Error("Invalid Session"));
}
};
Unfortunately session cookies do not work in PhoneGap (that I can tell). And the recommended solution is to instead include a unique token with every request to the server, much like to an api end-point.
Now, I do not want to ditch session cookies, as Passport does a great job with them and it works fine for people who are connecting with a web browser. So instead I have done the following...
When a user logs in, after authenticating via Passport, I generate a unique token "session_id" that is passed back to the client in the response. This token is then included as a custom header in every PhoneGap request.
I have then modified the above authorization middleware to the following:
var isAuthorized = function( req, res, next ) {
if ( req.isAuthenticated() ) {
return next();
} else if ( req.headers.session_id ) {
// no session cookies, this looks like a phonegap request
session.isPhoneGapSession( req.headers.session_id, function( err, userData ) {
if ( err ) { return next( err ); }
if ( userData ) {
req.login( userData, function( err ) {
if ( err ) return next( err );
return next();
});
} else {
return next(new Error("Invalid Session"));
}
});
} else {
return next(new Error("Invalid Session"));
}
};
So, if there is a session_id in the header, the method session.isPhoneGapSession is called. This checks to see if the session_id from the header matches up with a user in the session table of the database. If so, it passes the user data back. I then feed this data into Passport's req.login method, to shore everything up, and authorize the request.
This works. Hurray! However, I have a worry. And now we get to my question:
In the above solution, every time a request is received from PhoneGap, req.login will be called. In the Passport documentation, it states that this method is usually only invoked once, when a user first logs in (http://passportjs.org/guide/login/).
I don't really know what this method does, beyond just setting up the req.user object. Is it safe to call it frequently like this? Or am I courting disaster? Input from anyone who knows Passport well would be much appreciated.
(I suppose I could have just asked, is it safe to call Passport's req.login method on every request, what exactly does this method do? But I think it helps to see the context of why I am asking this question.)