-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
127 lines (104 loc) · 2.47 KB
/
index.js
File metadata and controls
127 lines (104 loc) · 2.47 KB
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
115
116
117
118
119
120
121
122
123
124
125
126
127
/**
* Module dependencies.
* @private
*/
const debug = require('debug')('express-tiny-session');
const onHeaders = require('on-headers');
/**
* Create a new cookie session middleware.
*
* @param {Object} [opts]
* @param {boolean} [opts.httpOnly]
* @param {string} [opts.name=express:sess] Name of the cookie to use
* @param {boolean} [opts.overwrite]
* @param {string} [opts.secret]
* @param {boolean} [opts.signed]
* @return {function} middleware
* @public
*/
function expressTinySession (opts = { }) {
const name = opts.name || 'express:sess';
// defaults
if (null == opts.httpOnly)
opts.httpOnly = true;
if (null == opts.signed)
opts.signed = true;
if (!opts.secret && opts.signed)
throw new Error('secret key required.');
debug('session options %j', opts);
return function cookieSession(req, res, next) {
const cookieVal = opts.secret ? req.signedCookies[name] : req.cookies[name];
let session = {};
let data = null;
if (cookieVal) {
try {
session = decode(cookieVal);
data = JSON.parse(JSON.stringify(session));
} catch (err) { /* */ }
if (!isPlaiObject(session)) {
session = {};
}
}
onHeaders(res, function setHeaders() {
if (this.req.session === undefined) {
// not accessed
return;
}
if (this.req.session === false) {
// remove
debug('clear session');
this.clearCookie(name, opts);
return;
}
if (!isEqual(data, this.req.session)) {
debug('send session %j', this.req.session);
this.cookie(name, encode(this.req.session), opts);
}
});
req.session = session;
next();
};
}
/**
* Decode the base64 cookie value to an object.
*
* @param {string} string
* @return {Object}
* @private
*/
function decode(string) {
const body = Buffer.from(string, 'base64').toString('utf8');
return JSON.parse(body);
}
/**
* Encode an object into a base64-encoded JSON string.
*
* @param {Object} body
* @return {string}
* @private
*/
function encode(body) {
const string = JSON.stringify(body);
return Buffer.from(string).toString('base64');
}
/**
* Comparison function
*
* @param {Object} data
* @param {Object} session
* @return {boolean}
* @private
*/
function isEqual(data, session) {
return JSON.stringify(data) === JSON.stringify(session);
}
/**
*
* @param {Object} obj
* @return {boolean}
* @private
*/
function isPlaiObject(obj) {
return typeof obj === 'object' && Object.prototype.toString.call(obj) === '[object Object]';
}
module.exports = expressTinySession;