Skip to content

Commit

Permalink
fix(session.js): Refactor session creation code to use promises in or…
Browse files Browse the repository at this point in the history
…der to fix a possible race condition while inserting a session to the database.
  • Loading branch information
andreialecu authored and ericfong committed Jan 12, 2015
1 parent 616b176 commit 3080de2
Showing 1 changed file with 23 additions and 11 deletions.
34 changes: 23 additions & 11 deletions lib/session.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ var Store = require('./db').Store
, Cookies = require('cookies')
, EventEmitter = require('events').EventEmitter
, crypto = require('crypto')
, debug = require('debug')('session');
, debug = require('debug')('session')
, Q = require("q");

/*!
* A simple index for storing sesssions in memory.
Expand Down Expand Up @@ -67,27 +68,38 @@ SessionStore.prototype.createSession = function(sid, fn) {
sid = undefined;
}
if(sid) {
this.find({id: sid}, function(err, s) {
if(err) return fn(err);
if(!s) {
store.insert({id: sid}, function(err, s) {
if(err) console.error(err);
Q.ninvoke(this, 'find', { id: sid })
.then(function (session) {
var defer = Q.defer();
if (!session) {
store.insert({ id: sid }, function (err, s) {
if (err) return defer.reject(err);
defer.resolve(s);
});
} else {
defer.resolve(session);
}
return defer.promise;
})
.then(function(s) {
var sess = sessionIndex[sid] || new Session(s, store, socketIndex, store.sockets);
sessionIndex[sid] = sess;
// index sessions by user
if(s && s.uid) {
if (s && s.uid) {
userSessionIndex[s.uid] = sess;
}
fn(err, sess);
});
fn(null, sess);
})
.catch(function (err) {
fn(err); // couldn't get a session
})
.done();
} else {
sid = this.createUniqueIdentifier();
var sess = sessionIndex[sid] = new Session({id: sid}, this, socketIndex, store.sockets);
this.insert({ id: sid }, function (err, s) {
fn(null, sess);
if(err) console.error(err);
if (err) return fn(err); // this shouldn't happen
fn(err, sess);
});
}
};
Expand Down

0 comments on commit 3080de2

Please sign in to comment.