-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcookie.js
55 lines (38 loc) · 1.34 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
'use strict';
const {parse, serialize} = require('cookie');
const {sign, unsign} = require('cookie-signature');
function cookie(app, {decode, secret} = {}) {
app.extendRequest('cookies', null);
const parseOpts = {decode};
app.addHook('onRequest', function onRequest(req, res, next) {
const cookieHeader = req.headers.cookie;
req.cookies = cookieHeader === undefined ? {} : parse(cookieHeader, parseOpts);
next();
});
app.extendRequest('unsignCookie', function unsignCookie(value) {
return unsign(value, secret);
});
app.extendResponse('signCookie', function signCookie(value) {
return sign(value, secret);
});
app.extendResponse('setCookie', setCookie);
app.extendResponse('clearCookie', clearCookie);
}
function setCookie(name, value, options) {
const opts = Object.assign({path: '/'}, options);
this.appendHeader('set-cookie', serialize(name, value, opts));
return this;
}
const clearCookieExpiresDate = new Date(1);
function clearCookie(name, options) {
// IE/Edge don't support Max-Age=0, so use Expires instead
const clearOpts = Object.assign({
expires: clearCookieExpiresDate,
maxAge: null,
path: '/',
}, options);
clearOpts.maxAge = null; // In case options contains maxAge
this.appendHeader('set-cookie', serialize(name, '', clearOpts));
return this;
}
module.exports = cookie;