-
Notifications
You must be signed in to change notification settings - Fork 122
Expand file tree
/
Copy pathregistry-org.controller.js
More file actions
822 lines (727 loc) · 34.9 KB
/
Copy pathregistry-org.controller.js
File metadata and controls
822 lines (727 loc) · 34.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
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
const mongoose = require('mongoose')
const logger = require('../../middleware/logger')
const { getConstants } = require('../../constants')
const _ = require('lodash')
const errors = require('./error')
const error = new errors.RegistryOrgControllerError()
const conversationErrors = require('../conversation.controller/error')
const convoError = new conversationErrors.ConversationControllerError()
const validateUUID = require('uuid').validate
const authContext = require('../../utils/authContext')
/**
* Retrieves information about all registry organizations.
*
* @async
* @function getAllOrgs
* @param {object} req - The Express request object.
* @param {object} res - The Express response object.
* @param {function} next - The next middleware function.
* @returns {Promise<void>} - A promise that resolves when the response is sent.
* @description This endpoint is accessible to Secretariat only. It retrieves a list of all registry organizations.
* Called by GET /api/registryOrg
*/
async function getAllOrgs (req, res, next) {
try {
const repo = req.ctx.repositories.getBaseOrgRepository()
const conversationRepo = req.ctx.repositories.getConversationRepository()
const isSecretariat = await authContext.isRequesterSecretariat(req, repo)
const CONSTANTS = getConstants()
let returnValue
// 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
try {
returnValue = await repo.getAllOrgs({ ...options }, false, isSecretariat)
// fetch conversations
for (let i = 0; i < returnValue.organizations.length; i++) {
const conversation = await conversationRepo.getAllByTargetUUID(returnValue.organizations[i].UUID, isSecretariat)
returnValue.organizations[i].conversation = conversation?.length ? conversation : undefined
}
} 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 })
}
return res.status(500).json({ message: 'Error fetching orgs' })
}
logger.info({ uuid: req.ctx.uuid, message: 'The orgs were sent to the user.' })
return res.status(200).json(returnValue)
} catch (err) {
next(err)
}
}
/**
* Retrieves information about a specific registry organization.
*
* @async
* @function getOrg
* @param {object} req - The Express request object, containing the organization identifier in `req.ctx.params.identifier`.
* @param {object} res - The Express response object.
* @param {function} next - The next middleware function.
* @returns {Promise<void>} - A promise that resolves when the response is sent.
* @description All authenticated users can access this endpoint. It retrieves information about the specified registry organization.
* Called by GET /api/registryOrg/:identifier
*/
async function getOrg (req, res, next) {
try {
const repo = req.ctx.repositories.getBaseOrgRepository()
const conversationRepo = req.ctx.repositories.getConversationRepository()
// User passed in parameter to filter for
const identifier = req.ctx.params.identifier
const identifierIsUUID = validateUUID(identifier)
let returnValue
try {
const requesterOrg = await authContext.getRequesterOrg(req, repo)
const isSecretariat = await authContext.isRequesterSecretariat(req, repo)
const isRequesterSameOrg = identifierIsUUID
? requesterOrg.UUID === identifier
: await authContext.isRequesterSameOrg(req, repo, identifier)
if (!isRequesterSameOrg && !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, {}, false, isSecretariat)
if (returnValue) {
// fetch conversation
const conversation = await conversationRepo.getAllByTargetUUID(returnValue.UUID, isSecretariat)
if (isSecretariat) {
returnValue.conversation = conversation?.length ? _.map(conversation, c => _.omit(c, ['__v', '_id', 'previous_conversation_uuid', 'next_conversation_uuid', 'target_uuid'])) : undefined
} else {
returnValue.conversation = conversation?.length ? _.map(conversation, c => _.omit(c, ['__v', '_id', 'UUID', 'previous_conversation_uuid', 'next_conversation_uuid', 'target_uuid', 'visibility'])) : undefined
}
}
} 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 })
}
throw error
}
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)
}
}
/**
* Creates a new registry organization.
*
* @async
* @function createOrg
* @param {object} req - The Express request object, containing the organization details in `req.ctx.body`.
* @param {object} res - The Express response object.
* @param {function} next - The next middleware function.
* @returns {Promise<void>} - A promise that resolves when the response is sent.
* @description This endpoint is accessible to Secretariat only. It creates a new registry organization.
* Called by POST /api/registryOrg
*/
async function createOrg (req, res, next) {
try {
const session = await mongoose.startSession({ causalConsistency: false })
const repo = req.ctx.repositories.getBaseOrgRepository()
const body = req.ctx.body
const isSecretariat = await authContext.isRequesterSecretariat(req, repo, { session })
let createdOrg
// 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'))
}
if (!isSecretariat) {
const secretariatOnlyFields = getConstants().SECRETARIAT_ONLY_FIELDS
const restrictedFieldsSent = secretariatOnlyFields.filter(field => _.has(body, field))
if (restrictedFieldsSent.length > 0) {
logger.info({ uuid: req.ctx.uuid, message: `Non-secretariat attempted to edit restricted fields: ${restrictedFieldsSent.join(', ')}` })
return res.status(403).json(error.secretariatOnlyEditing(restrictedFieldsSent))
}
}
try {
session.startTransaction()
const result = 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 for duplicate short_name
if (await repo.orgExists(body?.short_name, { session })) {
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))
}
// Check for alias collisions
const collisionString = await repo.checkAliasCollisions(body?.short_name, body?.name, body?.aliases, null, { session })
if (collisionString) {
logger.info({
uuid: req.ctx.uuid,
message: `${body?.short_name} organization was not created because the string '${collisionString}' collides with another organization's short_name, name, or alias.`
})
await session.abortTransaction()
return res.status(400).json(error.aliasCollision(collisionString))
}
const userRepo = req.ctx.repositories.getBaseUserRepository()
const requestingUserUUID = await authContext.getRequesterUserUUID(req, userRepo, repo, { session })
// Create the org – repo.createOrg will handle field mapping
createdOrg = await repo.createOrg(body, { session, upsert: true }, false, requestingUserUUID, isSecretariat)
await session.commitTransaction()
} catch (createErr) {
await session.abortTransaction()
if (createErr.message && createErr.message.includes('Unknown Org type requested')) {
return res.status(400).json({ message: createErr.message })
}
throw createErr
} finally {
await session.endSession()
}
let responseMessage
let payload
if (isSecretariat) {
responseMessage = {
message: `${body?.short_name} organization was successfully created.`,
created: createdOrg
}
payload = {
action: 'create_org',
change: `${body?.short_name} organization was successfully created.`,
req_UUID: req.ctx.uuid,
org_UUID: createdOrg.UUID,
org: createdOrg
}
} else {
payload = {
action: 'create_review_org',
change: body?.short_name + ' was successfully requested to be Reviewed.',
req_UUID: req.ctx.uuid
}
responseMessage = {
message: body?.short_name + ' was successfully received to be reviewed. By using Load ReviewObject data, you can check for a reply from the Secretariat about Joint Approval items.',
created: body?.shortName
}
}
logger.info(JSON.stringify(payload))
return res.status(200).json(responseMessage)
} catch (err) {
next(err)
}
}
async function validateRequestedShortName (req, repo, body, shortName, session) {
const requestedShortName = body?.new_short_name || body?.short_name || shortName
if (_.has(body, 'short_name') && _.has(body, 'new_short_name') && body.short_name !== shortName && body.short_name !== body.new_short_name) {
logger.info({
uuid: req.ctx.uuid,
message: `${shortName} organization could not be updated because short_name and new_short_name identify different requested short names.`
})
return {
status: 400,
response: {
message: 'Parameters were invalid',
errors: [{
instancePath: '/short_name',
message: 'short_name must match the path shortname or new_short_name when new_short_name is provided'
}]
}
}
}
if (requestedShortName !== shortName && await repo.orgExists(requestedShortName, { session })) {
logger.info({
uuid: req.ctx.uuid,
message: `${shortName} organization could not be updated because new short name ${requestedShortName} already exists.`
})
return {
status: 400,
response: error.duplicateShortname(requestedShortName)
}
}
const collisionString = await repo.checkAliasCollisions(requestedShortName, body?.name, body?.aliases, shortName, { session })
if (collisionString) {
logger.info({
uuid: req.ctx.uuid,
message: `${shortName} organization could not be updated because the string '${collisionString}' collides with another organization's short_name, name, or alias.`
})
return {
status: 400,
response: error.aliasCollision(collisionString)
}
}
return { requestedShortName }
}
/**
* Updates an existing registry organization.
*
* @async
* @function updateOrg
* @param {object} req - The Express request object, containing the organization shortname in `req.ctx.params.shortname` and update details in `req.ctx.query`.
* @param {object} res - The Express response object.
* @param {function} next - The next middleware function.
* @returns {Promise<void>} - A promise that resolves when the response is sent.
* @description This endpoint is accessible to Secretariat only. It updates an existing registry organization.
* Called by PUT /api/registryOrg/:shortname
*/
async function updateOrg (req, res, next) {
try {
const session = await mongoose.startSession({ causalConsistency: false })
const shortName = req.ctx.params.shortname
const repo = req.ctx.repositories.getBaseOrgRepository()
const userRepo = req.ctx.repositories.getBaseUserRepository()
const conversationRepo = req.ctx.repositories.getConversationRepository()
const { conversation, ...body } = req.ctx.body
let updatedOrg
let jointApprovalRequired
try {
session.startTransaction()
const requester = await authContext.getRequesterContext(req, { orgRepo: repo, userRepo }, { session })
const isSecretariat = requester.isSecretariat
const isAdmin = requester.isAdmin
const requestingUser = requester.user
const org = await repo.findOneByShortName(shortName, { session })
const requesterSameOrg = org
? await authContext.isRequesterSameOrg(req, repo, org, { session })
: await authContext.isRequesterSameOrg(req, repo, shortName, { session })
if (!isSecretariat && !requesterSameOrg) {
logger.info({ uuid: req.ctx.uuid, message: shortName + ' organization can only be updated by the users of the same organization or the Secretariat.' })
await session.abortTransaction()
return res.status(403).json(error.notSameOrgOrSecretariat())
}
if (!isSecretariat && !isAdmin) {
logger.info({ uuid: req.ctx.uuid, message: shortName + ' organization can only be updated by the Secretariat or an Org Admin.' })
await session.abortTransaction()
return res.status(403).json(error.notOrgAdminOrSecretariatUpdate())
}
if (!isSecretariat) {
const secretariatOnlyFields = getConstants().SECRETARIAT_ONLY_FIELDS
const restrictedFieldsSent = secretariatOnlyFields.filter(field => _.has(body, field))
if (restrictedFieldsSent.length > 0) {
logger.info({ uuid: req.ctx.uuid, message: `Non-secretariat attempted to edit restricted fields: ${restrictedFieldsSent.join(', ')}` })
await session.abortTransaction()
return res.status(403).json(error.secretariatOnlyEditing(restrictedFieldsSent))
}
}
// Edge Case: if a user has requested an org, but it is not approved yet, then we need to check to see if if there is a review org for the shortname request.
if (!org) {
// resolve edge case
const reviewRepo = req.ctx.repositories.getReviewObjectRepository()
const reviewOrg = await reviewRepo.getOrgReviewObjectByOrgShortname(shortName, isSecretariat, { session })
// Eventually we should validate this, but this is a bit tricky.
if (reviewOrg) {
// For review objects, verify the provided UUID matches the target review object's UUID
const providedUUID = body?.UUID || body?.uuid
if (providedUUID && providedUUID !== reviewOrg.uuid) {
await session.abortTransaction()
return res.status(400).json(error.uuidProvided('org'))
}
const updateResult = await reviewRepo.updateReviewOrgObject(body, reviewOrg.uuid, { session })
if (updateResult) {
updatedOrg = reviewOrg
await session.commitTransaction()
return res.status(200).json({ message: 'Review object updated successfully' })
}
} else {
logger.info({ uuid: req.ctx.uuid, message: shortName + ' organization could not be updated because it does not exist.' })
await session.abortTransaction()
return res.status(404).json(error.orgDnePathParam(shortName))
}
}
// Verify that the provided UUID matches the existing organization's immutable database UUID
if (org) {
const providedUUID = body?.UUID || body?.uuid
if (providedUUID && providedUUID !== org.UUID) {
await session.abortTransaction()
return res.status(400).json(error.uuidProvided('org'))
}
}
// Validate org
const result = repo.validateOrg(body, { session })
if (!result.isValid) {
logger.error(JSON.stringify({ uuid: req.ctx.uuid, message: 'CVE JSON schema validation FAILED.' }))
await session.abortTransaction()
return res.status(400).json({ message: 'Parameters were invalid', errors: result.errors })
}
// Validate conversation (if it exists)
if (conversation) {
if (
typeof conversation !== 'object' ||
!conversation.body ||
!conversationRepo.validateConversation(conversation)
) {
logger.error(JSON.stringify({ uuid: req.ctx.uuid, message: 'Invalid conversation object.' }))
await session.abortTransaction()
return res.status(400).json(convoError.invalidConversationObject())
}
}
const shortNameValidation = await validateRequestedShortName(req, repo, body, shortName, session)
if (shortNameValidation.status) {
await session.abortTransaction()
return res.status(shortNameValidation.status).json(shortNameValidation.response)
}
// Handle secretariat "stomping" of pending review objects
if (isSecretariat) {
const reviewRepo = req.ctx.repositories.getReviewObjectRepository()
const pendingReview = await reviewRepo.getOrgReviewObjectByOrgShortname(shortName, isSecretariat, { session })
if (pendingReview) {
const pendingReviewData = pendingReview.new_review_data
// Merge to get full expected state from pending review vs incoming
const pendingFullState = _.merge({}, org.toObject(), pendingReviewData)
const incomingFullState = _.merge({}, org.toObject(), body)
// Clean for comparison (remove metadata)
const cleanPending = _.omit(pendingFullState, ['_id', '__v', '__t', 'createdAt', 'updatedAt', 'created', 'last_updated'])
const cleanIncoming = _.omit(incomingFullState, ['_id', '__v', '__t', 'createdAt', 'updatedAt', 'created', 'last_updated'])
// Compare and set status accordingly
if (_.isEqual(cleanPending, cleanIncoming)) {
await reviewRepo.approveReviewOrgObject(pendingReview.uuid, req.ctx.user, { session })
} else {
await reviewRepo.rejectReviewOrgObject(pendingReview.uuid, req.ctx.user, { session })
}
}
}
// Update Org full will cause a write to the Conversations collection, to avoid a read-after-write issue, we need to get the previous conversation data first
const previousConversation = await conversationRepo.getAllByTargetUUID(await repo.getOrgUUID(shortName, { session }), isSecretariat, { session }) || []
updatedOrg = await repo.updateOrgFull(shortName, req.ctx.body, { session }, false, requestingUser.UUID, isAdmin, isSecretariat)
jointApprovalRequired = _.get(updatedOrg, 'joint_approval_required', false)
_.unset(updatedOrg, 'joint_approval_required')
// append previous conversations to any conversations that are in the org already
const currentConversations = Array.isArray(updatedOrg?.conversation) ? updatedOrg.conversation : []
const prevConversations = Array.isArray(previousConversation) ? previousConversation : []
if (updatedOrg) {
updatedOrg.conversation = [...currentConversations, ...prevConversations].map(c => _.omit(c, ['__v', '_id', 'previous_conversation_uuid', 'next_conversation_uuid']))
}
await session.commitTransaction()
} catch (updateErr) {
await session.abortTransaction()
throw updateErr
} finally {
await session.endSession()
}
if (jointApprovalRequired) {
const responseMessage = {
message: `${body?.short_name} organization was successfully updated, but joint approval is required for some fields. Check the ReviewObject for your org to check for a reply from the Secretariat about Joint Approval items.`,
updated: updatedOrg
}
const payload = {
action: 'update_registry_org',
change: body?.short_name + 'organization was successfully updated, but joint approval is required for some fields. Check the ReviewObject for your org to check for a reply from the Secretariat about Joint Approval items.',
req_UUID: req.ctx.uuid,
org_UUID: updatedOrg.UUID,
org: updatedOrg
}
logger.info(JSON.stringify(payload))
return res.status(200).json(responseMessage)
} else {
const responseMessage = {
message: `${body?.short_name} organization was successfully updated.`,
updated: updatedOrg
}
const payload = {
action: 'update_registry_org',
change: body?.short_name + ' was successfully updated.',
req_UUID: req.ctx.uuid,
org_UUID: updatedOrg.UUID,
org: updatedOrg
}
logger.info(JSON.stringify(payload))
return res.status(200).json(responseMessage)
}
} catch (err) {
next(err)
}
}
/**
* Deletes an existing registry organization.
*
* @async
* @function deleteOrg
* @param {object} req - The Express request object, containing the organization identifier in `req.ctx.params.identifier`.
* @param {object} res - The Express response object.
* @param {function} next - The next middleware function.
* @returns {Promise<void>} - A promise that resolves when the response is sent.
* @description This endpoint is accessible to Secretariat only. It deletes an existing registry organization.
* Called by DELETE /api/registryOrg/:identifier
*/
async function deleteOrg (req, res, next) {
try {
const session = await mongoose.startSession({ causalConsistency: false })
const repo = req.ctx.repositories.getBaseOrgRepository()
const shortName = req.ctx.params.identifier
let targetOrgUUID
try {
session.startTransaction()
const org = await repo.findOneByShortName(shortName)
if (!org) {
logger.info({ uuid: req.ctx.uuid, message: shortName + ' organization could not be deleted because it does not exist.' })
await session.abortTransaction()
return res.status(404).json(error.orgDnePathParam(shortName))
}
targetOrgUUID = org.UUID
await repo.deleteOrg(shortName, { session })
await session.commitTransaction()
} catch (deleteErr) {
await session.abortTransaction()
throw deleteErr
} finally {
await session.endSession()
}
const responseMessage = {
message: `${shortName} organization was successfully deleted.`
}
const payload = {
action: 'delete_registry_org',
change: shortName + ' was successfully deleted.',
req_UUID: req.ctx.uuid,
org_UUID: targetOrgUUID
}
logger.info(JSON.stringify(payload))
return res.status(200).json(responseMessage)
} catch (err) {
next(err)
}
}
/**
* Retrieves all users for the organization with the specified short name.
*
* @async
* @function getUsers
* @param {object} req - The Express request object, containing the organization shortname in `req.ctx.params.shortname`.
* @param {object} res - The Express response object.
* @param {function} next - The next middleware function.
* @returns {Promise<void>} - A promise that resolves when the response is sent. Response body includes 'role' field for admins.
* @description All registered users can access this endpoint. Regular, CNA & Admin Users can retrieve information about users in the same organization.
* Secretariat can retrieve all user information for any organization.
* Called by GET /api/registryOrg/: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 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 authContext.isRequesterSecretariat(req, orgRepo)
if (!orgUUID) {
logger.info({ uuid: req.ctx.uuid, message: orgShortName + ' organization does not exist.' })
return res.status(404).json(error.orgDnePathParam(orgShortName))
}
const isSameOrg = await authContext.isRequesterSameOrg(req, orgRepo, { UUID: orgUUID, short_name: orgShortName })
if (!isSameOrg && !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())
}
// This should always return Registry typed
const payload = await userRepo.getAllUsersByOrgShortname(orgShortName, options, true)
// Hydrate the role field
const org = await orgRepo.findOneByShortName(orgShortName)
payload.users.forEach(user => {
user.role = org.admins.includes(user.UUID) ? 'ADMIN' : user.role // Default to existing role if not admin
})
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)
}
}
/**
* Create a user with the provided short name as the owning organization.
*
* @async
* @function createUserByOrg
* @param {object} req - The Express request object, containing the organization shortname in `req.ctx.params.shortname` and user details in `req.ctx.body`.
* @param {object} res - The Express response object.
* @param {function} next - The next middleware function.
* @returns {Promise<void>} - A promise that resolves when the response is sent.
* @description User must belong to an organization with the Secretariat role or be an Admin of the organization.
* Admin User: Creates a user for the Admin's organization.
* Secretariat: Creates a user for any organization.
* Called by POST /api/registryOrg/:shortname/user
*/
async function createUserByOrg (req, res, next) {
const session = await mongoose.startSession({ causalConsistency: false })
try {
const body = req.ctx.body
const userRepo = req.ctx.repositories.getBaseUserRepository()
const orgRepo = req.ctx.repositories.getBaseOrgRepository()
const orgShortName = req.ctx.params.shortname
let returnValue
// Check to make sure Org Exists first
const orgUUID = await orgRepo.getOrgUUID(orgShortName, {}, false)
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()
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 (!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 })
}
// Ask repo if user already exists
if (await userRepo.orgHasUser(orgShortName, body?.username, { session }, true)) {
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))
}
const isRequesterSecretariat = await authContext.isRequesterSecretariat(req, orgRepo, { session })
const isRequesterAdminOfTargetOrg = await authContext.isRequesterAdminOfOrg(req, userRepo, orgRepo, orgShortName, { session })
if (!isRequesterSecretariat && !isRequesterAdminOfTargetOrg) {
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())
}
const requestingUserUUID = await authContext.getRequesterUserUUID(req, userRepo, orgRepo, { session })
returnValue = await userRepo.createUser(orgShortName, body, { session, upsert: true }, true, requestingUserUUID)
await session.commitTransaction()
} catch (error) {
await session.abortTransaction()
throw error
} finally {
await session.endSession()
}
const secret = returnValue.secret
delete returnValue.secret
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))
returnValue.secret = secret
const responseMessage = {
message: `${body?.username} was successfully created.`,
created: returnValue
}
return res.status(200).json(responseMessage)
} catch (err) {
next(err)
}
}
/**
* Updates the conversation at the provided index for the given organization.
*
* @async
* @function editConversationForOrg
* @param {object} req - The Express request object, containing the organization shortname in `req.ctx.params.shortname` and conversation updates in `req.ctx.body`.
* @param {object} res - The Express response object.
* @param {function} next - The next middleware function.
* @returns {Promise<void>} - A promise that resolves when the response is sent.
* @description User must be the original author of the conversation or the Secretariat role.
* The original author is allowed to update the conversation message body.
* Secretariat is allowed to update the conversation message body and visibility.
* Called by PUT /api/registry/org/:shortname/conversation/:index
*/
async function editConversationForOrg (req, res, next) {
const repo = req.ctx.repositories.getBaseOrgRepository()
const userRepo = req.ctx.repositories.getBaseUserRepository()
const conversationRepo = req.ctx.repositories.getConversationRepository()
const orgShortName = req.params.shortname || req.ctx.params.shortname
const index = parseInt(req.params.index || req.ctx.params.index)
const incomingParameters = req.ctx.body
const session = await mongoose.startSession({ causalConsistency: false })
try {
const orgUUID = await repo.getOrgUUID(orgShortName, {}, false)
if (!orgUUID) {
await session.endSession()
return res.status(404).json(error.orgDnePathParam(orgShortName))
}
await session.startTransaction()
// Find the conversation by index to get its actual UUID
const conversation = await conversationRepo.findByTargetUUIDAndIndex(orgUUID, index, { session })
if (!conversation) {
await session.abortTransaction()
await session.endSession()
return res.status(404).json(convoError.conversationIndexDne(orgShortName, index))
}
const isSecretariat = await authContext.isRequesterSecretariat(req, repo, { session })
// Authorization Logic
if (!isSecretariat) {
// Check visibility change attempt
if (incomingParameters.visibility) {
await session.abortTransaction()
await session.endSession()
return res.status(403).json({ message: 'Only the Secretariat is allowed to change the visibility of a conversation.' })
}
const requestingUser = await authContext.getRequesterUser(req, userRepo, repo, { session })
if (!requestingUser) {
await session.abortTransaction()
await session.endSession()
return res.status(403).json({ message: 'You must be the original author or Secretariat to edit this conversation.' })
}
// UUID extraction and comparison
const userUUID = requestingUser.UUID || requestingUser.uuid
const authorUUID = conversation.author_uuid || conversation.author_id || conversation.author_UUID
const isAuthor = String(authorUUID).toLowerCase() === String(userUUID).toLowerCase()
const isStillInOrg = await authContext.isRequesterSameOrg(req, repo, { UUID: orgUUID, short_name: orgShortName }, { session })
if (!isAuthor || !isStillInOrg) {
await session.abortTransaction()
await session.endSession()
return res.status(403).json({ message: 'You must be the original author or Secretariat to edit this conversation.' })
}
}
// Prepare Update
const updatePayload = { body: incomingParameters.body }
if (isSecretariat && incomingParameters.visibility) {
updatePayload.visibility = incomingParameters.visibility
}
const returnValue = await conversationRepo.editConversation(conversation.UUID, updatePayload, { session })
await session.commitTransaction()
await session.endSession()
return res.status(200).json({
message: 'The conversation was successfully updated.',
updated: returnValue
})
} catch (err) {
if (session.inTransaction()) {
await session.abortTransaction()
}
await session.endSession()
logger.error({ uuid: req.ctx.uuid, message: err.stack })
next(err)
}
}
module.exports = {
ALL_ORGS: getAllOrgs,
SINGLE_ORG: getOrg,
CREATE_ORG: createOrg,
UPDATE_ORG: updateOrg,
DELETE_ORG: deleteOrg,
USER_ALL: getUsers,
USER_CREATE_SINGLE: createUserByOrg,
EDIT_CONVERSATION: editConversationForOrg
}