cookie.js
1 /*! 2 * Connect - session - Cookie 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 */ 13 14 var cookie = require('cookie') 15 var deprecate = require('depd')('express-session') 16 17 /** 18 * Initialize a new `Cookie` with the given `options`. 19 * 20 * @param {IncomingMessage} req 21 * @param {Object} options 22 * @api private 23 */ 24 25 var Cookie = module.exports = function Cookie(options) { 26 this.path = '/'; 27 this.maxAge = null; 28 this.httpOnly = true; 29 30 if (options) { 31 if (typeof options !== 'object') { 32 throw new TypeError('argument options must be a object') 33 } 34 35 for (var key in options) { 36 if (key !== 'data') { 37 this[key] = options[key] 38 } 39 } 40 } 41 42 if (this.originalMaxAge === undefined || this.originalMaxAge === null) { 43 this.originalMaxAge = this.maxAge 44 } 45 }; 46 47 /*! 48 * Prototype. 49 */ 50 51 Cookie.prototype = { 52 53 /** 54 * Set expires `date`. 55 * 56 * @param {Date} date 57 * @api public 58 */ 59 60 set expires(date) { 61 this._expires = date; 62 this.originalMaxAge = this.maxAge; 63 }, 64 65 /** 66 * Get expires `date`. 67 * 68 * @return {Date} 69 * @api public 70 */ 71 72 get expires() { 73 return this._expires; 74 }, 75 76 /** 77 * Set expires via max-age in `ms`. 78 * 79 * @param {Number} ms 80 * @api public 81 */ 82 83 set maxAge(ms) { 84 if (ms && typeof ms !== 'number' && !(ms instanceof Date)) { 85 throw new TypeError('maxAge must be a number or Date') 86 } 87 88 if (ms instanceof Date) { 89 deprecate('maxAge as Date; pass number of milliseconds instead') 90 } 91 92 this.expires = typeof ms === 'number' 93 ? new Date(Date.now() + ms) 94 : ms; 95 }, 96 97 /** 98 * Get expires max-age in `ms`. 99 * 100 * @return {Number} 101 * @api public 102 */ 103 104 get maxAge() { 105 return this.expires instanceof Date 106 ? this.expires.valueOf() - Date.now() 107 : this.expires; 108 }, 109 110 /** 111 * Return cookie data object. 112 * 113 * @return {Object} 114 * @api private 115 */ 116 117 get data() { 118 return { 119 originalMaxAge: this.originalMaxAge, 120 partitioned: this.partitioned, 121 priority: this.priority 122 , expires: this._expires 123 , secure: this.secure 124 , httpOnly: this.httpOnly 125 , domain: this.domain 126 , path: this.path 127 , sameSite: this.sameSite 128 } 129 }, 130 131 /** 132 * Return a serialized cookie string. 133 * 134 * @return {String} 135 * @api public 136 */ 137 138 serialize: function(name, val){ 139 return cookie.serialize(name, val, this.data); 140 }, 141 142 /** 143 * Return JSON representation of this cookie. 144 * 145 * @return {Object} 146 * @api private 147 */ 148 149 toJSON: function(){ 150 return this.data; 151 } 152 };