-
Notifications
You must be signed in to change notification settings - Fork 70
/
org.controller.js
878 lines (762 loc) · 33 KB
/
org.controller.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
require('dotenv').config()
const User = require('../../model/user')
const Org = require('../../model/org')
const logger = require('../../middleware/logger')
const argon2 = require('argon2')
const getConstants = require('../../constants').getConstants
const cryptoRandomString = require('crypto-random-string')
const uuid = require('uuid')
const errors = require('./error')
const error = new errors.OrgControllerError()
const validateUUID = require('uuid').validate
const booleanIsTrue = require('../../utils/utils').booleanIsTrue
/**
* Get the details of all orgs
* Called by GET /api/org
**/
async function getOrgs (req, res, next) {
try {
const CONSTANTS = getConstants()
// temporary measure to allow tests to work after fixing #920
// tests required changing the global limit to force pagination
if (req.TEST_PAGINATOR_LIMIT) {
CONSTANTS.PAGINATOR_OPTIONS.limit = req.TEST_PAGINATOR_LIMIT
}
const options = CONSTANTS.PAGINATOR_OPTIONS
options.sort = { short_name: 'asc' }
options.page = req.ctx.query.page ? parseInt(req.ctx.query.page) : CONSTANTS.PAGINATOR_PAGE // if 'page' query parameter is not defined, set 'page' to the default page value
const repo = req.ctx.repositories.getOrgRepository()
const agt = setAggregateOrgObj({})
const pg = await repo.aggregatePaginate(agt, options)
const payload = { organizations: pg.itemsList }
if (pg.itemCount >= CONSTANTS.PAGINATOR_OPTIONS.limit) {
payload.totalCount = pg.itemCount
payload.itemsPerPage = pg.itemsPerPage
payload.pageCount = pg.pageCount
payload.currentPage = pg.currentPage
payload.prevPage = pg.prevPage
payload.nextPage = pg.nextPage
}
logger.info({ uuid: req.ctx.uuid, message: 'The orgs were sent to the user.' })
return res.status(200).json(payload)
} catch (err) {
next(err)
}
}
/**
* Get the details of a single org for the specified shortname
* Called by GET /api/org/{identifier}
**/
async function getOrg (req, res, next) {
try {
const orgShortName = req.ctx.org
const identifier = req.ctx.params.identifier
const repo = req.ctx.repositories.getOrgRepository()
const isSecretariat = await repo.isSecretariat(orgShortName)
const org = await repo.findOneByShortName(orgShortName)
let orgIdentifer = orgShortName
let agt = setAggregateOrgObj({ short_name: identifier })
// check if identifier is uuid and if so, reassign agt and orgIdentifier
if (validateUUID(identifier)) {
orgIdentifer = org.UUID
agt = setAggregateOrgObj({ UUID: identifier })
}
if (orgIdentifer !== identifier && !isSecretariat) {
logger.info({ uuid: req.ctx.uuid, message: identifier + ' organization can only be viewed by the users of the same organization or the Secretariat.' })
return res.status(403).json(error.notSameOrgOrSecretariat())
}
let result = await repo.aggregate(agt)
result = result.length > 0 ? result[0] : null
if (!result) { // an empty result can only happen if the requestor is the Secretariat
logger.info({ uuid: req.ctx.uuid, message: identifier + ' organization does not exist.' })
return res.status(404).json(error.orgDne(identifier, 'identifier', 'path'))
}
logger.info({ uuid: req.ctx.uuid, message: identifier + ' organization was sent to the user.', org: result })
return res.status(200).json(result)
} catch (err) {
next(err)
}
}
/**
* Get the details of all users from an org given the specified shortname
* Called by GET /api/org/{shortname}/users
**/
async function getUsers (req, res, next) {
try {
const CONSTANTS = getConstants()
// temporary measure to allow tests to work after fixing #920
// tests required changing the global limit to force pagination
if (req.TEST_PAGINATOR_LIMIT) {
CONSTANTS.PAGINATOR_OPTIONS.limit = req.TEST_PAGINATOR_LIMIT
}
const options = CONSTANTS.PAGINATOR_OPTIONS
options.sort = { username: 'asc' }
options.page = req.ctx.query.page ? parseInt(req.ctx.query.page) : CONSTANTS.PAGINATOR_PAGE // if 'page' query parameter is not defined, set 'page' to the default page value
const shortName = req.ctx.org
const orgShortName = req.ctx.params.shortname
const orgRepo = req.ctx.repositories.getOrgRepository()
const userRepo = req.ctx.repositories.getUserRepository()
const orgUUID = await orgRepo.getOrgUUID(orgShortName)
const isSecretariat = await orgRepo.isSecretariat(shortName)
if (!orgUUID) {
logger.info({ uuid: req.ctx.uuid, message: orgShortName + ' organization does not exist.' })
return res.status(404).json(error.orgDnePathParam(orgShortName))
}
if (orgShortName !== shortName && !isSecretariat) {
logger.info({ uuid: req.ctx.uuid, message: orgShortName + ' organization can only be viewed by the users of the same organization or the Secretariat.' })
return res.status(403).json(error.notSameOrgOrSecretariat())
}
const agt = setAggregateUserObj({ org_UUID: orgUUID })
const pg = await userRepo.aggregatePaginate(agt, options)
const payload = { users: pg.itemsList }
if (pg.itemCount >= CONSTANTS.PAGINATOR_OPTIONS.limit) {
payload.totalCount = pg.itemCount
payload.itemsPerPage = pg.itemsPerPage
payload.pageCount = pg.pageCount
payload.currentPage = pg.currentPage
payload.prevPage = pg.prevPage
payload.nextPage = pg.nextPage
}
logger.info({ uuid: req.ctx.uuid, message: `The users of ${orgShortName} organization were sent to the user.` })
return res.status(200).json(payload)
} catch (err) {
next(err)
}
}
/**
* Get the details of a single user for the specified username
* Called by GET /api/org/{shortname}/user/{username}
**/
async function getUser (req, res, next) {
try {
const shortName = req.ctx.org
const username = req.ctx.params.username
const orgShortName = req.ctx.params.shortname
const orgRepo = req.ctx.repositories.getOrgRepository()
const isSecretariat = await orgRepo.isSecretariat(shortName)
if (orgShortName !== shortName && !isSecretariat) {
logger.info({ uuid: req.ctx.uuid, message: shortName + ' organization can only be viewed by that organization\'s users or the Secretariat.' })
return res.status(403).json(error.notSameOrgOrSecretariat())
}
const orgUUID = await orgRepo.getOrgUUID(orgShortName)
if (!orgUUID) { // the org can only be non-existent if the requestor is the Secretariat
logger.info({ uuid: req.ctx.uuid, message: orgShortName + ' organization does not exist.' })
return res.status(404).json(error.orgDnePathParam(orgShortName))
}
const userRepo = req.ctx.repositories.getUserRepository()
const agt = setAggregateUserObj({ username: username, org_UUID: orgUUID })
let result = await userRepo.aggregate(agt)
result = result.length > 0 ? result[0] : null
if (!result) {
logger.info({ uuid: req.ctx.uuid, message: username + ' does not exist.' })
return res.status(404).json(error.userDne(username))
}
logger.info({ uuid: req.ctx.uuid, message: username + ' was sent to the user.', user: result })
return res.status(200).json(result)
} catch (err) {
next(err)
}
}
/**
* Get details on ID quota for an org with the specified org shortname
* Called by GET /api/org/{shortname}/id_quota
**/
async function getOrgIdQuota (req, res, next) {
try {
const orgShortName = req.ctx.org
const shortName = req.ctx.params.shortname
const repo = req.ctx.repositories.getOrgRepository()
const isSecretariat = await repo.isSecretariat(orgShortName)
if (orgShortName !== shortName && !isSecretariat) {
logger.info({ uuid: req.ctx.uuid, message: shortName + ' organization id quota can only be viewed by the users of the same organization or the Secretariat.' })
return res.status(403).json(error.notSameOrgOrSecretariat())
}
let result = await repo.findOneByShortName(shortName)
if (!result) { // a null result can only happen if the requestor is the Secretariat
logger.info({ uuid: req.ctx.uuid, message: shortName + ' organization does not exist.' })
return res.status(404).json(error.orgDnePathParam(shortName))
}
const returnPayload = {
id_quota: result.policies.id_quota,
total_reserved: null,
available: null
}
const query = {
owning_cna: await repo.getOrgUUID(shortName),
state: getConstants().CVE_STATES.RESERVED
}
const cveIdRepo = req.ctx.repositories.getCveIdRepository()
result = await cveIdRepo.countDocuments(query)
returnPayload.total_reserved = result
returnPayload.available = returnPayload.id_quota - returnPayload.total_reserved
logger.info({ uuid: req.ctx.uuid, message: 'The organization\'s id quota was returned to the user.', details: returnPayload })
return res.status(200).json(returnPayload)
} catch (err) {
next(err)
}
}
/**
* Creates a new org only if the org doesn't exist for the specified shortname.
* If the org exists, we do not update the org.
* Called by POST /api/org/
**/
async function createOrg (req, res, next) {
const CONSTANTS = getConstants()
try {
const newOrg = new Org()
const orgRepo = req.ctx.repositories.getOrgRepository()
for (const k in req.ctx.body) {
const key = k.toLowerCase()
switch (key) {
case 'short_name':
newOrg.short_name = req.ctx.body.short_name
break
case 'name':
newOrg.name = req.ctx.body.name
break
case 'authority':
if ('active_roles' in req.ctx.body.authority) {
newOrg.authority.active_roles = req.ctx.body.authority.active_roles
}
break
case 'policies':
if ('id_quota' in req.ctx.body.policies) {
newOrg.policies.id_quota = req.ctx.body.policies.id_quota
}
break
case 'uuid':
return res.status(400).json(error.uuidProvided('org'))
}
}
let result = await orgRepo.findOneByShortName(newOrg.short_name) // Find org in MongoDB
if (result) {
logger.info({ uuid: req.ctx.uuid, message: newOrg.short_name + ' organization was not created because it already exists.' })
return res.status(400).json(error.orgExists(newOrg.short_name))
}
newOrg.inUse = false
newOrg.UUID = uuid.v4()
if (newOrg.authority.active_roles.length === 0) { // default is to make the Org a CNA if no role is specified
newOrg.authority.active_roles = [CONSTANTS.AUTH_ROLE_ENUM.CNA]
}
if (newOrg.policies.id_quota === undefined) { // set to default quota if none is specified
newOrg.policies.id_quota = CONSTANTS.DEFAULT_ID_QUOTA
}
if (newOrg.authority.active_roles.length === 1 && newOrg.authority.active_roles[0] === 'ADP') { // ADPs have quota of 0
newOrg.policies.id_quota = 0
}
await orgRepo.updateByOrgUUID(newOrg.UUID, newOrg, { upsert: true }) // Create org in MongoDB if it doesn't exist
const agt = setAggregateOrgObj({ short_name: newOrg.short_name })
result = await orgRepo.aggregate(agt)
result = result.length > 0 ? result[0] : null
const responseMessage = {
message: newOrg.short_name + ' organization was successfully created.',
created: result
}
const payload = {
action: 'create_org',
change: newOrg.short_name + ' organization was successfully created.',
req_UUID: req.ctx.uuid,
org_UUID: await orgRepo.getOrgUUID(req.ctx.org),
org: result
}
const userRepo = req.ctx.repositories.getUserRepository()
payload.user_UUID = await userRepo.getUserUUID(req.ctx.user, payload.org_UUID)
logger.info(JSON.stringify(payload))
return res.status(200).json(responseMessage)
} catch (err) {
next(err)
}
}
/**
* Updates an org only if the org exist for the specified shortname.
* If no org exists, we do not create the org.
* Called by PUT /api/org/{shortname}
**/
async function updateOrg (req, res, next) {
try {
const shortName = req.ctx.params.shortname
const newOrg = new Org()
const removeRoles = []
const addRoles = []
const orgRepo = req.ctx.repositories.getOrgRepository()
const org = await orgRepo.findOneByShortName(shortName)
let agt = setAggregateOrgObj({ short_name: shortName })
// org doesn't exist
if (!org) {
logger.info({ uuid: req.ctx.uuid, message: shortName + ' organization could not be updated in MongoDB because it does not exist.' })
return res.status(404).json(error.orgDnePathParam(shortName))
}
Object.keys(req.ctx.query).forEach(k => {
const key = k.toLowerCase()
if (key === 'new_short_name') {
newOrg.short_name = req.ctx.query.new_short_name
agt = setAggregateOrgObj({ short_name: newOrg.short_name })
} else if (key === 'name') {
newOrg.name = req.ctx.query.name
} else if (key === 'id_quota') {
newOrg.policies.id_quota = req.ctx.query.id_quota
} else if (key === 'active_roles.add') {
if (Array.isArray(req.ctx.query['active_roles.add'])) {
req.ctx.query['active_roles.add'].forEach(r => {
addRoles.push(r)
})
}
} else if (key === 'active_roles.remove') {
if (Array.isArray(req.ctx.query['active_roles.remove'])) {
req.ctx.query['active_roles.remove'].forEach(r => {
removeRoles.push(r)
})
}
}
})
// updating the org's roles
if (org) {
const roles = org.authority.active_roles
// adding roles
addRoles.forEach(role => {
if (!roles.includes(role)) {
roles.push(role)
}
})
// removing roles
removeRoles.forEach(role => {
const index = roles.indexOf(role)
if (index > -1) {
roles.splice(index, 1)
}
})
newOrg.authority.active_roles = roles
}
if (newOrg.short_name) {
const result = await orgRepo.findOneByShortName(newOrg.short_name)
if (result) {
return res.status(403).json(error.duplicateShortname(newOrg.short_name))
}
}
// update org
let result = await orgRepo.updateByOrgUUID(org.UUID, newOrg)
if (result.n === 0) {
logger.info({ uuid: req.ctx.uuid, message: shortName + ' organization could not be updated in MongoDB because it does not exist.' })
return res.status(404).json(error.orgDnePathParam(shortName))
}
result = await orgRepo.aggregate(agt)
result = result.length > 0 ? result[0] : null
const responseMessage = {
message: shortName + ' organization was successfully updated.',
updated: result
}
const payload = {
action: 'update_org',
change: shortName + ' organization was successfully updated.',
req_UUID: req.ctx.uuid,
org_UUID: await orgRepo.getOrgUUID(req.ctx.org),
org: result
}
const userRepo = req.ctx.repositories.getUserRepository()
payload.user_UUID = await userRepo.getUserUUID(req.ctx.user, payload.org_UUID)
logger.info(JSON.stringify(payload))
return res.status(200).json(responseMessage)
} catch (err) {
next(err)
}
}
/**
* Creates a user only if the org exists and
* the user does not exist for the specified shortname and username
* Called by POST /api/org/{shortname}/user
**/
async function createUser (req, res, next) {
try {
const orgShortName = req.ctx.params.shortname
const requesterUsername = req.ctx.user
const requesterShortName = req.ctx.org
const orgRepo = req.ctx.repositories.getOrgRepository()
const userRepo = req.ctx.repositories.getUserRepository()
const newUser = new User()
const orgUUID = await orgRepo.getOrgUUID(orgShortName)
if (!orgUUID) { // the org can only be non-existent if the requestor is the Secretariat
logger.info({ uuid: req.ctx.uuid, message: 'The user could not be created because ' + orgShortName + ' organization does not exist.' })
return res.status(404).json(error.orgDnePathParam(orgShortName))
}
const users = await userRepo.findUsersByOrgUUID(orgUUID)
if (users >= 100) {
return res.status(400).json(error.userLimitReached())
}
Object.keys(req.ctx.body).forEach(k => {
const key = k.toLowerCase()
if (key === 'username') {
newUser.username = req.ctx.body.username
} else if (key === 'authority') {
if (req.ctx.body.authority.active_roles) {
newUser.authority.active_roles = [...new Set(req.ctx.body.authority.active_roles)] // Removes any duplicate strings from array
}
} else if (key === 'name') {
if (req.ctx.body.name.first) {
newUser.name.first = req.ctx.body.name.first
}
if (req.ctx.body.name.last) {
newUser.name.last = req.ctx.body.name.last
}
if (req.ctx.body.name.middle) {
newUser.name.middle = req.ctx.body.name.middle
}
if (req.ctx.body.name.suffix) {
newUser.name.suffix = req.ctx.body.name.suffix
}
} else if (key === 'org_uuid') {
return res.status(400).json(error.uuidProvided('org'))
} else if (key === 'uuid') {
return res.status(400).json(error.uuidProvided('user'))
}
})
const requesterOrgUUID = await orgRepo.getOrgUUID(requesterShortName)
const isSecretariat = await orgRepo.isSecretariatUUID(requesterOrgUUID)
const isAdmin = await userRepo.isAdminUUID(requesterUsername, requesterOrgUUID)
// check if user is only an Admin (not Secretatiat) and the user does not belong to the same organization as the new user
if (!isSecretariat && isAdmin) {
if (requesterOrgUUID !== orgUUID) {
return res.status(403).json(error.notOrgAdminOrSecretariat()) // The Admin user must belong to the new user's organization
}
}
newUser.org_UUID = orgUUID
newUser.UUID = uuid.v4()
newUser.active = true
const randomKey = cryptoRandomString({ length: getConstants().CRYPTO_RANDOM_STRING_LENGTH })
newUser.secret = await argon2.hash(randomKey)
let result = await userRepo.findOneByUserNameAndOrgUUID(newUser.username, newUser.org_UUID) // Find user in MongoDB
if (result) {
logger.info({ uuid: req.ctx.uuid, message: newUser.username + ' was not created because it already exists.' })
return res.status(400).json(error.userExists(newUser.username))
}
// Parsing all user name fields
newUser.name = parseUserName(newUser)
await userRepo.updateByUserNameAndOrgUUID(newUser.username, newUser.org_UUID, newUser, { upsert: true }) // Create user in MongoDB if it doesn't exist
const agt = setAggregateUserObj({ username: newUser.username, org_UUID: newUser.org_UUID })
result = await userRepo.aggregate(agt)
result = result.length > 0 ? result[0] : null
const payload = {
action: 'create_user',
change: result.username + ' was successfully created.',
req_UUID: req.ctx.uuid,
org_UUID: await orgRepo.getOrgUUID(req.ctx.org),
user: result
}
payload.user_UUID = await userRepo.getUserUUID(req.ctx.user, payload.org_UUID)
logger.info(JSON.stringify(payload))
result.secret = randomKey
const responseMessage = {
message: result.username + ' was successfully created.',
created: result
}
return res.status(200).json(responseMessage)
} catch (err) {
next(err)
}
}
/**
* Updates a user only if the user exist for the specified username.
* If no user exists, it does not create the user.
* Called by PUT /org/{shortname}/user/{username}
**/
async function updateUser (req, res, next) {
try {
const requesterShortName = req.ctx.org
const requesterUsername = req.ctx.user
const username = req.ctx.params.username
const shortName = req.ctx.params.shortname
const newUser = new User()
let newOrgShortName = null
const removeRoles = []
const addRoles = []
const userRepo = req.ctx.repositories.getUserRepository()
const orgRepo = req.ctx.repositories.getOrgRepository()
const orgUUID = await orgRepo.getOrgUUID(shortName)
const isSecretariat = await orgRepo.isSecretariat(requesterShortName)
const isAdmin = await userRepo.isAdmin(requesterUsername, requesterShortName) // Check if requester is Admin of the designated user's org
if (!orgUUID) {
logger.info({ uuid: req.ctx.uuid, message: 'The user could not be updated because ' + shortName + ' organization does not exist.' })
return res.status(404).json(error.orgDnePathParam(shortName))
}
if (shortName !== requesterShortName && !isSecretariat) {
logger.info({ uuid: req.ctx.uuid, message: shortName + ' organization can only be viewed by the users of the same organization or the Secretariat.' })
return res.status(403).json(error.notSameOrgOrSecretariat())
}
const user = await userRepo.findOneByUserNameAndOrgUUID(username, orgUUID)
if (!user) {
logger.info({ uuid: req.ctx.uuid, message: 'The user could not be updated because ' + username + ' does not exist for ' + shortName + ' organization.' })
return res.status(404).json(error.userDne(username))
}
// check if the user is not the requester or if the requester is not a secretariat
if ((shortName !== requesterShortName || username !== requesterUsername) && !isSecretariat) {
// check if the requester is not and admin; if admin, the requester must be from the same org as the user
if (!isAdmin || (isAdmin && shortName !== requesterShortName)) {
logger.info({ uuid: req.ctx.uuid, message: 'The user can only be updated by the Secretariat, an Org admin or if the requester is the user.' })
return res.status(403).json(error.notSameUserOrSecretariat())
}
}
// Sets the name values to what currently exists in the database, this ensures data is retained during partial name updates
newUser.name.first = user.name.first
newUser.name.last = user.name.last
newUser.name.middle = user.name.middle
newUser.name.suffix = user.name.suffix
const queryParameterPermissions = {
new_username: true,
org_short_name: true,
'name.first': false,
'name.last': false,
'name.middle': false,
'name.suffix': false,
active: true,
'active_roles.add': true,
'active_roles.remove': true
}
// Specific check for org_short_name
if (Object.keys(req.ctx.query).length > 0 && Object.keys(req.ctx.query).includes('org_short_name') && !(isSecretariat)) {
logger.info({ uuid: req.ctx.uuid, message: 'The user could not be updated because ' + requesterUsername + ' is an Org Admin and tried to reassign the organization.' })
return res.status(403).json(error.notAllowedToChangeOrganization())
}
// Check to ensure that the user has the right permissions to edit the fields tha they are requesting to edit, and fail fast if they do not.
if (Object.keys(req.ctx.query).length > 0 && Object.keys(req.ctx.query).some((key) => { return queryParameterPermissions[key] }) && !(isAdmin || isSecretariat)) {
logger.info({ uuid: req.ctx.uuid, message: 'The user could not be updated because ' + requesterUsername + ' user is not Org Admin or Secretariat to modify these fields.' })
console.log('in failed admin')
return res.status(403).json(error.notOrgAdminOrSecretariatUpdate())
}
for (const k in req.ctx.query) {
const key = k.toLowerCase()
if (key === 'new_username') {
newUser.username = req.ctx.query.new_username
} else if (key === 'org_short_name') {
newOrgShortName = req.ctx.query.org_short_name
} else if (key === 'name.first') {
newUser.name.first = req.ctx.query['name.first']
} else if (key === 'name.last') {
newUser.name.last = req.ctx.query['name.last']
} else if (key === 'name.middle') {
newUser.name.middle = req.ctx.query['name.middle']
} else if (key === 'name.suffix') {
newUser.name.suffix = req.ctx.query['name.suffix']
} else if (key === 'active') {
newUser.active = booleanIsTrue(req.ctx.query.active)
} else if (key === 'active_roles.add') {
if (Array.isArray(req.ctx.query['active_roles.add'])) {
req.ctx.query['active_roles.add'].forEach(r => {
addRoles.push(r)
})
}
} else if (key === 'active_roles.remove') {
if (Array.isArray(req.ctx.query['active_roles.remove'])) {
for (const r of req.ctx.query['active_roles.remove']) {
if (r.toLowerCase() === 'admin' && requesterUsername === username && (isAdmin || isSecretariat)) {
logger.info({ uuid: req.ctx.uuid, message: 'The user could not be updated because ' + requesterUsername + ' is an Org Admin changing their own role.' })
return res.status(403).json(error.notAllowedToSelfDemote())
}
removeRoles.push(r)
}
}
}
}
// check if the new org exist
if (newOrgShortName) {
newUser.org_UUID = await orgRepo.getOrgUUID(newOrgShortName)
if (!newUser.org_UUID) {
logger.info({ uuid: req.ctx.uuid, message: 'The user could not be updated because ' + newOrgShortName + ' organization does not exist.' })
return res.status(404).json(error.orgDne(newOrgShortName, 'org_short_name', 'query'))
}
}
// error if trying to set org to same org
if (newOrgShortName === shortName) {
logger.info({ uuid: req.ctx.uuid, message: 'The user could not be updated because user is already in ' + newOrgShortName })
return res.status(403).json(error.alreadyInOrg(newOrgShortName, user.username))
}
let agt = setAggregateUserObj({ username: username, org_UUID: orgUUID })
// check if org has user of same username already
if (newUser.username && newUser.org_UUID) {
agt = setAggregateUserObj({ username: newUser.username, org_UUID: newUser.org_UUID })
const duplicateUsers = await userRepo.find({ org_UUID: newUser.org_UUID, username: newUser.username })
if (duplicateUsers.length) {
logger.info({ uuid: req.ctx.uuid, message: 'The user could not be updated because ' + newOrgShortName + ' organization contains a user with the same username.' })
return res.status(403).json(error.duplicateUsername(newOrgShortName, newUser.username))
}
} else if (newUser.username) {
agt = setAggregateUserObj({ username: newUser.username, org_UUID: orgUUID })
const duplicateUsers = await userRepo.find({ org_UUID: orgUUID, username: newUser.username })
if (duplicateUsers.length) {
logger.info({ uuid: req.ctx.uuid, message: 'The user could not be updated because ' + shortName + ' organization contains a user with the same username.' })
return res.status(403).json(error.duplicateUsername(shortName, newUser.username))
}
} else if (newUser.org_UUID) {
agt = setAggregateUserObj({ username: username, org_UUID: newUser.org_UUID })
const duplicateUsers = await userRepo.find({ org_UUID: newUser.org_UUID, username: username })
if (duplicateUsers.length) {
logger.info({ uuid: req.ctx.uuid, message: 'The user could not be updated because ' + newOrgShortName + ' organization contains a user with the same username.' })
return res.status(403).json(error.duplicateUsername(newOrgShortName, username))
}
}
// updating the user's roles
const roles = user.authority.active_roles
// adding roles
addRoles.forEach(role => {
if (!roles.includes(role)) {
roles.push(role)
}
})
const duplicateCheckedRoles = [...new Set(roles)] // Removes any possible duplicates that may occur from concurrent users
// removing roles
removeRoles.forEach(role => {
const index = duplicateCheckedRoles.indexOf(role)
if (index > -1) {
duplicateCheckedRoles.splice(index, 1)
}
})
newUser.authority.active_roles = duplicateCheckedRoles
let result = await userRepo.updateByUserNameAndOrgUUID(username, orgUUID, newUser)
if (result.n === 0) {
logger.info({ uuid: req.ctx.uuid, message: 'The user could not be updated because ' + username + ' does not exist for ' + shortName + ' organization.' })
return res.status(404).json(error.userDne(username))
}
result = await userRepo.aggregate(agt)
result = result.length > 0 ? result[0] : null
let msgStr = ''
if (Object.keys(req.ctx.query).length > 0) {
msgStr = username + ' was successfully updated.'
} else {
msgStr = 'No updates were specified for ' + username + '.'
}
const responseMessage = {
message: msgStr,
updated: result
}
const payload = {
action: 'update_user',
change: username + ' was successfully updated.',
req_UUID: req.ctx.uuid,
org_UUID: await orgRepo.getOrgUUID(req.ctx.org),
user: result
}
payload.user_UUID = await userRepo.getUserUUID(req.ctx.user, payload.org_UUID)
logger.info(JSON.stringify(payload))
return res.status(200).json(responseMessage)
} catch (err) {
next(err)
}
}
// Called by PUT /org/{shortname}/user/{username}/reset_secret
async function resetSecret (req, res, next) {
try {
const requesterShortName = req.ctx.org
const requesterUsername = req.ctx.user
const username = req.ctx.params.username
const orgShortName = req.ctx.params.shortname
const userRepo = req.ctx.repositories.getUserRepository()
const orgRepo = req.ctx.repositories.getOrgRepository()
const isSecretariat = await orgRepo.isSecretariat(requesterShortName)
const orgUUID = await orgRepo.getOrgUUID(orgShortName) // userUUID may be null if user does not exist
if (!orgUUID) {
logger.info({ uuid: req.ctx.uuid, messsage: orgShortName + ' organization does not exist.' })
return res.status(404).json(error.orgDnePathParam(orgShortName))
}
if (orgShortName !== requesterShortName && !isSecretariat) {
logger.info({ uuid: req.ctx.uuid, message: orgShortName + ' organization can only be viewed by the users of the same organization or the Secretariat.' })
return res.status(403).json(error.notSameOrgOrSecretariat())
}
const oldUser = await userRepo.findOneByUserNameAndOrgUUID(username, orgUUID)
if (!oldUser) {
logger.info({ uuid: req.ctx.uuid, messsage: username + ' user does not exist.' })
return res.status(404).json(error.userDne(username))
}
const isAdmin = await userRepo.isAdmin(requesterUsername, requesterShortName)
// check if the user is not the requester or if the requester is not a secretariat
if ((orgShortName !== requesterShortName || username !== requesterUsername) && !isSecretariat) {
// check if the requester is not and admin; if admin, the requester must be from the same org as the user
if (!isAdmin || (isAdmin && orgShortName !== requesterShortName)) {
logger.info({ uuid: req.ctx.uuid, message: 'The api secret can only be reset by the Secretariat, an Org admin or if the requester is the user.' })
return res.status(403).json(error.notSameUserOrSecretariat())
}
}
const randomKey = cryptoRandomString({ length: getConstants().CRYPTO_RANDOM_STRING_LENGTH })
oldUser.secret = await argon2.hash(randomKey) // store in db
const user = await userRepo.updateByUserNameAndOrgUUID(oldUser.username, orgUUID, oldUser)
if (user.n === 0) {
logger.info({ uuid: req.ctx.uuid, message: 'The user could not be updated because ' + username + ' does not exist for ' + orgShortName + ' organization.' })
return res.status(404).json(error.userDne(username))
}
logger.info({ uuid: req.ctx.uuid, message: `The API secret was successfully reset and sent to ${username}` })
const payload = {
action: 'reset_userAPIkey',
change: 'API secret was successfully reset.',
req_UUID: req.ctx.uuid,
org_UUID: await orgRepo.getOrgUUID(req.ctx.org)
}
payload.user_UUID = await userRepo.getUserUUID(req.ctx.user, payload.org_UUID)
logger.info(JSON.stringify(payload))
return res.status(200).json({ 'API-secret': randomKey })
} catch (err) {
next(err)
}
}
function setAggregateOrgObj (query) {
return [
{
$match: query
},
{
$project: {
_id: false,
UUID: true,
short_name: true,
name: true,
'authority.active_roles': true,
'policies.id_quota': true,
time: true
}
}
]
}
function setAggregateUserObj (query) {
return [
{
$match: query
},
{
$project: {
_id: false,
username: true,
name: true,
UUID: true,
org_UUID: true,
active: true,
'authority.active_roles': true,
time: true
}
}
]
}
function parseUserName (newUser) {
if (newUser.name) {
if (!newUser.name.first) {
newUser.name.first = ''
}
if (!newUser.name.last) {
newUser.name.last = ''
}
if (!newUser.name.middle) {
newUser.name.middle = ''
}
if (!newUser.name.suffix) {
newUser.name.suffix = ''
}
}
return newUser.name
}
module.exports = {
ORG_ALL: getOrgs,
ORG_SINGLE: getOrg,
ORG_CREATE_SINGLE: createOrg,
ORG_UPDATE_SINGLE: updateOrg,
USER_ALL: getUsers,
ORG_ID_QUOTA: getOrgIdQuota,
USER_SINGLE: getUser,
USER_CREATE_SINGLE: createUser,
USER_UPDATE_SINGLE: updateUser,
USER_RESET_SECRET: resetSecret
}