I am implementing a restify middleware for session authentication. The function contains nested asynchronous db calls: db.sessions.remove() within the callback of db.sessions.findOne().
The 'return' statements are confusing me because I'm not sure if I am returning next() or next(err) from the callback back to verifyUserSession(), or is it just returning from verifyUserSessions? Am I doing this right?
function verifyUserSession(req, res, next) {
if (req.headers.sessionKey)
{
db.sessions.findOne(req.headers.sessionKey, function(err, session) {
if (err)
{
return next(err);
}
if (!session)
{
return next(new Error({'message': 'Session does not exist'}));
}
if ((new Date().getTime() - session.timestamp.getTime())/86400000 > 60)
{
db.sessions.remove({sessionKey: req.headers.sessionKey}, function(err){
if (err)
{
return next(err);
}
return next(new Error({'message': 'Session expired'}));
});
}
else
{
// session ok
}
});
}
}
You are using the callbacks just right.
return
is used only to return from the current callback. When you call return next(...)
you invoke the callback function and return the value it returns. Returns are often needed only to make sure you don't invoke a callback twice.
Note that you need to make sure every possible branch in your function will invoke the callback, otherwise your program will never proceed from verifyUserSession
. In the code example you gave this happens two cases: 1) if session is ok, 2) if req.headers.sessionKey
is not set. You should add callbacks for these branches as well.