-
Notifications
You must be signed in to change notification settings - Fork 114
Expand file tree
/
Copy pathorg.controller.js
More file actions
745 lines (646 loc) · 30.9 KB
/
org.controller.js
File metadata and controls
745 lines (646 loc) · 30.9 KB
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
require('dotenv').config()
const mongoose = require('mongoose')
const logger = require('../../middleware/logger')
const getConstants = require('../../constants').getConstants
const errors = require('./error')
const error = new errors.OrgControllerError()
const validateUUID = require('uuid').validate
/**
* Get the details of all orgs.
* Called by GET /api/org
*
* @param {Object} req - The request object
* @param {Object} res - The response object
* @param {Function} next - The next middleware function
* @returns {Promise<void>}
*/
async function getOrgs (req, res, next) {
try {
const repo = req.ctx.repositories.getBaseOrgRepository()
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 returnValue = await repo.getAllOrgs({ ...options }, true)
logger.info({ uuid: req.ctx.uuid, message: 'The orgs were sent to the user.' })
return res.status(200).json(returnValue)
} catch (err) {
next(err)
}
}
/**
* Get the details of a single org for the specified shortname/UUID.
* Called by GET /api/org/{identifier}
*
* When Switched over to user registry only - This to be deleted
*
* @param {Object} req - The request object
* @param {Object} res - The response object
* @param {Function} next - The next middleware function
* @returns {Promise<void>}
*/
async function getOrg (req, res, next) {
try {
const repo = req.ctx.repositories.getBaseOrgRepository()
const requesterOrgShortName = req.ctx.org
const identifier = req.ctx.params.identifier
const identifierIsUUID = validateUUID(identifier)
const returnLegacyFormat = true
let returnValue
try {
const requesterOrg = await repo.findOneByShortName(requesterOrgShortName, {}, returnLegacyFormat)
const requesterOrgIdentifier = identifierIsUUID ? requesterOrg.UUID : requesterOrgShortName
const isSecretariat = await repo.isSecretariat(requesterOrg, {}, returnLegacyFormat)
if (requesterOrgIdentifier !== 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())
}
returnValue = await repo.getOrg(identifier, identifierIsUUID, {}, returnLegacyFormat)
} catch (error) {
// Handle the specific error thrown by BaseOrgRepository.createOrg
if (error.message && error.message.includes('Unknown Org type requested')) {
return res.status(400).json({ message: error.message })
}
}
if (!returnValue) { // 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: returnValue })
return res.status(200).json(returnValue)
} catch (err) {
next(err)
}
}
/**
* Get the details of all users from an org given the specified shortname.
* Called by GET /api/org/{shortname}/users
*
* @param {Object} req - The request object
* @param {Object} res - The response object
* @param {Function} next - The next middleware function
* @returns {Promise<void>}
*/
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.getBaseOrgRepository()
const userRepo = req.ctx.repositories.getBaseUserRepository()
const orgUUID = await orgRepo.getOrgUUID(orgShortName)
const isSecretariat = await orgRepo.isSecretariatByShortName(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 payload = await userRepo.getAllUsersByOrgShortname(orgShortName, options, !!req.useRegistry)
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}
*
* @param {Object} req - The request object
* @param {Object} res - The response object
* @param {Function} next - The next middleware function
* @returns {Promise<void>}
*/
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.getBaseOrgRepository()
const isSecretariat = await orgRepo.isSecretariatByShortName(shortName, {}, !req.useRegistry)
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.getBaseUserRepository()
// This is simple, we can just call our function
const result = await userRepo.findOneByUsernameAndOrgShortname(username, orgShortName, {}, !!req.useRegistry)
if (!result) {
logger.info({ uuid: req.ctx.uuid, message: username + ' does not exist.' })
return res.status(404).json(error.userDne(username))
}
const rawResult = result.toObject()
delete rawResult._id
delete rawResult.__v
delete rawResult.secret
logger.info({ uuid: req.ctx.uuid, message: username + ' was sent to the user.', user: rawResult })
return res.status(200).json(rawResult)
} catch (err) {
next(err)
}
}
/**
* Get details on ID quota for an org with the specified org shortname.
* Called by GET /api/registry/org/{shortname}/hard_quota, GET /api/org/{shortname}/id_quota
*
* @param {Object} req - The request object
* @param {Object} res - The response object
* @param {Function} next - The next middleware function
* @returns {Promise<void>}
*/
async function getOrgIdQuota (req, res, next) {
try {
const orgRepo = req.ctx.repositories.getBaseOrgRepository()
const requesterOrgShortName = req.ctx.org
const shortName = req.ctx.params.shortname
const requesterOrg = await orgRepo.findOneByShortName(requesterOrgShortName)
const isSecretariat = await orgRepo.isSecretariat(requesterOrg, !req.useRegistry)
if (requesterOrgShortName !== 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())
}
const org = await orgRepo.getOrg(shortName, false, {}, !req.useRegistry)
if (!org) { // a null org 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 = await orgRepo.getOrgIdQuota(org, !req.useRegistry)
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/
*
* @param {Object} req - The request object
* @param {Object} res - The response object
* @param {Function} next - The next middleware function
* @returns {Promise<void>}
*/
async function createOrg (req, res, next) {
try {
const session = await mongoose.startSession()
const repo = req.ctx.repositories.getBaseOrgRepository()
const body = req.ctx.body
let returnValue
// Do not allow the user to pass in a UUID
if ((body?.UUID ?? null) || (body?.uuid ?? null)) return res.status(400).json(error.uuidProvided('org'))
try {
session.startTransaction()
if (req.useRegistry) {
// If we are creating an org via the registry flag, we can do a full validation.
const result = await repo.validateOrg(body, { session })
if (!result.isValid) {
logger.error(JSON.stringify({ uuid: req.ctx.uuid, message: 'CVE JSON schema validation FAILED.' }))
await session.abortTransaction()
if (!Array.isArray(body?.authority) || body?.authority.some(item => typeof item !== 'string')) {
return res.status(400).json({ error: 'BAD_INPUT', message: 'Parameters were invalid', details: [{ param: 'authority', msg: 'Parameter must be a one-dimensional array of strings' }] })
}
return res.status(400).json({ error: 'BAD_INPUT', message: 'Parameters were invalid', errors: result.errors })
}
}
// Check to see if the org already exits
if (await repo.orgExists(body?.short_name, { session }, !req.useRegistry)) {
logger.info({ uuid: req.ctx.uuid, message: body?.short_name + ' organization was not created because it already exists.' })
await session.abortTransaction()
return res.status(400).json(error.orgExists(body?.short_name))
}
const userRepo = req.ctx.repositories.getBaseUserRepository()
const isSecretariat = await repo.isSecretariatByShortName(req.ctx.org, { session })
const requestingUserUUID = await userRepo.getUserUUID(req.ctx.user, req.ctx.org, { session })
returnValue = await repo.createOrg(req.ctx.body, { session, upsert: true }, !req.useRegistry, requestingUserUUID, isSecretariat)
await session.commitTransaction()
} catch (error) {
await session.abortTransaction()
throw error
} finally {
await session.endSession()
}
const responseMessage = {
message: body?.short_name + ' organization was successfully created.',
created: returnValue
}
const payload = {
action: 'create_org',
change: body?.short_name + ' organization was successfully created.',
req_UUID: req.ctx.uuid,
org_UUID: returnValue.UUID,
org: returnValue
}
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}
*
* @param {Object} req - The request object
* @param {Object} res - The response object
* @param {Function} next - The next middleware function
* @returns {Promise<void>}
*/
async function updateOrg (req, res, next) {
const shortNameUrlParameter = req.ctx.params.shortname
const orgRepository = req.ctx.repositories.getBaseOrgRepository()
const session = await mongoose.startSession({ causalConsistency: false })
let responseMessage
// Get the query parameters as JSON
// These are validated by the middleware in org/index.js
const queryParametersJson = req.ctx.query
try {
try {
session.startTransaction()
// TODO: Check to see if this check is needed for both options
if (req.useRegistry) {
if (queryParametersJson['active_roles.add']) {
if (!Array.isArray(queryParametersJson.active_roles?.add) || queryParametersJson.active_roles?.add.some(item => typeof item !== 'string')) {
await session.abortTransaction()
return res.status(400).json({ message: 'Parameters were invalid', details: [{ param: 'authority', msg: 'Parameter must be a one-dimensional array of strings' }] })
}
}
if (queryParametersJson['active_roles.remove']) {
if (!Array.isArray(queryParametersJson.active_roles?.remove) || queryParametersJson.active_roles?.remove.some(item => typeof item !== 'string')) {
await session.abortTransaction()
return res.status(400).json({ message: 'Parameters were invalid', details: [{ param: 'authority', msg: 'Parameter must be a one-dimensional array of strings' }] })
}
}
}
if (!(await orgRepository.orgExists(shortNameUrlParameter, { session }))) {
logger.info({ uuid: req.ctx.uuid, message: `Organization ${shortNameUrlParameter} not found.` })
return res.status(404).json(error.orgDnePathParam(shortNameUrlParameter))
}
if (Object.hasOwn(queryParametersJson, 'new_short_name') && (await orgRepository.orgExists(queryParametersJson.new_short_name, { session }))) {
return res.status(403).json(error.duplicateShortname(queryParametersJson.new_short_name))
}
const userRepo = req.ctx.repositories.getBaseUserRepository()
const requestingUserUUID = await userRepo.getUserUUID(req.ctx.user, req.ctx.org, { session })
const isSecretariat = await orgRepository.isSecretariatByShortName(req.ctx.org, { session })
const isAdmin = await userRepo.isAdmin(req.ctx.user, req.ctx.org, { session })
const updatedOrg = await orgRepository.updateOrg(shortNameUrlParameter, queryParametersJson, { session }, !req.useRegistry, requestingUserUUID, isAdmin, isSecretariat)
responseMessage = { message: `${updatedOrg.short_name} organization was successfully updated.`, updated: updatedOrg } // Clarify message
const payload = { action: 'update_org', change: `${updatedOrg.short_name} organization was successfully updated.`, org: updatedOrg }
payload.user_UUID = await userRepo.getUserUUID(req.ctx.user, updatedOrg.UUID)
payload.org_UUID = updatedOrg.UUID
payload.req_UUID = req.ctx.uuid
await session.commitTransaction()
} catch (error) {
await session.abortTransaction()
throw error
} finally {
await session.endSession()
}
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/registry/org/{shortname}/user, POST /api/org/{shortname}/user
*
* @param {Object} req - The request object
* @param {Object} res - The response object
* @param {Function} next - The next middleware function
* @returns {Promise<void>}
*/
async function createUser (req, res, next) {
const session = await mongoose.startSession()
try {
const body = req.ctx.body
const userRepo = req.ctx.repositories.getBaseUserRepository()
const orgRepo = req.ctx.repositories.getBaseOrgRepository()
const orgShortName = req.ctx.params.shortname
const constants = getConstants()
let returnValue
// Check to make sure Org Exists first
const orgUUID = await orgRepo.getOrgUUID(orgShortName)
if (!orgUUID) {
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))
}
// Do not allow the user to pass in a UUID
if ((body?.UUID ?? null) || (body?.uuid ?? null)) {
return res.status(400).json(error.uuidProvided('user'))
}
if ((body?.org_UUID ?? null) || (body?.org_uuid ?? null)) {
return res.status(400).json(error.uuidProvided('org'))
}
try {
session.startTransaction()
if (req.useRegistry) {
const result = await userRepo.validateUser(body)
if (body?.role && typeof body?.role !== 'string') {
return res.status(400).json({ message: 'Parameters were invalid', details: [{ param: 'role', msg: 'Parameter must be a string' }] })
}
if (body?.role && !constants.USER_ROLES.includes(body?.role)) {
return res.status(400).json({ message: 'Parameters were invalid', details: [{ param: 'role', msg: `Role must be one of the following: ${constants.USER_ROLES}` }] })
}
if (!result.isValid) {
logger.error(JSON.stringify({ uuid: req.ctx.uuid, message: 'User JSON schema validation FAILED.' }))
await session.abortTransaction()
return res.status(400).json({ message: 'Parameters were invalid', errors: result.errors })
}
} else {
if (!body?.username || typeof body?.username !== 'string') {
return res.status(400).json({ message: 'Parameters were invalid', details: [{ param: 'username', msg: 'Parameter must be a non empty string' }] })
}
}
// Ask repo if user already exists
if (await userRepo.orgHasUser(orgShortName, body?.username, { session }, !!req.useRegistry)) {
logger.info({ uuid: req.ctx.uuid, message: `${body?.username} user was not created because it already exists.` })
await session.abortTransaction()
return res.status(400).json(error.userExists(body?.username))
}
if (!await userRepo.isAdminOrSecretariat(orgShortName, req.ctx.user, req.ctx.org, { session }, !!req.useRegistry)) {
await session.abortTransaction()
return res.status(403).json(error.notOrgAdminOrSecretariat()) // The Admin user must belong to the new user's organization
}
const users = await userRepo.findUsersByOrgShortname(orgShortName, { session })
if (users.length >= 100) {
await session.abortTransaction()
return res.status(400).json(error.userLimitReached())
}
returnValue = await userRepo.createUser(orgShortName, body, { session, upsert: true }, !!req.useRegistry)
await session.commitTransaction()
} catch (error) {
await session.abortTransaction()
throw error
} finally {
await session.endSession()
}
const responseMessage = {
message: `${body?.username} was successfully created.`,
created: returnValue
}
const payload = {
action: 'create_user',
change: `${body?.username} was successfully created.`,
req_UUID: req.ctx.uuid,
org_UUID: returnValue.org_UUID,
user_UUID: returnValue.UUID,
user: returnValue
}
logger.info(JSON.stringify(payload))
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}, PUT /org/{shortname}/user/{username}
*
* @param {Object} req - The request object
* @param {Object} res - The response object
* @param {Function} next - The next middleware function
* @returns {Promise<void>}
*/
async function updateUser (req, res, next) {
const session = await mongoose.startSession()
try {
session.startTransaction()
const requesterShortName = req.ctx.org
const requesterUsername = req.ctx.user
const usernameParams = req.ctx.params.username
const shortNameParams = req.ctx.params.shortname
const userRepo = req.ctx.repositories.getBaseUserRepository()
const orgRepo = req.ctx.repositories.getBaseOrgRepository()
const queryParametersJson = req.ctx.query
// Get requester UUID for later
const requesterUUID = await userRepo.getUserUUID(requesterUsername, requesterShortName, { session }, !!req.useRegistry)
const targetUserUUID = await userRepo.getUserUUID(usernameParams, shortNameParams, { session }, !!req.useRegistry)
const isRequesterSecretariat = await orgRepo.isSecretariatByShortName(requesterShortName, { session })
const isAdmin = await userRepo.isAdmin(requesterUsername, requesterShortName, { session })
const targetOrgUUID = await orgRepo.getOrgUUID(shortNameParams, { session })
// if (req.useRegistry) {
// if (body?.role && typeof body?.role !== 'string') {
// return res.status(400).json({ message: 'Parameters were invalid', details: [{ param: 'role', msg: 'Parameter must be a string' }] })
// }
// }
if (!targetOrgUUID) {
logger.info({ uuid: req.ctx.uuid, message: `Target organization ${shortNameParams} does not exist.` })
await session.abortTransaction()
return res.status(404).json(error.orgDnePathParam(shortNameParams))
}
if (shortNameParams !== requesterShortName && !isRequesterSecretariat) {
logger.info({ uuid: req.ctx.uuid, message: `${shortNameParams} organization data can only be modified by users of the same organization or the Secretariat.` })
await session.abortTransaction()
return res.status(403).json(error.notSameOrgOrSecretariat())
}
// Specific check for org_short_name (Secretariat only)
if (queryParametersJson.org_short_name && !isRequesterSecretariat) {
logger.info({ uuid: req.ctx.uuid, message: 'Only Secretariat can reassign user organization.' })
await session.abortTransaction()
return res.status(403).json(error.notAllowedToChangeOrganization())
}
if (!isRequesterSecretariat && !isAdmin) {
if (targetUserUUID !== requesterUUID) {
if (!targetUserUUID) {
logger.info({ uuid: req.ctx.uuid, message: 'User DNE' })
await session.abortTransaction()
return res.status(404).json(error.userDne(usernameParams))
}
logger.info({ uuid: req.ctx.uuid, message: 'Not same user or secretariat' })
await session.abortTransaction()
return res.status(403).json(error.notSameUserOrSecretariat())
}
}
const newOrgShortNameToMoveTo = queryParametersJson.org_short_name
if (newOrgShortNameToMoveTo) {
if (newOrgShortNameToMoveTo === shortNameParams) {
logger.info({ uuid: req.ctx.uuid, message: `User ${usernameParams} is already in organization ${newOrgShortNameToMoveTo}.` })
await session.abortTransaction()
return res.status(403).json(error.alreadyInOrg(newOrgShortNameToMoveTo, usernameParams))
}
const newTargetRegistryOrgUUID = await orgRepo.getOrgUUID(newOrgShortNameToMoveTo, { session })
if (!newTargetRegistryOrgUUID) {
logger.info({ uuid: req.ctx.uuid, message: `New target organization ${newOrgShortNameToMoveTo} does not exist.` })
await session.abortTransaction()
return res.status(404).json(error.orgDne(newOrgShortNameToMoveTo, 'org_short_name', 'query'))
}
}
if (queryParametersJson.active) {
if (requesterUUID === targetUserUUID) {
await session.abortTransaction()
return res.status(403).json(error.notOrgAdminOrSecretariatUpdate())
}
}
if (!targetUserUUID) {
logger.info({ uuid: req.ctx.uuid, message: 'User DNE' })
await session.abortTransaction()
return res.status(404).json(error.userDne(usernameParams))
}
if (!await userRepo.orgHasUserByUUID(shortNameParams, targetUserUUID, { session })) {
logger.info({ uuid: req.ctx.uuid, message: `User ${usernameParams} does not exist for ${shortNameParams} organization.` })
await session.abortTransaction()
return res.status(404).json(error.userDne(usernameParams))
}
// General permission check for fields requiring admin/secretariat
if ((queryParametersJson.new_username || queryParametersJson['active_roles.remove'] || queryParametersJson['active_roles.add'])) {
if (!isRequesterSecretariat && !isAdmin) {
logger.info({ uuid: req.ctx.uuid, message: `User ${requesterUsername} (not Admin/Secretariat) trying to modify admin-only fields.` })
await session.abortTransaction()
return res.status(403).json(error.notOrgAdminOrSecretariatUpdate())
}
}
// If we get here, we have the permissions needed to change a username. But we need to make sure the name that they want to change it to DNE
if (queryParametersJson.new_username) {
const unameToCheck = await userRepo.findOneByUsernameAndOrgShortname(queryParametersJson.new_username, shortNameParams, { session })
if (unameToCheck) {
logger.info({ uuid: req.ctx.uuid, message: queryParametersJson.new_username + ' was not created because it already exists.' })
await session.abortTransaction()
return res.status(403).json(error.duplicateUsername(queryParametersJson.new_username, shortNameParams))
}
}
// This is a special case, and needs to be handled in the controller, and not in the repository
const rolesFromQuery = queryParametersJson['active_roles.remove'] ?? []
const removeRolesCollector = []
const processRoleRemoval = (r) => {
const roleToRemove = r.toUpperCase()
removeRolesCollector.push(roleToRemove)
}
rolesFromQuery.forEach(processRoleRemoval)
// Check to make sure we are NOT self demoting
if (removeRolesCollector.includes('ADMIN')) {
if (requesterUUID === targetUserUUID) {
await session.abortTransaction()
return res.status(403).json(error.notAllowedToSelfDemote())
}
}
const payload = await userRepo.updateUser(usernameParams, shortNameParams, queryParametersJson, { session }, !!req.useRegistry)
await session.commitTransaction()
return res.status(200).json({ message: `${usernameParams} was successfully updated.`, updated: payload })
} catch (err) {
if (session && session.inTransaction()) {
await session.abortTransaction()
}
next(err)
} finally {
if (session && session.id) { // Check if session is still valid before trying to end
try {
await session.endSession()
} catch (sessionEndError) {
logger.error({ uuid: req.ctx.uuid, message: 'Error ending session in finally block', error: sessionEndError })
}
}
}
}
/**
* Resets API secret for specified user.
* Called by PUT /org/{shortname}/user/{username}/reset_secret, PUT /registry/org/{shortname}/user/{username}/reset_secret
*
* @param {Object} req - The request object
* @param {Object} res - The response object
* @param {Function} next - The next middleware function
* @returns {Promise<void>}
*/
async function resetSecret (req, res, next) {
try {
const session = await mongoose.startSession({ causalConsistency: false })
const requesterOrgShortName = req.ctx.org
const requesterUsername = req.ctx.user
const targetOrgShortName = req.ctx.params.shortname
const targetUsername = req.ctx.params.username
const orgRepo = req.ctx.repositories.getBaseOrgRepository()
const userRepo = req.ctx.repositories.getBaseUserRepository()
try {
session.startTransaction()
// Check if target org exists
const targetOrgUUID = await orgRepo.getOrgUUID(targetOrgShortName, { session }, !req.useRegistry)
if (!targetOrgUUID) {
logger.info({ uuid: req.ctx.uuid, message: 'Org DNE' })
await session.abortTransaction()
return res.status(404).json(error.orgDnePathParam(targetOrgShortName))
}
// Check if target user exists in target org
const targetUserUUID = await userRepo.getUserUUID(targetUsername, targetOrgShortName, { session }, !!req.useRegistry)
if (!targetUserUUID) {
logger.info({ uuid: req.ctx.uuid, message: 'User DNE' })
await session.abortTransaction()
return res.status(404).json(error.userDne(targetUsername))
}
const requesterUserUUID = await userRepo.getUserUUID(requesterUsername, requesterOrgShortName, { session }, !!req.useRegistry)
const isRequesterSecretariat = await orgRepo.isSecretariatByShortName(requesterOrgShortName, { session })
if (!isRequesterSecretariat) {
// If they are in the same organization, they must be the target user themselves OR an admin of the target org.
// 1. WE are not the same user
if (requesterUserUUID !== targetUserUUID) {
// Check to see if we are the admin of the target organization
const isAdminOfTargetOrg = await userRepo.isAdmin(requesterUsername, targetOrgShortName, { session })
// The tests say we have to check the org next:
if (requesterOrgShortName !== targetOrgShortName && !isAdminOfTargetOrg) {
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.' })
await session.abortTransaction()
return res.status(403).json(error.notSameOrgOrSecretariat())
}
if (!isAdminOfTargetOrg) {
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.' })
await session.abortTransaction()
return res.status(403).json(error.notSameUserOrSecretariat())
}
}
}
const updatedSecret = await userRepo.resetSecret(targetUsername, targetOrgShortName, { session }, !!req.useRegistry)
logger.info({ uuid: req.ctx.uuid, message: `The API secret was successfully reset and sent to ${targetUsername}` })
const payload = {
action: 'reset_userAPIkey',
change: 'API secret was successfully reset.',
req_UUID: req.ctx.uuid,
org_UUID: targetOrgUUID
}
payload.user_UUID = targetUserUUID
logger.info(JSON.stringify(payload))
await session.commitTransaction()
return res.status(200).json({ 'API-secret': updatedSecret })
} catch (error) {
await session.abortTransaction()
throw error
} finally {
await session.endSession()
}
} catch (err) {
next(err)
}
}
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
}