-
Notifications
You must be signed in to change notification settings - Fork 0
/
cookies.js
111 lines (98 loc) · 2.71 KB
/
cookies.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
/*global escape: false */
/**
* Functions related to the manipulation and reading of cookies.
*
* @module
*/
function isBrowser() {
return (typeof(window) !== 'undefined');
}
/**
* Read cookies currently stored in the browser, returning an object
* keyed by cookie name.
*
* @name readBrowserCookies()
* @returns Object
* @api public
*/
exports.readBrowserCookies = function () {
if (!isBrowser()) {
throw new Error('readBrowserCookies cannot be called server-side');
}
var cookies = {};
var parts = document.cookie.split(';');
for (var i = 0, len = parts.length; i < len; i++) {
var name = parts[i].split('=')[0].trim();
var value = parts[i].split('=').slice(1).join('=');
cookies[name] = value;
}
return cookies;
};
/**
* Reads browser cookies and returned the value of the named cookie.
*
* @name readBrowserCookie(name)
* @returns {String}
* @api public
*/
exports.readBrowserCookie = function (name) {
return exports.readBrowserCookies()[name];
};
/**
* Creates a string for storing a cookie on the browser.
*
* @name cookieString(req, opt)
* @param {Request Object} req
* @param {Object} opt
* @returns {String}
* @api public
*/
exports.cookieString = function (req, opt) {
var str = escape(opt.name) + '=' + escape(opt.value) + '; path=' + opt.path;
if (opt.days) {
var expires = new Date();
expires.setTime(
new Date().getTime() + 1000 * 60 * 60 * 24 * opt.days
);
str += '; expires=' + expires.toGMTString();
}
return str;
};
/**
* Sets a cookie on the browser, for use client-side only.
*
* @name setBrowserCookie(req, opt)
* @param {Request Object} req
* @param {Object} opt
* @api public
*/
exports.setBrowserCookie = function (req, opt) {
if (!isBrowser()) {
throw new Error('setBrowserCookie cannot be called server-side');
}
var str = (typeof opt === 'string') ? opt: exports.cookieString(req, opt);
//console.log('document.cookie = ' + str);
document.cookie = str;
};
/**
* Creates a Set-Cookie header on a response object.
*
* @name setResponseCookie(req, res, opt)
* @param {Request Object} req
* @param {Response Object} res
* @param {Object} opt
* @api public
*/
exports.setResponseCookie = function (req, res, opt) {
var str = (typeof opt === 'string') ? opt: exports.cookieString(req, opt);
if (typeof res !== 'object') {
res = {code: 200, body: res};
}
if (!res.headers) {
res.headers = {};
}
// TODO: is it possible to send multiple set-cookie headers by turning
// headers into an array like in node?
// XXX: just replacing all cookies for now - not ideal!
res.headers['Set-Cookie'] = str;
};