forked from koajs/session
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
323 lines (275 loc) · 6.6 KB
/
index.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
/**
* Module dependencies.
*/
var debug = require('debug')('koa-session');
var deepEqual = require('deep-equal');
var ONE_DAY = 24 * 60 * 60 * 1000;
/**
* Initialize session middleware with `opts`:
*
* - `key` session cookie name ["koa:sess"]
* - all other options are passed as cookie options
*
* @param {Object} [opts]
* @param {Application} app, koa application instance
* @api public
*/
module.exports = function(opts){
opts = opts || {};
// key
opts.key = opts.key || 'koa:sess';
// back-compat maxage
if (!('maxAge' in opts)) opts.maxAge = opts.maxage;
// defaults
if (null === opts.overwrite) opts.overwrite = true;
if (null === opts.httpOnly) opts.httpOnly = true;
if (null === opts.signed) opts.signed = true;
debug('session options %j', opts);
// setup encoding/decoding
if (typeof opts.encode !== 'function') {
opts.encode = encode;
}
if (typeof opts.decode !== 'function') {
opts.decode = decode;
}
return async (ctx, next) => {
// to pass to Session()
ctx.sessionKey = opts.key;
ctx.__defineGetter__('session', function(){
let sess = ctx._sess;
// already retrieved
if (sess) return sess;
// unset
if (false === sess) return null;
var json = ctx.cookies.get(opts.key, opts);
if (json) {
debug('parse %s', json);
try {
// make sure sessionOptions exists
initSessionOptions(ctx, opts);
var obj = opts.decode(json);
if (typeof opts.valid === 'function' && !opts.valid(ctx, obj)) {
// valid session value fail, ignore this session
sess = new Session(ctx);
json = obj;
debug('invalid %j', obj);
} else {
sess = new Session(ctx, obj);
// make prev a different object from sess
json = opts.decode(json);
}
} catch (err) {
// backwards compatibility:
// create a new session if parsing fails.
// new Buffer(string, 'base64') does not seem to crash
// when `string` is not base64-encoded.
// but `JSON.parse(string)` will crash.
debug('decode %j error: %s', json, err);
if (!(err instanceof SyntaxError)) throw err;
sess = new Session(ctx);
json = null;
}
} else {
debug('new session');
sess = new Session(ctx);
}
ctx._sess = sess;
ctx._prevjson = json;
return sess;
});
ctx.__defineSetter__('session', function(val){
if (null === val) {
ctx._sess = false;
return ctx._sess;
}
if ('object' === typeof val) {
ctx._sess = new Session(ctx, val);
return ctx._sess;
}
throw new Error('this.session can only be set as null or an object.');
});
// make sessionOptions independent in each request
initSessionOptions(ctx, opts);
try {
await next();
} catch (err) {
throw err;
} finally {
commit(ctx, ctx._prevjson, ctx._sess, opts);
}
};
};
function initSessionOptions(ctx, opts) {
if (ctx.sessionOptions) {
return;
}
ctx.sessionOptions = {};
for (var key in opts) {
ctx.sessionOptions[key] = opts[key];
}
}
/**
* Commit the session changes or removal.
*
* @param {Context} ctx
* @param {Object} prevjson
* @param {Object} sess
* @param {Object} opts
* @api private
*/
function commit(ctx, prevjson, sess, opts) {
// not accessed
if (undefined === sess) return;
// removed
if (false === sess) {
ctx.cookies.set(opts.key, '', opts);
return;
}
// do nothing if new and not populated
if (!prevjson && !sess.length) return;
// save
if (sess.changed(prevjson)) {
if (typeof opts.beforeSave === 'function') {
opts.beforeSave(ctx, sess);
}
sess.save();
}
}
/**
* Session model.
*
* @param {Context} ctx
* @param {Object} obj
* @api private
*/
function Session(ctx, obj) {
this._ctx = ctx;
if (!obj) {
this.isNew = true;
}
else {
for (var k in obj) {
// change session options
if ('_maxAge' === k) this._ctx.sessionOptions.maxAge = obj._maxAge;
else this[k] = obj[k];
}
}
}
/**
* JSON representation of the session.
*
* @return {Object}
* @api public
*/
Session.prototype.inspect =
Session.prototype.toJSON = function(){
var self = this;
var obj = {};
Object.keys(this).forEach(function(key){
if ('isNew' === key) return;
if ('_' === key[0]) return;
obj[key] = self[key];
});
return obj;
};
/**
* Check if the session has changed relative to the `prev`
* JSON value from the request.
*
* @param {Object} [prev]
* @return {Boolean}
* @api private
*/
Session.prototype.changed = function(prev){
if (!prev) return true;
delete prev._expire;
delete prev._maxAge;
return !deepEqual(prev, this.toJSON());
};
/**
* Return how many values there are in the session object.
* Used to see if it's "populated".
*
* @return {Number}
* @api public
*/
Session.prototype.__defineGetter__('length', function(){
return Object.keys(this.toJSON()).length;
});
/**
* populated flag, which is just a boolean alias of .length.
*
* @return {Boolean}
* @api public
*/
Session.prototype.__defineGetter__('populated', function(){
return !!this.length;
});
/**
* get session maxAge
*
* @return {Number}
* @api public
*/
Session.prototype.__defineGetter__('maxAge', function(){
return this._ctx.sessionOptions.maxAge;
});
/**
* set session maxAge
*
* @param {Number}
* @api public
*/
Session.prototype.__defineSetter__('maxAge', function(val){
this._ctx.sessionOptions.maxAge = val;
});
/**
* Save session changes by
* performing a Set-Cookie.
*
* @api private
*/
Session.prototype.save = function(){
var ctx = this._ctx;
var json = this.toJSON();
var opts = ctx.sessionOptions;
var key = ctx.sessionKey;
// set expire into cookie value
var maxAge = opts.maxAge || ONE_DAY;
json._expire = maxAge + Date.now();
json._maxAge = maxAge;
try {
json = opts.encode(json);
debug('save %s', json);
} catch (e) {
debug('encode %j error: %s', json, e);
json = '';
}
ctx.cookies.set(key, json, opts);
};
/**
* Decode the base64 cookie value to an object.
*
* @param {String} string
* @return {Object}
* @api private
*/
function decode(string) {
var body = new Buffer(string, 'base64').toString('utf8');
var json = JSON.parse(body);
// check if the cookie is expired
if (!json._expire) return null;
if (json._expire < Date.now()) return null;
return json;
}
/**
* Encode an object into a base64-encoded JSON string.
*
* @param {Object} body
* @return {String}
* @api private
*/
function encode(body) {
body = JSON.stringify(body);
return new Buffer(body).toString('base64');
}