forked from DeadAlready/node-easy-session
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
368 lines (324 loc) · 10.5 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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
'use strict';
var RBAC = require('easy-rbac');
module.exports.main = function easySessionMain(connect, opts) {
if(!connect) {
throw new TypeError('expected connect or express or express-session object as first argument');
}
var Session = connect.Session || connect.session.Session;
// Get options
opts = opts || {};
if(typeof opts !== 'object') {
throw new TypeError('expected an options object as second argument');
}
var ipCheck = opts.ipCheck === undefined ? true : !!opts.ipCheck;
var uaCheck = opts.uaCheck === undefined ? true : !!opts.uaCheck;
var freshTimeout = opts.freshTimeout || (5 * 60 * 1000);
var maxFreshTimeout = opts.maxFreshTimeout || (10 * 60 * 1000);
var rbac;
if(opts.rbac) {
rbac = new RBAC(opts.rbac);
}
// Extend the Session object
/**
* Function for logging the user in.
* Regenerates the session and adds _loggedInAt to the session object.
* Depending on the configuration also adds _ip and _ua for continuity checks.
* @param obj - optional properties to set on created session
* @param cb
*/
Session.prototype.login = function login(role, extend, cb) {
if(typeof role === 'function') {
cb = role;
extend = false;
role = 'authenticated';
} else if (typeof role === 'object') {
cb = extend;
extend = role;
role = 'authenticated';
}
if(typeof extend === 'function') {
cb = extend;
extend = false;
} else if (extend && typeof extend !== 'object') {
throw new TypeError('Second parameter expected to be an object');
}
var req = this.req;
this.regenerate(function (err) {
if(err) {
cb(err);
return;
}
// Add logged in date
req.session._loggedInAt = Date.now();
req.session._lastRequestAt = Date.now();
req.session.setRole(role);
if(ipCheck) {
req.session._ip = req.ip;
}
if(uaCheck) {
req.session._ua = req.headers['user-agent'];
}
if(extend) {
Object.keys(extend).forEach(function (key) {
req.session[key] = extend[key];
});
}
req.session.save();
cb();
});
};
/**
* Function for logging out the user.
* Is just a proxy for session regeneration.
* @param cb
* @returns {*}
*/
Session.prototype.logout = function logout(cb) {
return this.regenerate(cb);
};
var oldResetMaxAge = Session.prototype.resetMaxAge;
Session.prototype.resetMaxAge = function resetMaxAge() {
this._lastRequestAt = Date.now();
return oldResetMaxAge.call(this);
};
/**
* Function for setting the last request for current moment
* @returns {*}
*/
Session.prototype.setLastRequest = function setLastRequest() {
this._lastRequestAt = Date.now();
};
/**
* Function for checking if the user is a guest.
* Returns true if logged out, false if logged in.
* @returns {boolean}
*/
Session.prototype.isGuest = function isGuest() {
return !this._loggedInAt; // If this is not set then we are not logged in
};
/**
* Function for checking if the user is logged in.
* Returns true if logged id, false if logged out.
*
* @param [optional] {string} - If present the user is also checked for the role
* @returns {boolean}
*/
Session.prototype.isLoggedIn = function isLoggedIn(role) {
if(!role) {
return !this.isGuest();
}
return !this.isGuest() && this.hasRole(role);
};
/**
* Function for checking if the logged in session is fresh or stale.
* Returns true if fresh, false if stale.
* @returns {boolean}
*/
Session.prototype.isFresh = function isFresh() {
if(!this._loggedInAt) {
return false;
}
var age = Date.now() - this._loggedInAt;
if(age > (maxFreshTimeout)) {
return false;
}
if(age < freshTimeout || (Date.now() - this._lastRequestAt) < (freshTimeout)) {
return true;
}
return false;
};
/**
* Function setting a role on the session
* @returns {boolean}
*/
Session.prototype.setRole = function setRole(role) {
this._role = role;
return this;
};
/**
* Function getting a role from the session
* @returns {boolean}
*/
Session.prototype.getRole = function getRole() {
return this._role || 'guest';
};
/**
* Function checking the session role
*
* returns true if given role matches the session role, false otherwise
* @returns {boolean}
*/
Session.prototype.hasRole = function hasRole(role, reverse) {
if(reverse) {
return this.hasNotRole(role);
}
var current = this.getRole();
if(Array.isArray(role)) {
return role.indexOf(current) !== -1;
}
return current === role;
};
/**
* Function checking the session role not to match a set
*
* returns false if given role matches the session role, true otherwise
* @returns {boolean}
*/
Session.prototype.hasNotRole = function hasNotRole(role) {
var current = this.getRole();
if(Array.isArray(role)) {
return role.indexOf(current) === -1;
}
return current !== role;
};
if(rbac) {
Session.prototype.can = function can(operation, params, cb) {
return rbac.can(this.getRole(), operation, params, cb);
};
}
/**
* Middleware for removing cookies from browser cache and
* depending on configuration checking if users IP and UA have changed mid session.
*/
return function sessionMiddleware(req, res, next) {
// Remove cookies from cache - a security feature
res.header('Cache-Control', 'no-cache="Set-Cookie, Set-Cookie2"');
if(!req.session) { // If there is no session then something is wrong
next(new Error('Session object missing'));
return;
}
function refresh(){
res.removeListener('finish', refresh);
res.removeListener('close', refresh);
req.session.setLastRequest();
}
res.on('finish', refresh);
res.on('close', refresh);
if(req.session.isGuest()) { // If not logged in then continue
next();
return;
}
if(ipCheck && req.session._ip !== req.ip) { // Check if IP matches
// It would be wise to log more information here to either notify the user or
// to try and prevent further attacks
console.warn('The request IP did not match session IP');
// Generate a new unauthenticated session
req.session.logout(next);
return;
}
if(uaCheck && req.session._ua !== req.headers['user-agent']) { // Check if UA matches
// It would be wise to log more information here to either notify the user or
// to try and prevent further attacks
console.warn('The request User Agent did not match session user agent');
// Generate a new unauthenticated session
req.session.logout(next);
return;
}
// Everything checks out so continue
next();
};
};
/**
* An express/connect middleware for checking if the user is loggedIn
* @param errorCallback
* @returns {Function}
*/
function isLoggedIn(errorCallback) {
return function (req, res, next) {
if(req.session.isLoggedIn()) {
next();
return;
}
if(errorCallback) {
errorCallback(req, res, next);
return;
}
(res.sendStatus || res.send).call(res, 401);
};
}
module.exports.isLoggedIn = isLoggedIn;
/**
* An express/connect middleware for checking if the user is loggedIn and session isFresh
* @param errorCallback
* @returns {Function}
*/
function isFresh(errorCallback) {
return function (req, res, next) {
if(req.session.isFresh()) {
next();
return;
}
if(errorCallback) {
errorCallback(req, res, next);
return;
}
(res.sendStatus || res.send).call(res, 401);
};
}
module.exports.isFresh = isFresh;
/**
* An express/connect middleware for checking if the user is logged in and has
* certain _role value
*
* @param role - role to check for
* @param reverse - secondary parameter for hasRole
* @param errorCallback
* @returns {Function}
*/
module.exports.checkRole = function checkRole(role, reverse, errorCallback) {
if(typeof reverse === 'function') {
errorCallback = reverse;
reverse = false;
}
return function (req, res, next) { // Check role
if(req.session.hasRole(role, reverse)) {
next();
return;
}
if(errorCallback) {
errorCallback(req, res, next);
return;
}
(res.sendStatus || res.send).call(res, 401);
};
};
/**
* An express/connect middleware factory for checking if the is allowed for operation
*
* @param operation - operation to check for
* @param params - secondary parameter for can
* @param errorCallback
* @returns {Function}
*/
module.exports.can = function can(operation, params, errorCallback) {
if(typeof operation !== 'string') {
throw new TypeError('Expected first parameter to be string');
}
return function canAccess(req, res, next) {
var resultFn = function (err, can) {
if(err || !can) {
errFn();
return;
}
next();
};
var errFn = function () {
if(errorCallback) {
errorCallback(req, res, next);
return;
}
(res.sendStatus || res.send).call(res, 403);
};
if(typeof params === 'function') {
params(req, res, function (err, data) {
if(err) {
errFn(new Error('RBAC check failed'));
return;
}
req.session.can(operation, data, resultFn);
});
return;
}
req.session.can(operation, params, resultFn);
};
};