Create 64 byte session ids

This commit is contained in:
Ritchie Martori 2013-07-12 15:47:58 -07:00
parent 9a62c48cfc
commit a09b527000
2 changed files with 37 additions and 2 deletions

View File

@ -3,7 +3,8 @@
*/ */
var Model = require('../asteroid').Model var Model = require('../asteroid').Model
, asteroid = require('../asteroid'); , asteroid = require('../asteroid')
, crypto = require('crypto');
/** /**
* Default Session properties. * Default Session properties.
@ -20,3 +21,36 @@ var properties = {
*/ */
var Session = module.exports = Model.extend('session', properties); var Session = module.exports = Model.extend('session', properties);
/**
* Create a cryptographically random session id.
*
* @param {Function} callback
*/
Session.createSessionId = function (fn) {
crypto.randomBytes(this.settings.sessionIdLength || 64, function(err, buf) {
if(err) {
fn(err);
} else {
fn(null, buf.toString('base64'));
}
});
}
/*!
* Hook to create session id.
*/
Session.beforeCreate = function (next, data) {
data = data || {};
Session.createSessionId(function (err, id) {
if(err) {
next(err);
} else {
data.id = id;
next();
}
});
}

View File

@ -37,6 +37,7 @@ describe('User', function(){
assert(session.uid); assert(session.uid);
assert(session.id); assert(session.id);
assert.equal((new Buffer(session.id, 'base64')).length, 64);
done(); done();
}); });