3 * Connect - session - Session
4 * Copyright(c) 2010 Sencha Inc.
5 * Copyright(c) 2011 TJ Holowaychuk
13 module.exports = Session;
16 * Create a new `Session` with the given request and `data`.
18 * @param {IncomingRequest} req
19 * @param {Object} data
23 function Session(req, data) {
24 Object.defineProperty(this, 'req', { value: req });
25 Object.defineProperty(this, 'id', { value: req.sessionID });
27 if (typeof data === 'object' && data !== null) {
28 // merge data into this, ignoring prototype properties
29 for (var prop in data) {
30 if (!(prop in this)) {
31 this[prop] = data[prop]
38 * Update reset `.cookie.maxAge` to prevent
39 * the cookie from expiring when the
40 * session is still active.
42 * @return {Session} for chaining
46 Session.prototype.touch = function(){
47 return this.resetMaxAge();
51 * Reset `.maxAge` to `.originalMaxAge`.
53 * @return {Session} for chaining
57 Session.prototype.resetMaxAge = function(){
58 this.cookie.maxAge = this.cookie.originalMaxAge;
63 * Save the session data with optional callback `fn(err)`.
65 * @param {Function} fn
66 * @return {Session} for chaining
70 Session.prototype.save = function(fn){
71 this.req.sessionStore.set(this.id, this, fn || function(){});
76 * Re-loads the session data _without_ altering
77 * the maxAge properties. Invokes the callback `fn(err)`,
78 * after which time if no exception has occurred the
79 * `req.session` property will be a new `Session` object,
80 * although representing the same session.
82 * @param {Function} fn
83 * @return {Session} for chaining
87 Session.prototype.reload = function(fn){
89 , store = this.req.sessionStore;
90 store.get(this.id, function(err, sess){
91 if (err) return fn(err);
92 if (!sess) return fn(new Error('failed to load session'));
93 store.createSession(req, sess);
100 * Destroy `this` session.
102 * @param {Function} fn
103 * @return {Session} for chaining
107 Session.prototype.destroy = function(fn){
108 delete this.req.session;
109 this.req.sessionStore.destroy(this.id, fn);
114 * Regenerate this request's session.
116 * @param {Function} fn
117 * @return {Session} for chaining
121 Session.prototype.regenerate = function(fn){
122 this.req.sessionStore.regenerate(this.req, fn);