generated from CMU-17313Q/NodeBB-f23
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathuser.js
3122 lines (2744 loc) · 115 KB
/
user.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
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict'
const assert = require('assert')
const async = require('async')
const fs = require('fs')
const path = require('path')
const nconf = require('nconf')
const validator = require('validator')
const request = require('request')
const requestAsync = require('request-promise-native')
const jwt = require('jsonwebtoken')
const db = require('./mocks/databasemock')
const User = require('../src/user')
const Topics = require('../src/topics')
const Categories = require('../src/categories')
const Posts = require('../src/posts')
const Password = require('../src/password')
const groups = require('../src/groups')
const messaging = require('../src/messaging')
const helpers = require('./helpers')
const meta = require('../src/meta')
const file = require('../src/file')
const socketUser = require('../src/socket.io/user')
const apiUser = require('../src/api/users')
const utils = require('../src/utils')
const privileges = require('../src/privileges')
const { isInstructor, isStudent } = require('../src/privileges/users')
describe('User', () => {
let userData
let testUid
let testCid
const plugins = require('../src/plugins')
async function dummyEmailerHook (data) {
// pretend to handle sending emails
}
before((done) => {
// Attach an emailer hook so related requests do not error
plugins.hooks.register('emailer-test', {
hook: 'filter:email.send',
method: dummyEmailerHook
})
Categories.create({
name: 'Test Category',
description: 'A test',
order: 1
}, (err, categoryObj) => {
if (err) {
return done(err)
}
testCid = categoryObj.cid
done()
})
})
after(() => {
plugins.hooks.unregister('emailer-test', 'filter:email.send')
})
beforeEach(() => {
userData = {
username: 'John Smith',
fullname: 'John Smith McNamara',
password: 'swordfish',
email: '[email protected]',
callback: undefined
}
})
const goodImage = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAgCAYAAAABtRhCAAAACXBIWXMAAC4jAAAuIwF4pT92AAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCE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hPi/C959ZFn+TtO0lG3bJ0ql0p85jsPW1haFQoG2tjYkSWpF/Uwmw9raGu+//z7A977vX2+GrP93wSZiTdNOGIbxy3K5/DPHcfYXCoVe27Yzpmm2m6bppVKp/Orqqnv69OmoZVn/mEwm/9TzvP9x138NAMpJ4VFTBr6SAAAAAElFTkSuQmCC'
describe('.create(), when created', () => {
it('should be created properly', async () => {
testUid = await User.create({ username: userData.username, password: userData.password })
assert.ok(testUid)
await User.setUserField(testUid, 'email', userData.email)
await User.email.confirmByUid(testUid)
})
it('should be created properly', async () => {
const email = '<h1>test</h1>@gmail.com'
const uid = await User.create({ username: 'weirdemail', email })
const data = await User.getUserData(uid)
const validationPending = await User.email.isValidationPending(uid, email)
assert.strictEqual(validationPending, true)
assert.equal(data.email, '<h1>test</h1>@gmail.com')
assert.strictEqual(data.profileviews, 0)
assert.strictEqual(data.reputation, 0)
assert.strictEqual(data.postcount, 0)
assert.strictEqual(data.topiccount, 0)
assert.strictEqual(data.lastposttime, 0)
assert.strictEqual(data.banned, false)
})
it('should have a valid email, if using an email', (done) => {
User.create({ username: userData.username, password: userData.password, email: 'fakeMail' }, (err) => {
assert(err)
assert.equal(err.message, '[[error:invalid-email]]')
done()
})
})
it('should error with invalid password', (done) => {
User.create({ username: 'test', password: '1' }, (err) => {
assert.equal(err.message, '[[reset_password:password_too_short]]')
done()
})
})
it('should error with invalid password', (done) => {
User.create({ username: 'test', password: {} }, (err) => {
assert.equal(err.message, '[[error:invalid-password]]')
done()
})
})
it('should error with a too long password', (done) => {
let toolong = ''
for (let i = 0; i < 5000; i++) {
toolong += 'a'
}
User.create({ username: 'test', password: toolong }, (err) => {
assert.equal(err.message, '[[error:password-too-long]]')
done()
})
})
it('should error if username is already taken or rename user', async () => {
let err
async function tryCreate (data) {
try {
return await User.create(data)
} catch (_err) {
err = _err
}
}
const [uid1, uid2] = await Promise.all([
tryCreate({ username: 'dupe1' }),
tryCreate({ username: 'dupe1' })
])
if (err) {
assert.strictEqual(err.message, '[[error:username-taken]]')
} else {
const userData = await User.getUsersFields([uid1, uid2], ['username'])
const userNames = userData.map(u => u.username)
// make sure only 1 dupe1 is created
assert.equal(userNames.filter(username => username === 'dupe1').length, 1)
assert.equal(userNames.filter(username => username === 'dupe1 0').length, 1)
}
})
it('should error if email is already taken', async () => {
let err
async function tryCreate (data) {
try {
return await User.create(data)
} catch (_err) {
err = _err
}
}
await Promise.all([
tryCreate({ username: 'notdupe1', email: '[email protected]' }),
tryCreate({ username: 'notdupe2', email: '[email protected]' })
])
assert.strictEqual(err.message, '[[error:email-taken]]')
})
})
it('should create a instructor properly', async () => {
const instructorUid = await User.create({
username: 'instructor',
fullname: 'instructor fullname',
email: '[email protected]',
password: 'instructorpass',
accounttype: 'instructor'
})
assert.ok(instructorUid)
assert.equal(await isInstructor(instructorUid), true)
assert.equal(await isStudent(instructorUid), false)
})
it('should create a student properly', async () => {
const studentUid = await User.create({
username: 'student',
fullname: 'student fullname',
email: '[email protected]',
password: 'studentpass',
accountType: 'student'
})
assert.ok(studentUid)
assert.equal(await isInstructor(studentUid), false)
assert.equal(await isStudent(studentUid), true)
})
it('should register as a student by default', async () => {
const uid = await User.create({
username: 'some user',
fullname: 'some user fullname',
email: '[email protected]',
password: 'somepassword123'
})
assert.ok(uid)
assert.equal(await isInstructor(uid), false)
assert.equal(await isStudent(uid), true)
})
describe('.uniqueUsername()', () => {
it('should deal with collisions', (done) => {
const users = []
for (let i = 0; i < 10; i += 1) {
users.push({
username: 'Jane Doe',
email: `jane.doe${i}@example.com`
})
}
async.series([
function (next) {
async.eachSeries(users, (user, next) => {
User.create(user, next)
}, next)
},
function (next) {
User.uniqueUsername({
username: 'Jane Doe',
userslug: 'jane-doe'
}, (err, username) => {
assert.ifError(err)
assert.strictEqual(username, 'Jane Doe 9')
next()
})
}
], done)
})
})
describe('.isModerator()', () => {
it('should return false', (done) => {
User.isModerator(testUid, testCid, (err, isModerator) => {
assert.equal(err, null)
assert.equal(isModerator, false)
done()
})
})
it('should return two false results', (done) => {
User.isModerator([testUid, testUid], testCid, (err, isModerator) => {
assert.equal(err, null)
assert.equal(isModerator[0], false)
assert.equal(isModerator[1], false)
done()
})
})
it('should return two false results', (done) => {
User.isModerator(testUid, [testCid, testCid], (err, isModerator) => {
assert.equal(err, null)
assert.equal(isModerator[0], false)
assert.equal(isModerator[1], false)
done()
})
})
})
describe('.getModeratorUids()', () => {
before((done) => {
groups.join('cid:1:privileges:moderate', 1, done)
})
it('should retrieve all users with moderator bit in category privilege', (done) => {
User.getModeratorUids((err, uids) => {
assert.ifError(err)
assert.strictEqual(1, uids.length)
assert.strictEqual(1, parseInt(uids[0], 10))
done()
})
})
after((done) => {
groups.leave('cid:1:privileges:moderate', 1, done)
})
})
describe('.getModeratorUids()', () => {
before((done) => {
async.series([
async.apply(groups.create, { name: 'testGroup' }),
async.apply(groups.join, 'cid:1:privileges:groups:moderate', 'testGroup'),
async.apply(groups.join, 'testGroup', 1)
], done)
})
it('should retrieve all users with moderator bit in category privilege', (done) => {
User.getModeratorUids((err, uids) => {
assert.ifError(err)
assert.strictEqual(1, uids.length)
assert.strictEqual(1, parseInt(uids[0], 10))
done()
})
})
after((done) => {
async.series([
async.apply(groups.leave, 'cid:1:privileges:groups:moderate', 'testGroup'),
async.apply(groups.destroy, 'testGroup')
], done)
})
})
describe('.isReadyToPost()', () => {
it('should error when a user makes two posts in quick succession', (done) => {
meta.config = meta.config || {}
meta.config.postDelay = '10'
async.series([
async.apply(Topics.post, {
uid: testUid,
title: 'Topic 1',
content: 'lorem ipsum',
cid: testCid
}),
async.apply(Topics.post, {
uid: testUid,
title: 'Topic 2',
content: 'lorem ipsum',
cid: testCid
})
], (err) => {
assert(err)
done()
})
})
it('should allow a post if the last post time is > 10 seconds', (done) => {
User.setUserField(testUid, 'lastposttime', +new Date() - (11 * 1000), () => {
Topics.post({
uid: testUid,
title: 'Topic 3',
content: 'lorem ipsum',
cid: testCid
}, (err) => {
assert.ifError(err)
done()
})
})
})
it('should error when a new user posts if the last post time is 10 < 30 seconds', (done) => {
meta.config.newbiePostDelay = 30
meta.config.newbiePostDelayThreshold = 3
User.setUserField(testUid, 'lastposttime', +new Date() - (20 * 1000), () => {
Topics.post({
uid: testUid,
title: 'Topic 4',
content: 'lorem ipsum',
cid: testCid
}, (err) => {
assert(err)
done()
})
})
})
it('should not error if a non-newbie user posts if the last post time is 10 < 30 seconds', (done) => {
User.setUserFields(testUid, {
lastposttime: +new Date() - (20 * 1000),
reputation: 10
}, () => {
Topics.post({
uid: testUid,
title: 'Topic 5',
content: 'lorem ipsum',
cid: testCid
}, (err) => {
assert.ifError(err)
done()
})
})
})
it('should only post 1 topic out of 10', async () => {
await User.create({ username: 'flooder', password: '123456' })
const { jar } = await helpers.loginUser('flooder', '123456')
const titles = new Array(10).fill('topic title')
const res = await Promise.allSettled(titles.map(async (title) => {
const { body } = await helpers.request('post', '/api/v3/topics', {
form: {
cid: testCid,
title,
content: 'the content'
},
jar,
json: true
})
return body.status
}))
const failed = res.filter(res => res.value.code === 'bad-request')
const success = res.filter(res => res.value.code === 'ok')
assert.strictEqual(failed.length, 9)
assert.strictEqual(success.length, 1)
})
})
describe('.search()', () => {
let adminUid
let uid
before(async () => {
adminUid = await User.create({ username: 'noteadmin' })
await groups.join('administrators', adminUid)
})
it('should return an object containing an array of matching users', (done) => {
User.search({ query: 'john' }, (err, searchData) => {
assert.ifError(err)
uid = searchData.users[0].uid
assert.equal(Array.isArray(searchData.users) && searchData.users.length > 0, true)
assert.equal(searchData.users[0].username, 'John Smith')
done()
})
})
it('should search user', async () => {
const searchData = await apiUser.search({ uid: testUid }, { query: 'john' })
assert.equal(searchData.users[0].username, 'John Smith')
})
it('should error for guest', async () => {
try {
await apiUser.search({ uid: 0 }, { query: 'john' })
assert(false)
} catch (err) {
assert.equal(err.message, '[[error:no-privileges]]')
}
})
it('should error with invalid data', async () => {
try {
await apiUser.search({ uid: testUid }, null)
assert(false)
} catch (err) {
assert.equal(err.message, '[[error:invalid-data]]')
}
})
it('should error for unprivileged user', async () => {
try {
await apiUser.search({ uid: testUid }, { searchBy: 'ip', query: '123' })
assert(false)
} catch (err) {
assert.equal(err.message, '[[error:no-privileges]]')
}
})
it('should error for unprivileged user', async () => {
try {
await apiUser.search({ uid: testUid }, { filters: ['banned'], query: '123' })
assert(false)
} catch (err) {
assert.equal(err.message, '[[error:no-privileges]]')
}
})
it('should error for unprivileged user', async () => {
try {
await apiUser.search({ uid: testUid }, { filters: ['flagged'], query: '123' })
assert(false)
} catch (err) {
assert.equal(err.message, '[[error:no-privileges]]')
}
})
it('should search users by ip', async () => {
const uid = await User.create({ username: 'ipsearch' })
await db.sortedSetAdd('ip:1.1.1.1:uid', [1, 1], [testUid, uid])
const data = await apiUser.search({ uid: adminUid }, { query: '1.1.1.1', searchBy: 'ip' })
assert(Array.isArray(data.users))
assert.equal(data.users.length, 2)
})
it('should search users by uid', async () => {
const data = await apiUser.search({ uid: testUid }, { query: uid, searchBy: 'uid' })
assert(Array.isArray(data.users))
assert.equal(data.users[0].uid, uid)
})
it('should search users by fullname', async () => {
const uid = await User.create({ username: 'fullnamesearch1', fullname: 'Mr. Fullname' })
const data = await apiUser.search({ uid: adminUid }, { query: 'mr', searchBy: 'fullname' })
assert(Array.isArray(data.users))
assert.equal(data.users.length, 1)
assert.equal(uid, data.users[0].uid)
})
it('should search users by fullname', async () => {
const uid = await User.create({ username: 'fullnamesearch2', fullname: 'Baris:Usakli' })
const data = await apiUser.search({ uid: adminUid }, { query: 'baris:', searchBy: 'fullname' })
assert(Array.isArray(data.users))
assert.equal(data.users.length, 1)
assert.equal(uid, data.users[0].uid)
})
it('should return empty array if query is empty', async () => {
const data = await apiUser.search({ uid: testUid }, { query: '' })
assert.equal(data.users.length, 0)
})
it('should filter users', async () => {
const uid = await User.create({ username: 'ipsearch_filter' })
await User.bans.ban(uid, 0, '')
await User.setUserFields(uid, { flags: 10 })
const data = await apiUser.search({ uid: adminUid }, {
query: 'ipsearch',
filters: ['online', 'banned', 'flagged']
})
assert.equal(data.users[0].username, 'ipsearch_filter')
})
it('should sort results by username', (done) => {
async.waterfall([
function (next) {
User.create({ username: 'brian' }, next)
},
function (uid, next) {
User.create({ username: 'baris' }, next)
},
function (uid, next) {
User.create({ username: 'bzari' }, next)
},
function (uid, next) {
User.search({
uid: testUid,
query: 'b',
sortBy: 'username',
paginate: false
}, next)
}
], (err, data) => {
assert.ifError(err)
assert.equal(data.users[0].username, 'baris')
assert.equal(data.users[1].username, 'brian')
assert.equal(data.users[2].username, 'bzari')
done()
})
})
})
describe('.delete()', () => {
let uid
before((done) => {
User.create({ username: 'usertodelete', password: '123456', email: '[email protected]' }, (err, newUid) => {
assert.ifError(err)
uid = newUid
done()
})
})
it('should delete a user account', (done) => {
User.delete(1, uid, (err) => {
assert.ifError(err)
User.existsBySlug('usertodelete', (err, exists) => {
assert.ifError(err)
assert.equal(exists, false)
done()
})
})
})
it('should not re-add user to users:postcount if post is purged after user account deletion', async () => {
const uid = await User.create({ username: 'olduserwithposts' })
assert(await db.isSortedSetMember('users:postcount', uid))
const result = await Topics.post({
uid,
title: 'old user topic',
content: 'old user topic post content',
cid: testCid
})
assert.equal(await db.sortedSetScore('users:postcount', uid), 1)
await User.deleteAccount(uid)
assert(!await db.isSortedSetMember('users:postcount', uid))
await Posts.purge(result.postData.pid, 1)
assert(!await db.isSortedSetMember('users:postcount', uid))
})
it('should not re-add user to users:reputation if post is upvoted after user account deletion', async () => {
const uid = await User.create({ username: 'olduserwithpostsupvote' })
assert(await db.isSortedSetMember('users:reputation', uid))
const result = await Topics.post({
uid,
title: 'old user topic',
content: 'old user topic post content',
cid: testCid
})
assert.equal(await db.sortedSetScore('users:reputation', uid), 0)
await User.deleteAccount(uid)
assert(!await db.isSortedSetMember('users:reputation', uid))
await Posts.upvote(result.postData.pid, 1)
assert(!await db.isSortedSetMember('users:reputation', uid))
})
it('should delete user even if they started a chat', async () => {
const uid1 = await User.create({ username: 'chatuserdelete1' })
const uid2 = await User.create({ username: 'chatuserdelete2' })
const roomId = await messaging.newRoom(uid1, [uid2])
await messaging.addMessage({
uid: uid1,
content: 'hello',
roomId
})
await messaging.leaveRoom([uid2], roomId)
await User.delete(1, uid1)
assert.strictEqual(await User.exists(uid1), false)
})
})
describe('passwordReset', () => {
let uid
let code
before(async () => {
uid = await User.create({ username: 'resetuser', password: '123456' })
await User.setUserField(uid, 'email', '[email protected]')
await User.email.confirmByUid(uid)
})
it('.generate() should generate a new reset code', (done) => {
User.reset.generate(uid, (err, _code) => {
assert.ifError(err)
assert(_code)
code = _code
done()
})
})
it('.generate() should invalidate a previous generated reset code', async () => {
const _code = await User.reset.generate(uid)
const valid = await User.reset.validate(code)
assert.strictEqual(valid, false)
code = _code
})
it('.validate() should ensure that this new code is valid', (done) => {
User.reset.validate(code, (err, valid) => {
assert.ifError(err)
assert.strictEqual(valid, true)
done()
})
})
it('.validate() should correctly identify an invalid code', (done) => {
User.reset.validate(`${code}abcdef`, (err, valid) => {
assert.ifError(err)
assert.strictEqual(valid, false)
done()
})
})
it('.send() should create a new reset code and reset password', async () => {
code = await User.reset.send('[email protected]')
})
it('.commit() should update the user\'s password and confirm their email', (done) => {
User.reset.commit(code, 'newpassword', (err) => {
assert.ifError(err)
async.parallel({
userData: function (next) {
User.getUserData(uid, next)
},
password: function (next) {
db.getObjectField(`user:${uid}`, 'password', next)
}
}, (err, results) => {
assert.ifError(err)
Password.compare('newpassword', results.password, true, (err, match) => {
assert.ifError(err)
assert(match)
assert.strictEqual(results.userData['email:confirmed'], 1)
done()
})
})
})
})
it('.should error if same password is used for reset', async () => {
const uid = await User.create({ username: 'badmemory', email: '[email protected]', password: '123456' })
const code = await User.reset.generate(uid)
let err
try {
await User.reset.commit(code, '123456')
} catch (_err) {
err = _err
}
assert.strictEqual(err.message, '[[error:reset-same-password]]')
})
it('should not validate email if password reset is due to expiry', async () => {
const uid = await User.create({ username: 'resetexpiry', email: '[email protected]', password: '123456' })
let confirmed = await User.getUserField(uid, 'email:confirmed')
let [verified, unverified] = await groups.isMemberOfGroups(uid, ['verified-users', 'unverified-users'])
assert.strictEqual(confirmed, 0)
assert.strictEqual(verified, false)
assert.strictEqual(unverified, true)
await User.setUserField(uid, 'passwordExpiry', Date.now())
const code = await User.reset.generate(uid)
await User.reset.commit(code, '654321')
confirmed = await User.getUserField(uid, 'email:confirmed');
[verified, unverified] = await groups.isMemberOfGroups(uid, ['verified-users', 'unverified-users'])
assert.strictEqual(confirmed, 0)
assert.strictEqual(verified, false)
assert.strictEqual(unverified, true)
})
})
describe('hash methods', () => {
it('should return uid from email', (done) => {
User.getUidByEmail('[email protected]', (err, uid) => {
assert.ifError(err)
assert.equal(parseInt(uid, 10), parseInt(testUid, 10))
done()
})
})
it('should return uid from username', (done) => {
User.getUidByUsername('John Smith', (err, uid) => {
assert.ifError(err)
assert.equal(parseInt(uid, 10), parseInt(testUid, 10))
done()
})
})
it('should return uid from userslug', (done) => {
User.getUidByUserslug('john-smith', (err, uid) => {
assert.ifError(err)
assert.equal(parseInt(uid, 10), parseInt(testUid, 10))
done()
})
})
it('should get user data even if one uid is NaN', (done) => {
User.getUsersData([NaN, testUid], (err, data) => {
assert.ifError(err)
assert(data[0])
assert.equal(data[0].username, '[[global:guest]]')
assert(data[1])
assert.equal(data[1].username, userData.username)
done()
})
})
it('should not return private user data', (done) => {
User.setUserFields(testUid, {
fb_token: '123123123',
another_secret: 'abcde',
postcount: '123'
}, (err) => {
assert.ifError(err)
User.getUserData(testUid, (err, userData) => {
assert.ifError(err)
assert(!Object.hasOwn(userData, 'fb_token'))
assert(!Object.hasOwn(userData, 'another_secret'))
assert(!Object.hasOwn(userData, 'password'))
assert(!Object.hasOwn(userData, 'rss_token'))
assert.strictEqual(userData.postcount, 123)
assert.strictEqual(userData.uid, testUid)
done()
})
})
})
it('should not return password even if explicitly requested', (done) => {
User.getUserFields(testUid, ['password'], (err, payload) => {
assert.ifError(err)
assert(!Object.hasOwn(payload, 'password'))
done()
})
})
it('should not modify the fields array passed in', async () => {
const fields = ['username', 'email']
await User.getUserFields(testUid, fields)
assert.deepStrictEqual(fields, ['username', 'email'])
})
it('should return an icon text and valid background if username and picture is explicitly requested', async () => {
const payload = await User.getUserFields(testUid, ['username', 'picture'])
const validBackgrounds = await User.getIconBackgrounds(testUid)
assert.strictEqual(payload['icon:text'], userData.username.slice(0, 1).toUpperCase())
assert(payload['icon:bgColor'])
assert(validBackgrounds.includes(payload['icon:bgColor']))
})
it('should return a valid background, even if an invalid background colour is set', async () => {
await User.setUserField(testUid, 'icon:bgColor', 'teal')
const payload = await User.getUserFields(testUid, ['username', 'picture'])
const validBackgrounds = await User.getIconBackgrounds(testUid)
assert(payload['icon:bgColor'])
assert(validBackgrounds.includes(payload['icon:bgColor']))
})
it('should return private data if field is whitelisted', (done) => {
function filterMethod (data, callback) {
data.whitelist.push('another_secret')
callback(null, data)
}
plugins.hooks.register('test-plugin', { hook: 'filter:user.whitelistFields', method: filterMethod })
User.getUserData(testUid, (err, userData) => {
assert.ifError(err)
assert(!Object.hasOwn(userData, 'fb_token'))
assert.equal(userData.another_secret, 'abcde')
plugins.hooks.unregister('test-plugin', 'filter:user.whitelistFields', filterMethod)
done()
})
})
it('should return 0 as uid if username is falsy', (done) => {
User.getUidByUsername('', (err, uid) => {
assert.ifError(err)
assert.strictEqual(uid, 0)
done()
})
})
it('should get username by userslug', (done) => {
User.getUsernameByUserslug('john-smith', (err, username) => {
assert.ifError(err)
assert.strictEqual('John Smith', username)
done()
})
})
it('should get uids by emails', (done) => {
User.getUidsByEmails(['[email protected]'], (err, uids) => {
assert.ifError(err)
assert.equal(uids[0], testUid)
done()
})
})
it('should not get groupTitle for guests', (done) => {
User.getUserData(0, (err, userData) => {
assert.ifError(err)
assert.strictEqual(userData.groupTitle, '')
assert.deepStrictEqual(userData.groupTitleArray, [])
done()
})
})
it('should load guest data', (done) => {
User.getUsersData([1, 0], (err, data) => {
assert.ifError(err)
assert.strictEqual(data[1].username, '[[global:guest]]')
assert.strictEqual(data[1].userslug, '')
assert.strictEqual(data[1].uid, 0)
done()
})
})
})
describe('profile methods', () => {
let uid
let jar
let csrfToken
before(async () => {
const newUid = await User.create({ username: 'updateprofile', email: '[email protected]', password: '123456' })
uid = newUid
await User.setUserField(uid, 'email', '[email protected]')
await User.email.confirmByUid(uid);
({ jar, csrf_token: csrfToken } = await helpers.loginUser('updateprofile', '123456'))
})
it('should return error if not logged in', async () => {
try {
await apiUser.update({ uid: 0 }, { uid: 1 })
assert(false)
} catch (err) {
assert.equal(err.message, '[[error:invalid-uid]]')
}
})
it('should return error if data is invalid', async () => {
try {
await apiUser.update({ uid }, null)
assert(false)
} catch (err) {
assert.equal(err.message, '[[error:invalid-data]]')
}
})
it('should return error if data is missing uid', async () => {
try {
await apiUser.update({ uid }, { username: 'bip', email: 'bop' })
assert(false)
} catch (err) {
assert.equal(err.message, '[[error:invalid-data]]')
}
})
describe('.updateProfile()', () => {
let uid
it('should update a user\'s profile', async () => {
uid = await User.create({ username: 'justforupdate', email: '[email protected]', password: '123456' })
await User.setUserField(uid, 'email', '[email protected]')
await User.email.confirmByUid(uid)
const data = {
uid,
username: 'updatedUserName',
email: '[email protected]',
fullname: 'updatedFullname',
website: 'http://nodebb.org',
location: 'izmir',
groupTitle: 'testGroup',
birthday: '01/01/1980',
signature: 'nodebb is good',
password: '123456'
}
const result = await apiUser.update({ uid }, { ...data, password: '123456', invalid: 'field' })
assert.equal(result.username, 'updatedUserName')
assert.equal(result.userslug, 'updatedusername')
assert.equal(result.location, 'izmir')
const userData = await db.getObject(`user:${uid}`)
Object.keys(data).forEach((key) => {
if (key === 'email') {
assert.strictEqual(userData.email, '[email protected]') // email remains the same until confirmed
} else if (key !== 'password') {
assert.equal(data[key], userData[key])
} else {
assert(userData[key].startsWith('$2a$'))
}
})
// updateProfile only saves valid fields
assert.strictEqual(userData.invalid, undefined)
})
it('should also generate an email confirmation code for the changed email', async () => {
const confirmSent = await User.email.isValidationPending(uid, '[email protected]')
assert.strictEqual(confirmSent, true)
})
})
it('should change a user\'s password', async () => {
const uid = await User.create({ username: 'changepassword', password: '123456' })
await apiUser.changePassword({ uid }, { uid, newPassword: '654321', currentPassword: '123456' })
const correct = await User.isPasswordCorrect(uid, '654321', '127.0.0.1')
assert(correct)
})
it('should not let user change another user\'s password', async () => {
const regularUserUid = await User.create({ username: 'regularuserpwdchange', password: 'regularuser1234' })
const uid = await User.create({ username: 'changeadminpwd1', password: '123456' })
try {
await apiUser.changePassword({ uid }, { uid: regularUserUid, newPassword: '654321', currentPassword: '123456' })
assert(false)
} catch (err) {
assert.equal(err.message, '[[user:change_password_error_privileges]]')
}
})
it('should not let user change admin\'s password', async () => {
const adminUid = await User.create({ username: 'adminpwdchange', password: 'admin1234' })
await groups.join('administrators', adminUid)
const uid = await User.create({ username: 'changeadminpwd2', password: '123456' })
try {
await apiUser.changePassword({ uid }, { uid: adminUid, newPassword: '654321', currentPassword: '123456' })
assert(false)
} catch (err) {
assert.equal(err.message, '[[user:change_password_error_privileges]]')
}
})
it('should let admin change another users password', async () => {
const adminUid = await User.create({ username: 'adminpwdchange2', password: 'admin1234' })
await groups.join('administrators', adminUid)
const uid = await User.create({ username: 'forgotmypassword', password: '123456' })
await apiUser.changePassword({ uid: adminUid }, { uid, newPassword: '654321' })
const correct = await User.isPasswordCorrect(uid, '654321', '127.0.0.1')
assert(correct)
})