UNPKG

1.9 kBJavaScriptView Raw
1/*!
2 * Connect - session - Store
3 * Copyright(c) 2010 Sencha Inc.
4 * Copyright(c) 2011 TJ Holowaychuk
5 * MIT Licensed
6 */
7
8'use strict';
9
10/**
11 * Module dependencies.
12 * @private
13 */
14
15var Cookie = require('./cookie')
16var EventEmitter = require('events').EventEmitter
17var Session = require('./session')
18var util = require('util')
19
20/**
21 * Module exports.
22 * @public
23 */
24
25module.exports = Store
26
27/**
28 * Abstract base class for session stores.
29 * @public
30 */
31
32function Store () {
33 EventEmitter.call(this)
34}
35
36/**
37 * Inherit from EventEmitter.
38 */
39
40util.inherits(Store, EventEmitter)
41
42/**
43 * Re-generate the given requests's session.
44 *
45 * @param {IncomingRequest} req
46 * @return {Function} fn
47 * @api public
48 */
49
50Store.prototype.regenerate = function(req, fn){
51 var self = this;
52 this.destroy(req.sessionID, function(err){
53 self.generate(req);
54 fn(err);
55 });
56};
57
58/**
59 * Load a `Session` instance via the given `sid`
60 * and invoke the callback `fn(err, sess)`.
61 *
62 * @param {String} sid
63 * @param {Function} fn
64 * @api public
65 */
66
67Store.prototype.load = function(sid, fn){
68 var self = this;
69 this.get(sid, function(err, sess){
70 if (err) return fn(err);
71 if (!sess) return fn();
72 var req = { sessionID: sid, sessionStore: self };
73 fn(null, self.createSession(req, sess))
74 });
75};
76
77/**
78 * Create session from JSON `sess` data.
79 *
80 * @param {IncomingRequest} req
81 * @param {Object} sess
82 * @return {Session}
83 * @api private
84 */
85
86Store.prototype.createSession = function(req, sess){
87 var expires = sess.cookie.expires
88 var originalMaxAge = sess.cookie.originalMaxAge
89
90 sess.cookie = new Cookie(sess.cookie);
91
92 if (typeof expires === 'string') {
93 // convert expires to a Date object
94 sess.cookie.expires = new Date(expires)
95 }
96
97 // keep originalMaxAge intact
98 sess.cookie.originalMaxAge = originalMaxAge
99
100 req.session = new Session(req, sess);
101 return req.session;
102};