2 * Connect - session - Session
3 * Copyright(c) 2010 Sencha Inc.
4 * Copyright(c) 2011 TJ Holowaychuk
14 module.exports = Session;
17 * Create a new `Session` with the given request and `data`.
19 * @param {IncomingRequest} req
20 * @param {Object} data
24 function Session(req, data) {
25 Object.defineProperty(this, 'req', { value: req });
26 Object.defineProperty(this, 'id', { value: req.sessionID });
28 if (typeof data === 'object' && data !== null) {
29 // merge data into this, ignoring prototype properties
30 for (var prop in data) {
31 if (!(prop in this)) {
32 this[prop] = data[prop]
39 * Update reset `.cookie.maxAge` to prevent
40 * the cookie from expiring when the
41 * session is still active.
43 * @return {Session} for chaining
47 defineMethod(Session.prototype, 'touch', function touch() {
48 return this.resetMaxAge();
52 * Reset `.maxAge` to `.originalMaxAge`.
54 * @return {Session} for chaining
58 defineMethod(Session.prototype, 'resetMaxAge', function resetMaxAge() {
59 this.cookie.maxAge = this.cookie.originalMaxAge;
64 * Save the session data with optional callback `fn(err)`.
66 * @param {Function} fn
67 * @return {Session} for chaining
71 defineMethod(Session.prototype, 'save', function save(fn) {
72 this.req.sessionStore.set(this.id, this, fn || function(){});
77 * Re-loads the session data _without_ altering
78 * the maxAge properties. Invokes the callback `fn(err)`,
79 * after which time if no exception has occurred the
80 * `req.session` property will be a new `Session` object,
81 * although representing the same session.
83 * @param {Function} fn
84 * @return {Session} for chaining
88 defineMethod(Session.prototype, 'reload', function reload(fn) {
90 var store = this.req.sessionStore
92 store.get(this.id, function(err, sess){
93 if (err) return fn(err);
94 if (!sess) return fn(new Error('failed to load session'));
95 store.createSession(req, sess);
102 * Destroy `this` session.
104 * @param {Function} fn
105 * @return {Session} for chaining
109 defineMethod(Session.prototype, 'destroy', function destroy(fn) {
110 delete this.req.session;
111 this.req.sessionStore.destroy(this.id, fn);
116 * Regenerate this request's session.
118 * @param {Function} fn
119 * @return {Session} for chaining
123 defineMethod(Session.prototype, 'regenerate', function regenerate(fn) {
124 this.req.sessionStore.regenerate(this.req, fn);
129 * Helper function for creating a method on a prototype.
131 * @param {Object} obj
132 * @param {String} name
133 * @param {Function} fn
136 function defineMethod(obj, name, fn) {
137 Object.defineProperty(obj, name, {