You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

140 lines
2.2 KiB

  1. /*!
  2. * Connect - session - Cookie
  3. * Copyright(c) 2010 Sencha Inc.
  4. * Copyright(c) 2011 TJ Holowaychuk
  5. * MIT Licensed
  6. */
  7. /**
  8. * Module dependencies.
  9. */
  10. var utils = require('../../utils')
  11. , cookie = require('cookie');
  12. /**
  13. * Initialize a new `Cookie` with the given `options`.
  14. *
  15. * @param {IncomingMessage} req
  16. * @param {Object} options
  17. * @api private
  18. */
  19. var Cookie = module.exports = function Cookie(options) {
  20. this.path = '/';
  21. this.maxAge = null;
  22. this.httpOnly = true;
  23. if (options) utils.merge(this, options);
  24. this.originalMaxAge = undefined == this.originalMaxAge
  25. ? this.maxAge
  26. : this.originalMaxAge;
  27. };
  28. /*!
  29. * Prototype.
  30. */
  31. Cookie.prototype = {
  32. /**
  33. * Set expires `date`.
  34. *
  35. * @param {Date} date
  36. * @api public
  37. */
  38. set expires(date) {
  39. this._expires = date;
  40. this.originalMaxAge = this.maxAge;
  41. },
  42. /**
  43. * Get expires `date`.
  44. *
  45. * @return {Date}
  46. * @api public
  47. */
  48. get expires() {
  49. return this._expires;
  50. },
  51. /**
  52. * Set expires via max-age in `ms`.
  53. *
  54. * @param {Number} ms
  55. * @api public
  56. */
  57. set maxAge(ms) {
  58. this.expires = 'number' == typeof ms
  59. ? new Date(Date.now() + ms)
  60. : ms;
  61. },
  62. /**
  63. * Get expires max-age in `ms`.
  64. *
  65. * @return {Number}
  66. * @api public
  67. */
  68. get maxAge() {
  69. return this.expires instanceof Date
  70. ? this.expires.valueOf() - Date.now()
  71. : this.expires;
  72. },
  73. /**
  74. * Return cookie data object.
  75. *
  76. * @return {Object}
  77. * @api private
  78. */
  79. get data() {
  80. return {
  81. originalMaxAge: this.originalMaxAge
  82. , expires: this._expires
  83. , secure: this.secure
  84. , httpOnly: this.httpOnly
  85. , domain: this.domain
  86. , path: this.path
  87. }
  88. },
  89. /**
  90. * Check if the cookie has a reasonably large max-age.
  91. *
  92. * @return {Boolean}
  93. * @api private
  94. */
  95. get hasLongExpires() {
  96. var week = 604800000;
  97. return this.maxAge > (4 * week);
  98. },
  99. /**
  100. * Return a serialized cookie string.
  101. *
  102. * @return {String}
  103. * @api public
  104. */
  105. serialize: function(name, val){
  106. return cookie.serialize(name, val, this.data);
  107. },
  108. /**
  109. * Return JSON representation of this cookie.
  110. *
  111. * @return {Object}
  112. * @api private
  113. */
  114. toJSON: function(){
  115. return this.data;
  116. }
  117. };