forked from julianlam/nodebb-plugin-session-sharing
-
Notifications
You must be signed in to change notification settings - Fork 2
/
library.js
817 lines (733 loc) · 22.5 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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
'use strict'
/* globals process, require, module */
var meta = module.parent.require('./meta')
var user = module.parent.require('./user')
var groups = module.parent.require('./groups')
var SocketPlugins = require.main.require('./src/socket.io/plugins')
var _ = module.parent.require('underscore')
var winston = module.parent.require('winston')
var async = require('async')
var db = module.parent.require('./database')
var nconf = module.parent.require('nconf')
var jwt = require('jsonwebtoken')
var controllers = require('./lib/controllers')
var nbbAuthController = module.parent.require('./controllers/authentication')
/* all the user profile fields that can be passed to user.updateProfile */
var profileFields = [
'username',
'email',
'fullname',
'website',
'location',
'groupTitle',
'birthday',
'signature',
'aboutme',
'email:confirmed'
]
var payloadKeys = profileFields.concat([
'id', // the uniq identifier of that account
'firstName', // for backwards compatibillity
'lastName', // dto.
'picture',
'groups'
])
var plugin = {
ready: false,
settings: {
name: 'appId',
cookieName: 'token',
cookieDomain: undefined,
secret: '',
behaviour: 'trust',
noRegistration: 'off',
payloadParent: undefined,
forceresign: 'on',
jwtmode: 'client'
}
}
payloadKeys.forEach(function (key) {
plugin.settings['payload:' + key] = key
})
plugin.init = function (params, callback) {
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/lookup', controllers.retrieveUser)
if (process.env.NODE_ENV === 'development') {
router.get('/debug/session', plugin.generate)
}
plugin.reloadSettings(callback)
}
plugin.appendConfig = function (config, callback) {
config.sessionSharing = {
logoutRedirect: plugin.settings.logoutRedirect,
loginOverride: plugin.settings.loginOverride,
registerOverride: plugin.settings.registerOverride
}
callback(null, config)
}
/* Websocket Listeners */
SocketPlugins.sessionSharing = {}
SocketPlugins.sessionSharing.showUserIds = function (socket, data, callback) {
// Retrieve the hash and find matches
var uids = data.uids
var payload = []
// var match, idx
payload.length = uids.length
if (uids.length) {
async.map(
uids,
function (uid, next) {
db.getSortedSetRangeByScore(
plugin.settings.name + ':uid',
0,
-1,
uid,
uid,
next
)
},
function (err, remoteIds) {
if (err) {
winston.warn(err)
}
remoteIds.forEach(function (remoteId, idx) {
payload[idx] = remoteId
})
callback(null, payload)
}
)
} else {
callback(new Error('no-uids-supplied'))
}
}
SocketPlugins.sessionSharing.findUserByRemoteId = function (
socket,
data,
callback
) {
if (data.remoteId) {
plugin.getUser(data.remoteId, callback)
} else {
callback(new Error('no-remote-id-supplied'))
}
}
/* End Websocket Listeners */
/*
* Given a remoteId, show user data
*/
plugin.getUser = function (remoteId, callback) {
async.waterfall(
[
async.apply(db.sortedSetScore, plugin.settings.name + ':uid', remoteId),
function (uid, next) {
if (uid) {
user.getUserFields(uid, ['username', 'userslug', 'picture'], next)
} else {
setImmediate(next)
}
}
],
callback
)
}
plugin.process = function (token, callback) {
async.waterfall(
[
async.apply(jwt.verify, token, plugin.settings.secret),
async.apply(plugin.normalizePayload),
async.apply(plugin.findOrCreateUser),
async.apply(plugin.updateUserProfile),
async.apply(plugin.updateUserGroups),
async.apply(plugin.verifyUser)
],
callback
)
}
plugin.normalizePayload = function (payload, callback) {
var 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)
return callback(new Error('payload-invalid'))
}
payloadKeys.forEach(function (key) {
var propName = plugin.settings['payload:' + key]
if (propName) {
userData[key] = payload[propName]
}
})
if (!userData.id) {
winston.warn('[session-sharing] No user id was given in payload')
return callback(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')
return callback(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
}
winston.verbose('[session-sharing] Payload verified')
callback(null, userData)
}
plugin.verifyUser = function (uid, callback) {
// Check ban state of user, reject if banned
var isBanned = async function () {
return await user.bans.isBanned(uid)
}
isBanned.then(banned => callback(banned ? new Error('banned') : null, uid), () => callback(new Error('banned'), uid))
}
plugin.findOrCreateUser = function (userData, callback) {
var queries = {}
if (userData.email && userData.email.length) {
queries.mergeUid = async.apply(
db.sortedSetScore,
'email:uid',
userData.email
) // mergeUid:本地账户邮箱对应的UID
}
queries.uid = async.apply(
db.sortedSetScore,
plugin.settings.name + ':uid',
userData.id
) // uid:JWT ID对应的本地UID
async.parallel(queries, function (err, checks) {
if (err) {
return callback(err)
}
async.waterfall(
[
/* check if found something to work with */
function (next) {
if (checks.uid && !isNaN(parseInt(checks.uid, 10))) {
console.log('has_ZUID')
var uid = parseInt(checks.uid, 10)
/* check if the user with the given id actually exists */
return user.exists(uid, function (err, exists) {
/* ignore errors, but assume the user doesn't exist */
if (err) {
winston.warn(
'[session-sharing] Error while testing user existance',
err
)
return next(null, null)
}
if (exists) {
return next(null, uid)
}
/* reference is outdated, user got deleted */
db.sortedSetRemove(
plugin.settings.name + ':uid',
userData.id,
function (err) {
next(err, null)
}
)
})
}
if (checks.mergeUid && !isNaN(parseInt(checks.mergeUid, 10))) {
console.log('has_MUID')
winston.info(
'[session-sharing] Found user via their email, associating this id (' +
userData.id +
') with their NodeBB account'
)
return db.sortedSetAdd(
plugin.settings.name + ':uid',
checks.mergeUid,
userData.id,
function (err) {
next(err, parseInt(checks.mergeUid, 10))
}
)
}
setImmediate(next, null, null)
},
/* create the user from payload if necessary */
function (uid, next) {
winston.debug('createUser?', !uid)
if (!uid) {
if (plugin.settings.noRegistration === 'on') {
return next(new Error('no-match'))
}
return plugin.createUser(userData, function (err, uid) {
next(err, uid, userData, true)
})
}
setImmediate(next, null, uid, userData, false)
}
],
callback
)
})
}
plugin.updateUserProfile = function (uid, userData, isNewUser, callback) {
winston.debug(
'consider updateProfile?',
isNewUser || plugin.settings.updateProfile === 'on'
)
/* even update the profile on a new account, since some fields are not initialized by NodeBB */
if (!isNewUser && plugin.settings.updateProfile !== 'on') {
return setImmediate(callback, null, uid, userData, isNewUser)
}
async.waterfall(
[
function (next) {
user.getUserFields(uid, profileFields, next)
},
function (existingFields, next) {
var obj = {}
profileFields.forEach(function (field) {
if (
typeof userData[field] !== 'undefined' &&
existingFields[field] !== userData[field]
) {
obj[field] = userData[field]
}
})
if (Object.keys(obj).length) {
winston.debug('[session-sharing] Updating profile fields:', obj)
obj.uid = uid
return user.updateProfile(uid, obj, function (err, userObj) {
if (err) {
winston.warn(
'[session-sharing] Unable to update profile information for uid: ' +
uid +
'(' +
err.message +
')'
)
}
// If it errors out, not that big of a deal, continue anyway.
next(null, userObj || existingFields)
})
}
setImmediate(next, null, {})
},
function (userObj, next) {
var err = null
if (userData.picture) {
db.setObjectField(
'user:' + uid,
'picture',
userData.picture,
data => {
err = data
}
)
}
if (userData['email:confirmed']) {
db.setObjectField(
'user:' + uid,
'email:confirmed',
userData['email:confirmed'],
data => {
err = data
}
)
winston.warn('user2.5: ' + JSON.stringify(userData))
}
setImmediate(next, err)
}
],
function (err) {
winston.warn('callback for update')
return callback(err, uid, userData, isNewUser)
}
)
}
plugin.updateUserGroups = function (uid, userData, isNewUser, callback) {
if (!userData.groups || !userData.groups.length) {
return setImmediate(callback, null, uid)
}
async.waterfall(
[
// Retrieve user groups
async.apply(groups.getUserGroupsFromSet, 'groups:createtime', [uid]),
function (groups, next) {
// Normalize user group data to just group names
groups = groups[0].map(function (groupObj) {
return groupObj.name
})
// Build join and leave arrays
var join = userData.groups.filter(function (name) {
return !groups.includes(name)
})
var leave = groups.filter(function (name) {
// `registered-users` is always a joined group
if (name === 'registered-users') {
return false
}
return !userData.groups.includes(name)
})
executeJoinLeave(uid, join, leave, next)
}
],
function (err) {
return callback(err, uid)
}
)
}
function executeJoinLeave(uid, join, leave, callback) {
async.parallel(
[
function (next) {
if (plugin.settings.syncGroupJoin !== 'on') {
return setImmediate(next)
}
async.each(
join,
function (name, next) {
groups.join(name, uid, next)
},
next
)
},
function (next) {
if (plugin.settings.syncGroupLeave !== 'on') {
return setImmediate(next)
}
async.each(
leave,
function (name, next) {
groups.leave(name, uid, next)
},
next
)
}
],
callback
)
}
plugin.createUser = function (userData, callback) {
winston.verbose(
'[session-sharing] No user found, creating a new user for this login'
)
user.create(_.pick(userData, profileFields), function (err, uid) {
if (err) {
return callback(err)
}
db.sortedSetAdd(plugin.settings.name + ':uid', uid, userData.id, function (
err
) {
callback(err, uid)
})
})
}
plugin.parseAuthorizationHeader = function (req) {
if (req.headers && req.headers.authorization) {
var parts = req.headers.authorization.split(' ')
if (parts.length === 2 && parts[0] === 'Bearer') {
return parts[1]
}
}
}
plugin.addMiddleware = function (req, res, next) {
function handleGuest(req, res, next) {
if (
plugin.settings.guestRedirect &&
!req.originalUrl.startsWith(nconf.get('relative_path') + '/login?local=1')
) {
// If a guest redirect is specified, follow it
res.redirect(
plugin.settings.guestRedirect.replace(
'%1',
encodeURIComponent(nconf.get('url') + req.originalUrl)
)
)
} else if (res.locals.fullRefresh === true) {
res.redirect(nconf.get('relative_path') + req.url)
} else {
next()
}
}
// Only respond to page loads by guests and api, not asset calls
var hasSession =
req.hasOwnProperty('user') &&
req.user.hasOwnProperty('uid') &&
parseInt(req.user.uid, 10) > 0
var hasLoginLock = req.session.hasOwnProperty('loginLock')
var hasJwt = !!(
(Object.keys(req.cookies).length &&
req.cookies.hasOwnProperty(plugin.settings.cookieName) &&
req.cookies[plugin.settings.cookieName].length) ||
plugin.parseAuthorizationHeader(req)
)
if (
!plugin.ready || // plugin not ready
(plugin.settings.behaviour === 'trust' && hasSession) || // user logged in + "trust" behaviour
(plugin.settings.behaviour === 'revalidate' && hasLoginLock)
) {
var uid = parseInt(req.user.uid, 10)
if (
plugin.settings.jwtmode === 'host' &&
((hasJwt && plugin.settings.forceresign === 'on') || !hasJwt)
) {
user.getUserFields(
uid,
[
'username',
'email',
'location',
'birthday',
'website',
'aboutme',
'signature',
'picture',
'email:confirmed'
],
function (err, usr) {
if (err) {
return false
} else {
plugin.settings['payload:email:confirmed'] = 'email:confirmed'
var payload = {}
payload[plugin.settings['payload:id']] = usr.uid
// delete usr.uid;
for (const key in usr) {
if (usr.hasOwnProperty(key)) {
if (key === 'uid') {
payload[plugin.settings['payload:id']] = usr['uid']
} else payload[plugin.settings['payload:' + key]] = usr[key]
}
}
payload[plugin.settings['payload:picture']] =
typeof payload[plugin.settings['payload:picture']] === 'string' &&
payload[plugin.settings['payload:picture']].length > 1
? nconf.get('url') +
'/' +
payload[plugin.settings['payload:picture']]
: payload[plugin.settings['payload:picture']]
if (
plugin.settings['payloadParent'] ||
plugin.settings['payload:parent']
) {
var parentKey =
plugin.settings['payloadParent'] ||
plugin.settings['payload:parent']
var newPayload = {}
newPayload[parentKey] = payload
payload = newPayload
}
db.sortedSetAdd(plugin.settings.name + ':uid', uid, uid, function (
err
) {
if (err) console.log('dberr')
})
var token = jwt.sign(payload, plugin.settings.secret)
// console.dir(token);
res.cookie(plugin.settings.cookieName, token, {
maxAge: 1000 * 60 * 60 * 24 * 21,
httpOnly: true,
domain: plugin.settings.cookieDomain
})
}
}
)
}
// console.log('t_has_s');
delete req.session.loginLock // remove login lock for "revalidate" logins
return next()
} else {
// Hook into ip blacklist functionality in core
meta.blacklist.test(req.ip, function (err) {
if (err) {
console.log('blk_err')
if (hasSession) {
req.logout()
res.locals.fullRefresh = true
}
plugin.cleanup({ res: res })
return handleGuest(req, res, next)
} else {
if (hasJwt && plugin.settings.jwtmode === 'client') {
// console.log('has_jwt');
var token = plugin.parseAuthorizationHeader(req)
? plugin.parseAuthorizationHeader(req)
: req.cookies[plugin.settings.cookieName]
return plugin.process(token, function (err, uid) {
if (err) {
console.log('jwt_err')
switch (err.message) {
case 'banned':
winston.info(
'[session-sharing] uid ' +
uid +
' is banned, not logging them in'
)
next()
break
case 'payload-invalid':
winston.warn(
'[session-sharing] The passed-in payload was invalid and could not be processed'
)
next()
break
case 'no-match':
winston.info(
'[session-sharing] Payload valid, but local account not found. Assuming guest.'
)
handleGuest(req, res, next)
break
default:
winston.warn(
'[session-sharing] Error encountered while parsing token: ' +
err.message
)
next()
break
}
return
}
winston.verbose(
'[session-sharing] Processing login for uid ' +
uid +
', path ' +
req.originalUrl
)
req.uid = uid
console.log('login_jwt')
nbbAuthController.doLogin(req, uid, function () {
req.session.loginLock = true
res.redirect(req.originalUrl)
})
})
} else if (hasSession) {
// Has login session but no cookie, can assume "revalidate" behaviour
console.log('has_s_no_jwt')
user.isAdministrator(req.user.uid, function (err, isAdmin) {
if (err) {
winston.warn(err)
}
if (!isAdmin) {
req.logout()
res.locals.fullRefresh = true
handleGuest(req, res, next)
} else {
// Admins can bypass
return next()
}
})
} else {
console.log('lst')
handleGuest(req, res, next)
}
}
})
}
}
plugin.cleanup = function (data, callback) {
if (plugin.settings.cookieDomain) {
winston.verbose('[session-sharing] Clearing cookie')
data.res.clearCookie(plugin.settings.cookieName, {
domain: plugin.settings.cookieDomain,
expires: new Date(),
path: '/'
})
}
if (typeof callback === 'function') {
callback()
} else {
return true
}
}
plugin.generate = function (req, res) {
var 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']) {
var parentKey =
plugin.settings['payloadParent'] || plugin.settings['payload:parent']
var newPayload = {}
newPayload[parentKey] = payload
payload = newPayload
}
var token = jwt.sign(payload, plugin.settings.secret)
console.dir(res)
res.cookie(plugin.settings.cookieName, token, {
maxAge: 1000 * 60 * 60 * 24 * 21,
httpOnly: true,
domain: plugin.settings.cookieDomain
})
console.dir(res)
res.sendStatus(200)
}
plugin.addAdminNavigation = function (header, callback) {
header.plugins.push({
route: '/plugins/session-sharing',
icon: 'fa-user-secret',
name: 'Session Sharing'
})
callback(null, header)
}
plugin.reloadSettings = function (callback) {
meta.settings.get('session-sharing', function (err, settings) {
if (err) {
return callback(err)
}
if (!settings.hasOwnProperty('secret') || !settings.secret.length) {
winston.error(
'[session-sharing] JWT Secret not found, session sharing disabled.'
)
return callback()
}
// 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']
db.setObjectField(
'settings:session-sharing',
'payloadParent',
settings.payloadParent
)
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(_.pick(settings, Boolean), plugin.settings)
plugin.ready = true
callback()
})
}
module.exports = plugin