3 * Connect - session - Session
4 * Copyright(c) 2010 Sencha Inc.
5 * Copyright(c) 2011 TJ Holowaychuk
10 * Module dependencies.
13 var utils = require('../../utils')
14 , Cookie = require('./cookie');
17 * Create a new `Session` with the given request and `data`.
19 * @param {IncomingRequest} req
20 * @param {Object} data
24 var Session = module.exports = function Session(req, data) {
25 Object.defineProperty(this, 'req', { value: req });
26 Object.defineProperty(this, 'id', { value: req.sessionID });
27 if ('object' == typeof data) {
28 utils.merge(this, data);
30 this.lastAccess = Date.now();
35 * Update `.lastAccess` timestamp,
36 * and reset `.cookie.maxAge` to prevent
37 * the cookie from expiring when the
38 * session is still active.
40 * @return {Session} for chaining
44 Session.prototype.touch = function(){
51 * Update `.lastAccess` timestamp.
53 * @return {Session} for chaining
57 Session.prototype.resetLastAccess = function(){
58 this.lastAccess = Date.now();
63 * Reset `.maxAge` to `.originalMaxAge`.
65 * @return {Session} for chaining
69 Session.prototype.resetMaxAge = function(){
70 this.cookie.maxAge = this.cookie.originalMaxAge;
75 * Save the session data with optional callback `fn(err)`.
77 * @param {Function} fn
78 * @return {Session} for chaining
82 Session.prototype.save = function(fn){
83 this.req.sessionStore.set(this.id, this, fn || function(){});
88 * Re-loads the session data _without_ altering
89 * the maxAge or lastAccess properties. Invokes the
90 * callback `fn(err)`, after which time if no exception
91 * has occurred the `req.session` property will be
92 * a new `Session` object, although representing the
95 * @param {Function} fn
96 * @return {Session} for chaining
100 Session.prototype.reload = function(fn){
102 , store = this.req.sessionStore;
103 store.get(this.id, function(err, sess){
104 if (err) return fn(err);
105 if (!sess) return fn(new Error('failed to load session'));
106 store.createSession(req, sess);
113 * Destroy `this` session.
115 * @param {Function} fn
116 * @return {Session} for chaining
120 Session.prototype.destroy = function(fn){
121 delete this.req.session;
122 this.req.sessionStore.destroy(this.id, fn);
127 * Regenerate this request's session.
129 * @param {Function} fn
130 * @return {Session} for chaining
134 Session.prototype.regenerate = function(fn){
135 this.req.sessionStore.regenerate(this.req, fn);