diff options
| author | mo khan <mo@mokhan.ca> | 2015-02-21 20:55:43 -0700 |
|---|---|---|
| committer | mo khan <mo@mokhan.ca> | 2015-02-21 20:55:43 -0700 |
| commit | b3cea2d8f1c0436e8be1f45b09f6c0fe42f7fb2a (patch) | |
| tree | 1a4c02b1a09d923a60542b9ca6f366c04d298584 /week-7/Final4/blog/sessions.js | |
| parent | 8419ce131f9d933339495c12a644ac6ff747f116 (diff) | |
final 4.
Diffstat (limited to 'week-7/Final4/blog/sessions.js')
| -rw-r--r-- | week-7/Final4/blog/sessions.js | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/week-7/Final4/blog/sessions.js b/week-7/Final4/blog/sessions.js new file mode 100644 index 0000000..3af169f --- /dev/null +++ b/week-7/Final4/blog/sessions.js @@ -0,0 +1,65 @@ +var crypto = require('crypto'); + +/* The SessionsDAO must be constructed with a connected database object */ +function SessionsDAO(db) { + "use strict"; + + /* If this constructor is called without the "new" operator, "this" points + * to the global object. Log a warning and call it correctly. */ + if (false === (this instanceof SessionsDAO)) { + console.log('Warning: SessionsDAO constructor called without "new" operator'); + return new SessionsDAO(db); + } + + var sessions = db.collection("sessions"); + + this.startSession = function(username, callback) { + "use strict"; + + // Generate session id + var current_date = (new Date()).valueOf().toString(); + var random = Math.random().toString(); + var session_id = crypto.createHash('sha1').update(current_date + random).digest('hex'); + + // Create session document + var session = {'username': username, '_id': session_id} + + // Insert session document + sessions.insert(session, function (err, result) { + "use strict"; + callback(err, session_id); + }); + } + + this.endSession = function(session_id, callback) { + "use strict"; + // Remove session document + sessions.remove({ '_id' : session_id }, function (err, numRemoved) { + "use strict"; + callback(err); + }); + } + this.getUsername = function(session_id, callback) { + "use strict"; + + if (!session_id) { + callback(Error("Session not set"), null); + return; + } + + sessions.findOne({ '_id' : session_id }, function(err, session) { + "use strict"; + + if (err) return callback(err, null); + + if (!session) { + callback(new Error("Session: " + session + " does not exist"), null); + return; + } + + callback(null, session.username); + }); + } +} + +module.exports.SessionsDAO = SessionsDAO; |
