store.js 1.9 KB

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