/
cookie.js
114 lines (95 loc) · 2.88 KB
/
cookie.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
// Express - Cookie - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)
/**
* Module dependencies.
*/
var Request = require('express/request').Request
/**
* Parse an HTTP _cookie_ string into a hash.
*
* @param {string} cookie
* @return {hash}
* @api public
*/
exports.parseCookie = function(cookie) {
return cookie.replace(/^ *| *$/g, '').split(/ *; */).reduce(function(hash, pair){
var parts = pair.split(/ *= */)
hash[parts[0]] = parts[1]
return hash
}, {})
}
/**
* Compile cookie _name_, _val_ and _options_ to a string.
*
* @param {string} name
* @param {string} val
* @param {hash} options
* @return {string}
* @api public
*/
exports.compileCookie = function(name, val, options) {
if (!options) return name + '=' + val
return name + '=' + val + '; ' + options.map(function(val, key){
if (val instanceof Date)
val = val.toGMTString()
return val === true ? key : key + '=' + val
}).join('; ')
}
// --- Cookie
exports.Cookie = Plugin.extend({
extend: {
/**
* Initialize extensions.
*/
init: function() {
Request.include({
/**
* Get or set cookie values.
*
* Options:
*
* - path Cookie path, defaults to '/'
* - domain Tail matched domain name such as 'vision-media.ca' or 'blog.vision-media.ca' etc
* - expires Date object converted to 'Wdy, DD-Mon-YYYY HH:MM:SS GMT'
* when undefined the cookie will last the duration of a the
* client's session.
* - secure When true the cookie will be sent by the client only when transfering data via HTTPS
* - httpOnly When true the cookie will be sent to the server only and will not be accessable via
* client-side scripting.
*
* @param {string} name
* @param {string} val
* @param {hash} options
* @return {string}
* @api public
*/
cookie: function(name, val, options) {
options = options || {}
options.path = options.path || '/'
return val ?
this.response.cookies.push(exports.compileCookie(name, val, options)) :
this.cookies[name]
}
})
}
},
// --- Events
on: {
/**
* Parse request cookie data.
*/
request: function(event) {
event.request.response.cookies = []
event.request.cookies = event.request.headers.cookie
? exports.parseCookie(event.request.headers.cookie)
: {}
},
/**
* Set the Set-Cookie header when response cookies are available.
*/
response: function(event) {
if (event.response.cookies &&
event.response.cookies.length)
event.request.header('set-cookie', event.response.cookies.join('\nset-cookie: '))
}
}
})