forked from julianlam/nodebb-plugin-session-sharing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
library.js
643 lines (527 loc) · 19.4 KB
/
library.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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
'use strict';
const winston = module.parent.require('winston');
const nconf = module.parent.require('nconf');
const util = require('util');
const _ = require('lodash');
const jwt = require('jsonwebtoken');
const meta = require.main.require('./src/meta');
const user = require.main.require('./src/user');
const groups = require.main.require('./src/groups');
const messaging = require.main.require('./src/messaging');
const SocketPlugins = require.main.require('./src/socket.io/plugins');
const db = require.main.require('./src/database');
const plugins = require.main.require('./src/plugins');
const controllers = require('./lib/controllers');
const nbbAuthController = require.main.require('./src/controllers/authentication');
const logoutAsync = util.promisify((req, callback) => req.logout(callback));
/* all the user profile fields that can be passed to user.updateProfile */
const profileFields = [
'username',
'email',
'fullname',
'website',
'location',
'groupTitle',
'birthday',
'signature',
'aboutme',
'did',
];
const payloadKeys = profileFields.concat([
'id', // the uniq identifier of that account
'firstName', // for backwards compatibillity
'lastName', // dto.
'picture',
'groups',
'chatrooms',
]);
const plugin = {
ready: false,
settings: {
name: 'appId',
cookieName: 'token',
cookieDomain: undefined,
secret: '',
behaviour: 'trust',
adminRevalidate: 'off',
noRegistration: 'off',
payloadParent: undefined,
allowBannedUsers: false,
},
};
payloadKeys.forEach(function (key) {
plugin.settings['payload:' + key] = key;
});
plugin.init = async (params) => {
var router = params.router;
var hostMiddleware = params.middleware;
router.get('/admin/plugins/session-sharing', hostMiddleware.admin.buildHeader, controllers.renderAdminPage);
router.get('/api/admin/plugins/session-sharing', controllers.renderAdminPage);
router.get('/api/session-sharing/px.png', controllers.authPixel);
router.get('/api/session-sharing/jwtAuth', controllers.jwtAuth);
router.get('/api/session-sharing/lookup', controllers.retrieveUser);
router.post('/api/session-sharing/user', controllers.process);
router.get('/api/session-sharing/groups/:slug/chat', controllers.getChatRoomByGroup);
if (process.env.NODE_ENV === 'development') {
router.get('/debug/session', plugin.generate);
}
await plugin.reloadSettings();
};
plugin.appendConfig = async (config) => {
config.sessionSharing = {
logoutRedirect: plugin.settings.logoutRedirect,
loginOverride: plugin.settings.loginOverride,
registerOverride: plugin.settings.registerOverride,
editOverride: plugin.settings.editOverride,
hostWhitelist: plugin.settings.hostWhitelist,
};
return config;
};
/* Websocket Listeners */
SocketPlugins.sessionSharing = {};
SocketPlugins.sessionSharing.showUserIds = async (socket, data) => {
// Retrieve the hash and find matches
const { uids } = data;
if (!uids.length) {
throw new Error('no-uids-supplied');
}
return Promise.all(uids.map(async uid => db.getSortedSetRangeByScore(plugin.settings.name + ':uid', 0, -1, uid, uid)));
};
SocketPlugins.sessionSharing.findUserByRemoteId = async (socket, data) => {
if (!data.remoteId) {
throw new Error('no-remote-id-supplied');
}
return plugin.getUser(data.remoteId);
};
/* End Websocket Listeners */
/*
* Given a remoteId, show user data
*/
plugin.getUser = async (remoteId) => {
const uid = await db.sortedSetScore(plugin.settings.name + ':uid', remoteId);
if (!uid) {
return;
}
return user.getUserFields(uid, ['username', 'userslug', 'picture', 'did']);
};
plugin.process = async (token) => {
const payload = await jwt.verify(token, plugin.settings.secret);
const userData = await plugin.normalizePayload(payload);
const [uid, isNewUser] = await plugin.findOrCreateUser(userData);
await plugin.updateUserProfile(uid, userData, isNewUser);
await plugin.updateUserGroups(uid, userData);
await plugin.updateUserChatrooms(uid, userData);
await plugin.verifyUser(token, uid, isNewUser);
return uid;
};
plugin.normalizePayload = async (payload) => {
const userData = {};
if (plugin.settings.payloadParent) {
payload = payload[plugin.settings.payloadParent];
}
if (typeof payload !== 'object') {
winston.warn('[session-sharing] the payload is not an object', payload);
throw new Error('payload-invalid');
}
payloadKeys.forEach(function (key) {
const propName = plugin.settings['payload:' + key];
if (payload[propName]) {
userData[key] = payload[propName];
}
});
if (!userData.id) {
winston.warn('[session-sharing] No user id was given in payload');
throw new Error('payload-invalid');
}
userData.fullname = (userData.fullname || [userData.firstName, userData.lastName].join(' ')).trim();
if (!userData.username) {
userData.username = userData.fullname;
}
/* strip username from illegal characters */
userData.username = userData.username.trim().replace(/[^'"\s\-.*0-9\u00BF-\u1FFF\u2C00-\uD7FF\w]+/, '-');
if (!userData.username) {
winston.warn('[session-sharing] No valid username could be determined');
throw new Error('payload-invalid');
}
if (userData.hasOwnProperty('groups') && !Array.isArray(userData.groups)) {
winston.warn('[session-sharing] Array expected for `groups` in JWT payload. Ignoring.');
delete userData.groups;
}
if (userData.hasOwnProperty('chatrooms') && !Array.isArray(userData.chatrooms)) {
winston.warn('[session-sharing] Array expected for `chatrooms` in JWT payload. Ignoring.');
delete userData.groups;
}
winston.verbose('[session-sharing] Payload verified');
const data = await plugins.hooks.fire('filter:sessionSharing.normalizePayload', {
payload: payload,
userData: userData,
});
return data.userData;
};
plugin.verifyUser = async (token, uid, isNewUser) => {
await plugins.hooks.fire('static:sessionSharing.verifyUser', {
uid: uid,
isNewUser: isNewUser,
token: token,
});
// Check ban state of user
const isBanned = await user.bans.isBanned(uid);
// Reject if banned and settings dont allow banned users to login
if (isBanned && !plugin.settings.allowBannedUsers) {
throw new Error('banned');
}
};
plugin.findOrCreateUser = async (userData) => {
const { id } = userData;
let isNewUser = false;
let userId = null;
let queries = [db.sortedSetScore(plugin.settings.name + ':uid', userData.id)];
if (userData.email && userData.email.length) {
queries = [...queries, db.sortedSetScore('email:uid', userData.email)];
}
let [uid, mergeUid] = await Promise.all(queries);
uid = parseInt(uid, 10);
mergeUid = parseInt(mergeUid, 10);
/* check if found something to work with */
if (uid && !isNaN(uid)) {
try {
/* check if the user with the given id actually exists */
const exists = await user.exists(uid);
if (exists) {
userId = uid;
} else {
/* reference is outdated, user got deleted */
await db.sortedSetRemove(plugin.settings.name + ':uid', id);
}
} catch (error) {
/* ignore errors, but assume the user doesn't exist */
winston.warn('[session-sharing] Error while testing user existance', error);
}
}
if (!userId && mergeUid && !isNaN(mergeUid)) {
winston.info('[session-sharing] Found user via their email, associating this id (' + id + ') with their NodeBB account');
await db.sortedSetAdd(plugin.settings.name + ':uid', mergeUid, id);
userId = mergeUid;
}
/* create the user from payload if necessary */
winston.debug('createUser?', !userId);
if (!userId) {
if (plugin.settings.noRegistration === 'on') {
throw new Error('no-match');
}
userId = await plugin.createUser(userData);
isNewUser = true;
}
return [userId, isNewUser];
};
plugin.updateUserProfile = async (uid, userData, isNewUser) => {
winston.debug('consider updateProfile?', isNewUser || plugin.settings.updateProfile === 'on');
let userObj = {};
/* even update the profile on a new account, since some fields are not initialized by NodeBB */
if (!isNewUser && plugin.settings.updateProfile !== 'on') {
return;
}
const existingFields = await user.getUserFields(uid, profileFields);
const obj = profileFields.reduce((result, field) => {
if (typeof userData[field] !== 'undefined' && existingFields[field] !== userData[field]) {
result[field] = userData[field];
}
return result;
}, {});
if (Object.keys(obj).length) {
winston.debug('[session-sharing] Updating profile fields:', obj);
obj.uid = uid;
try {
userObj = await user.updateProfile(uid, obj);
// If it errors out, not that big of a deal, continue anyway.
if (!userObj) {
userObj = existingFields;
}
} catch (error) {
winston.warn('[session-sharing] Unable to update profile information for uid: ' + uid + '(' + error.message + ')');
}
}
if (userData.picture) {
await db.setObjectField('user:' + uid, 'picture', userData.picture);
}
};
plugin.updateUserGroups = async (uid, userData) => {
if (!userData.groups || !Array.isArray(userData.groups)) {
return;
}
// Retrieve user groups
let [userGroups] = await groups.getUserGroupsFromSet('groups:createtime', [uid]);
// Normalize user group data to just group names
userGroups = userGroups.map(groupObj => groupObj.name);
// Build join and leave arrays
let join = userData.groups.filter(name => !userGroups.includes(name));
if (plugin.settings.syncGroupList === 'on') {
join = join.filter(group => plugin.settings.syncGroups.includes(group));
}
let leave = userGroups.filter((name) => {
// `registered-users` is always a joined group
if (name === 'registered-users') {
return false;
}
return !userData.groups.includes(name);
});
if (plugin.settings.syncGroupList === 'on') {
leave = leave.filter(group => plugin.settings.syncGroups.includes(group));
}
await executeJoinLeave(uid, join, leave);
};
plugin.updateUserChatrooms = async (uid, userData) => {
if (!userData.chatrooms || !Array.isArray(userData.chatrooms)) {
return;
}
userData.chatrooms.forEach(async (roomId) => {
if (!await messaging.isUserInRoom(uid, roomId)) {
messaging.addUsersToRoom(1, [uid], roomId);
}
});
};
plugin.getChatroomForGroup = async (slug) => {
const result = await db.client.collection('objects')
.findOne({
_key: {
$regex: '^chat:room:\\d+$' },
groups: '["' + slug + '"]',
}, { _id: false });
return result;
};
async function executeJoinLeave(uid, join, leave) {
await Promise.all([
(async () => {
if (plugin.settings.syncGroupJoin !== 'on') {
return;
}
await Promise.all(join.map(name => groups.join(name, uid)));
})(),
(async () => {
if (plugin.settings.syncGroupLeave !== 'on') {
return;
}
await Promise.all(leave.map(name => groups.leave(name, uid)));
})(),
]);
}
plugin.createUser = async (userData) => {
winston.verbose('[session-sharing] No user found, creating a new user for this login');
const uid = await user.create(_.pick(userData, profileFields));
await db.sortedSetAdd(plugin.settings.name + ':uid', uid, userData.id);
return uid;
};
plugin.addMiddleware = async function ({ req, res }) {
const { hostWhitelist, guestRedirect, editOverride, loginOverride, registerOverride } = await meta.settings.get('session-sharing');
if (hostWhitelist) {
const hosts = hostWhitelist.split(',') || [hostWhitelist];
let whitelisted = false;
for (const host of hosts) {
if (req.headers.host.includes(host)) {
whitelisted = true;
break;
}
}
if (!whitelisted) {
return;
}
}
function handleGuest(req, res) {
if (guestRedirect && !req.originalUrl.startsWith(nconf.get('relative_path') + '/login?local=1')) {
// If a guest redirect is specified, follow it
res.redirect(guestRedirect.replace('%1', encodeURIComponent(req.protocol + '://' + req.get('host') + req.originalUrl)));
} else if (res.locals.fullRefresh === true) {
res.redirect(nconf.get('relative_path') + req.url);
}
}
// Only respond to page loads by guests, not api or asset calls
const hasSession = req.hasOwnProperty('user') && req.user.hasOwnProperty('uid') && parseInt(req.user.uid, 10) > 0;
const hasLoginLock = req.session.hasOwnProperty('loginLock');
if (
!plugin.ready || // plugin not ready
(plugin.settings.behaviour === 'trust' && hasSession) || // user logged in + "trust" behaviour
((plugin.settings.behaviour === 'revalidate' || plugin.settings.behaviour === 'update') && hasLoginLock) ||
req.originalUrl.startsWith(nconf.get('relative_path') + '/api') // api routes
) {
// Let requests through under "update" or "revalidate" behaviour only if they're logging in for the first time
delete req.session.loginLock; // remove login lock for "update" or "revalidate" logins
return;
}
if (editOverride && hasSession && req.originalUrl.match(/\/user\/.*\/edit(\/\w+)?$/)) {
return res.redirect(editOverride.replace('%1', encodeURIComponent(req.protocol + '://' + req.get('host') + req.originalUrl)));
}
if (loginOverride && req.originalUrl.match(/\/login$/)) {
return res.redirect(loginOverride.replace('%1', encodeURIComponent(req.protocol + '://' + req.get('host') + req.originalUrl)));
}
if (registerOverride && req.originalUrl.match(/\/register$/)) {
return res.redirect(registerOverride.replace('%1', encodeURIComponent(req.protocol + '://' + req.get('host') + req.originalUrl)));
}
// Hook into ip blacklist functionality in core
try {
await meta.blacklist.test(req.ip);
} catch (error) {
if (hasSession) {
await logoutAsync(req);
res.locals.fullRefresh = true;
}
await plugin.cleanup({ res: res });
return handleGuest.call(null, req, res);
}
if (Object.keys(req.cookies).length && req.cookies.hasOwnProperty(plugin.settings.cookieName) && req.cookies[plugin.settings.cookieName].length) {
try {
const uid = await plugin.process(req.cookies[plugin.settings.cookieName]);
if (uid === req.uid) {
winston.verbose(`[session-sharing] Re-validated login for uid ${uid}, path ${req.originalUrl}`);
return;
}
winston.verbose('[session-sharing] Processing login for uid ' + uid + ', path ' + req.originalUrl);
await nbbAuthController.doLogin(req, uid);
req.session.loginLock = true;
const url = req.session.returnTo || req.originalUrl.replace(nconf.get('relative_path'), '');
delete req.session.returnTo;
res.redirect(nconf.get('relative_path') + url);
} catch (error) {
let handleAsGuest = false;
switch (error.message) {
case 'payload-invalid':
winston.warn('[session-sharing] The passed-in payload was invalid and could not be processed');
break;
case 'no-match':
winston.info('[session-sharing] Payload valid, but local account not found. Assuming guest.');
handleAsGuest = true;
break;
default:
winston.warn('[session-sharing] Error encountered while parsing token: ' + error.message);
break;
}
const data = await plugins.hooks.fire('filter:sessionSharing.error', {
error,
res: res,
settings: plugin.settings,
handleAsGuest: handleAsGuest,
});
if (data.handleAsGuest) {
return handleGuest.call(error, req, res);
}
throw error;
}
} else if (hasSession) {
// Has login session but no cookie, can assume "revalidate" behaviour
const isAdmin = await user.isAdministrator(req.user.uid);
if (plugin.settings.behaviour !== 'update' && (plugin.settings.adminRevalidate === 'on' || !isAdmin)) {
winston.verbose(`[session-sharing] Found login session but no cookie, logging out user (was uid ${req.uid})`);
await logoutAsync(req);
res.locals.fullRefresh = true;
return handleGuest(req, res);
}
} else {
return handleGuest.call(null, req, res);
}
};
plugin.cleanup = async (data) => {
if (plugin.settings.cookieDomain) {
winston.verbose('[session-sharing] Clearing cookie');
data.res.clearCookie(plugin.settings.cookieName, {
domain: plugin.settings.cookieDomain,
expires: new Date(),
path: '/',
});
}
data.res.clearCookie('nbb_token', {
domain: plugin.settings.cookieDomain,
expires: new Date(),
path: '/',
});
return true;
};
plugin.generate = function (req, res) {
if (!plugin.ready) {
return res.sendStatus(404);
}
let payload = {};
payload[plugin.settings['payload:id']] = 1;
payload[plugin.settings['payload:username']] = 'testUser';
payload[plugin.settings['payload:email']] = '[email protected]';
payload[plugin.settings['payload:firstName']] = 'Test';
payload[plugin.settings['payload:lastName']] = 'User';
payload[plugin.settings['payload:location']] = 'Testlocation';
payload[plugin.settings['payload:birthday']] = '04/01/1981';
payload[plugin.settings['payload:website']] = 'nodebb.org';
payload[plugin.settings['payload:aboutme']] = 'I am just testing';
payload[plugin.settings['payload:signature']] = 'T User';
payload[plugin.settings['payload:groupTitle']] = 'TestUsers';
payload[plugin.settings['payload:groups']] = ['test-group'];
if (plugin.settings.payloadParent || plugin.settings['payload:parent']) {
const parentKey = plugin.settings.payloadParent || plugin.settings['payload:parent'];
const newPayload = {};
newPayload[parentKey] = payload;
payload = newPayload;
}
const token = jwt.sign(payload, plugin.settings.secret);
res.cookie(plugin.settings.cookieName, token, {
maxAge: 1000 * 60 * 60 * 24 * 21,
httpOnly: true,
domain: plugin.settings.cookieDomain,
});
res.sendStatus(200);
};
plugin.addAdminNavigation = async (header) => {
header.plugins.push({
route: '/plugins/session-sharing',
icon: 'fa-user-secret',
name: 'Session Sharing',
});
return header;
};
plugin.reloadSettings = async (data) => {
// If data argument is truthy, then it is the action hook from core
if (data && data.plugin !== 'session-sharing') {
return;
}
const settings = await meta.settings.get('session-sharing');
if (!settings.hasOwnProperty('secret') || !settings.secret.length) {
winston.error('[session-sharing] JWT Secret not found, session sharing disabled.');
return;
}
// If "payload:parent" is found, but payloadParent is not, update the latter and delete the former
if (!settings.payloadParent && settings['payload:parent']) {
winston.verbose('[session-sharing] Migrating payload:parent to payloadParent');
settings.payloadParent = settings['payload:parent'];
await db.setObjectField('settings:session-sharing', 'payloadParent', settings.payloadParent);
await db.deleteObjectField('settings:session-sharing', 'payload:parent');
}
if (!settings['payload:username'] && !settings['payload:firstName'] && !settings['payload:lastName'] && !settings['payload:fullname']) {
settings['payload:username'] = 'username';
}
winston.info('[session-sharing] Settings OK');
plugin.settings = _.defaults(_.pickBy(settings, Boolean), plugin.settings);
plugin.ready = true;
};
plugin.appendTemplate = async (data) => {
if (!data.req.session || !data.req.session.sessionSharing || !data.req.session.sessionSharing.banned) {
return data;
}
const info = await user.getLatestBanInfo(data.req.session.sessionSharing.uid);
data.templateData.sessionSharingBan = {
ban: info,
banned: true,
};
delete data.req.session.sessionSharing;
return data;
};
plugin.saveReverseToken = async ({ req, userData: data }) => {
if (!plugin.ready || !data || plugin.settings.reverseToken !== 'on') {
return; // no reverse token if secret not set
}
const res = req.res;
const userData = await user.getUserFields(data.uid, ['uid', 'username', 'picture', 'reputation', 'postcount', 'banned']);
userData.groups = (await groups.getUserGroups([data.uid])).pop();
const token = jwt.sign(userData, plugin.settings.secret);
res.cookie('nbb_token', token, {
maxAge: meta.getSessionTTLSeconds() * 1000,
httpOnly: true,
domain: plugin.settings.cookieDomain,
});
winston.info(`[plugins/session-sharing] Saving reverse cookie for uid ${userData.uid}, session: ${req.session.id}`);
};
module.exports = plugin;