-
Notifications
You must be signed in to change notification settings - Fork 122
Expand file tree
/
Copy pathregistry-user.controller.js
More file actions
557 lines (471 loc) · 20.5 KB
/
Copy pathregistry-user.controller.js
File metadata and controls
557 lines (471 loc) · 20.5 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
const mongoose = require('mongoose')
const logger = require('../../middleware/logger')
const { getConstants } = require('../../constants')
const errors = require('../user.controller/error')
const error = new errors.UserControllerError()
const validateUUID = require('uuid').validate
const _ = require('lodash')
/**
* Retrieves information about all registry users.
*
* @async
* @function getAllUsers
* @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. Response body includes 'role' field for admins.
* @description This endpoint is accessible to Secretariat only. It retrieves a list of all registry users.
* Called by GET /api/registryUser
*/
async function getAllUsers (req, res, next) {
try {
const CONSTANTS = getConstants()
const repo = req.ctx.repositories.getBaseUserRepository()
// 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.getAllUsers(options)
// Hydrate roles
const orgRepo = req.ctx.repositories.getBaseOrgRepository()
const distinctOrgUUIDs = [...new Set(returnValue.users.map(u => u.org_UUID))]
// Fetch all relevant orgs in one go (or in parallel) if possible, but map is easy for now
// Since we don't have a "getManyOrgsByUUID", we might need to do it one by one or improve repository
// For now, let's iterate and fetch. It's not optimal but safe given repo limitations.
// Optimization: We can build a map of orgUUID -> orgObject
const orgMap = {}
for (const uuid of distinctOrgUUIDs) {
// We need the org content to get admins
const org = await orgRepo.findOneByUUID(uuid)
if (org) {
orgMap[uuid] = org
}
}
returnValue.users.forEach(user => {
const org = orgMap[user.org_UUID]
if (org && org.admins && org.admins.includes(user.UUID)) {
user.role = 'ADMIN'
}
// If not admin, leave as is (undefined or empty or whatever it was)
})
logger.info({ uuid: req.ctx.uuid, message: 'The user information was sent to the secretariat user.' })
return res.status(200).json(returnValue)
} catch (err) {
next(err)
}
}
/**
* Retrieves information about a specific registry user.
*
* @async
* @function getUser
* @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. Response body includes 'role' field for admins.
* @description All authenticated users can access this endpoint. It retrieves information about the specified registry user.
* Called by GET /api/registryUser/:identifier
*/
async function getUser (req, res, next) {
/*
This function is a little bit overloaded ATM until future releases of CVE-Services
Currently it can be called with just an identifier (UUID) OR with the org shortname and username
We need to make sure that either way we convert to one or the other. For now, I am going shortname / username
*/
// Check to see if identifier is set
const identifier = req.ctx.params.identifier
// if identifier is set, BUT it is a username
if (identifier && !validateUUID(identifier)) {
return res.status(400).json({ error: 'This function expects a UUID when called this way' })
}
let userToGetParameters = {
org: req.ctx.params.shortname,
username: req.ctx.params.username
}
const userRepo = req.ctx.repositories.getBaseUserRepository()
const repo = req.ctx.repositories.getBaseOrgRepository()
const isSecretariat = await repo.isSecretariatByShortName(req.ctx.org)
try {
const result = identifier
? await userRepo.getUserUUID(identifier)
: await userRepo.findOneByUsernameAndOrgShortname(userToGetParameters.username, userToGetParameters.org)
const org = identifier
? await repo.getOrg(identifier, true)
: await repo.getOrg(req.ctx.params.shortname)
if (!result) {
logger.info({ uuid: req.ctx.uuid, message: identifier || userToGetParameters.username + 'user could not be found.' })
return res.status(404).json(error.userDne(userToGetParameters.username))
}
userToGetParameters = {
org: org.short_name,
username: result.username
}
if (!isSecretariat && req.ctx.org !== userToGetParameters.org) {
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())
}
const user = result.toObject()
const userPayload = _.omit(user, ['secret', '_id', '__v'])
if (org.admins?.includes(userPayload.UUID)) {
userPayload.role = 'ADMIN'
}
return res.status(200).json(userPayload)
} catch (err) {
next(err)
}
}
async function createUser (req, res, next) {
const session = await mongoose.startSession({ causalConsistency: false })
try {
const orgRepo = req.ctx.repositories.getBaseOrgRepository()
const userRepo = req.ctx.repositories.getBaseUserRepository()
const body = req.ctx.body
const orgShortName = req.ctx.params.shortname
let returnValue
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()
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 })) {
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 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 })
await session.commitTransaction()
} catch (error) {
await session.abortTransaction()
throw error
} finally {
await session.endSession()
}
const responseMessage = {
message: `${body?.username} was successfully created.`,
created: returnValue
}
return res.status(200).json(responseMessage)
} catch (err) {
next(err)
}
}
async function updateUser (req, res, next) {
/*
This function is a little bit overloaded ATM until future releases of CVE-Services
Currently it can be called with just an identifier (UUID) OR with the org shortname and username
We need to make sure that either way we convert to one or the other. For now, I am going shortname / username
*/
const session = await mongoose.startSession({ causalConsistency: false })
// Check to see if identifier is set
const identifier = req.ctx.params.identifier
// if identifier is set, BUT it is a username
if (identifier && !validateUUID(identifier)) {
return res.status(400).json({ error: 'This function expects a UUID when called this way' })
}
const orgRepo = req.ctx.repositories.getBaseOrgRepository()
const userRepo = req.ctx.repositories.getBaseUserRepository()
const body = req.ctx.body
if ('secret' in body) {
logger.info({ uuid: req.ctx.uuid, message: 'User attempted to update the secret.' })
return res.status(400).json(error.secretUpdateNotAllowed())
}
const requestingUserParameters = {
org: req.ctx.org,
username: req.ctx.user
}
const userToEditParameters = {
org: req.ctx.params.shortname,
username: req.ctx.params.username
}
const isSecretariat = await orgRepo.isSecretariatByShortName(requestingUserParameters.org, { session })
const isAdmin = await userRepo.isAdmin(requestingUserParameters.username, userToEditParameters.org, { session })
// TODO: This will need to be atomic at some point like revoke or grant
// Specific check for org_short_name (Secretariat only)
const userToEdit = identifier
? await userRepo.getUserUUID(identifier)
: await userRepo.findOneByUsernameAndOrgShortname(userToEditParameters.username, userToEditParameters.org, { session })
const org = await orgRepo.findOneByShortName(userToEditParameters.org)
if (!org) {
logger.info({ uuid: req.ctx.uuid, message: `Target organization ${userToEditParameters.org} does not exist.` })
return res.status(404).json(error.orgDnePathParam(userToEditParameters.org))
}
if (body.org_short_name && !isSecretariat) {
logger.info({ uuid: req.ctx.uuid, message: 'Only Secretariat can reassign user organization.' })
return res.status(403).json(error.notAllowedToChangeOrganization())
}
if (body.org_short_name) {
const targetOrg = await orgRepo.findOneByShortName(body.org_short_name)
if (!targetOrg) {
logger.info({ uuid: req.ctx.uuid, message: `Target organization ${body.org_short_name} does not exist.` })
return res.status(404).json(error.orgDnePathParam(body.org_short_name))
}
}
if (body.org_short_name && isSecretariat && userToEditParameters.org === org.short_name && body.org_short_name === org.short_name) {
logger.info({ uuid: req.ctx.uuid, message: `User ${userToEditParameters.username} is already in organization ${userToEditParameters.org}.` })
return res.status(403).json(error.alreadyInOrg(org.short_name, userToEditParameters.username))
}
if (!org) {
logger.info({ uuid: req.ctx.uuid, message: 'Org DNE' })
return res.status(404).json(error.orgDnePathParam(userToEditParameters.org))
}
if (!isSecretariat && !isAdmin && requestingUserParameters.org !== userToEditParameters.org) {
logger.info({ uuid: req.ctx.uuid, message: requestingUserParameters.org + ' user can only be updated by the user or admins of the same organization or the Secretariat.' })
return res.status(403).json(error.notSameOrgOrSecretariat())
}
if (!isSecretariat && !isAdmin) {
if (requestingUserParameters.username !== userToEditParameters.username) {
if (!userToEdit) {
logger.info({ uuid: req.ctx.uuid, message: 'User DNE' })
return res.status(404).json(error.userDne(userToEditParameters.username))
}
logger.info({ uuid: req.ctx.uuid, message: 'Not same user or secretariat' })
return res.status(403).json(error.notSameUserOrSecretariat())
}
}
if (!org) {
logger.info({ uuid: req.ctx.uuid, message: `Target organization ${userToEditParameters.org} does not exist.` })
return res.status(404).json(error.orgDnePathParam(userToEditParameters.org))
}
if (!userToEdit) {
logger.info({ uuid: req.ctx.uuid, message: userToEditParameters.username + ' user could not be found.' })
return res.status(404).json(error.userDne(userToEditParameters.username))
}
if (!isSecretariat) {
// For now, we want to make sure that no one, other than a secretariat can edit time fields
delete body.created
delete body.last_updated
}
let result
let updatedUser
let updatedUserUUID
try {
session.startTransaction()
try {
// if a user is NOT an ADMIN OR SECRETARIAT they can only update their name fields
if (!isSecretariat && !isAdmin) {
const allowedFields = ['name', 'name.first', 'name.last', 'name.middle', 'name.suffix']
const restrictedUpdates = _.omit(body, allowedFields)
const keysToCheck = Object.keys(restrictedUpdates)
const originalValues = _.pick(JSON.parse(JSON.stringify(userToEdit)), keysToCheck)
if (!_.isEqual(restrictedUpdates, originalValues)) {
logger.info({ uuid: req.ctx.uuid, message: 'Regular users can only update their contact info.' })
await session.abortTransaction()
return res.status(400).json(error.notAllowedToChangeField())
}
}
result = await userRepo.validateUser(body)
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 (body?.username && body.username !== userToEdit.username) {
if (await userRepo.orgHasUser(userToEditParameters.org, body.username, { session })) {
logger.info({ uuid: req.ctx.uuid, message: 'The username ' + body.username + ' already exists.' })
await session.abortTransaction()
return res.status(403).json(error.duplicateUsername())
}
}
// UUID of the user will not change, lets get it before we write to avoid read after write issues.
updatedUserUUID = await userRepo.getUserUUID(req.ctx.user, org.UUID)
updatedUser = await userRepo.updateUserFull(userToEdit.UUID, body, { session })
await session.commitTransaction()
} catch (error) {
await session.abortTransaction()
throw error
} finally {
await session.endSession()
}
const payload = {
action: 'update_registry_user',
change: userToEditParameters.username + ' was successfully updated.',
req_UUID: req.ctx.uuid,
org_UUID: org.UUID,
user: updatedUser,
user_UUID: updatedUserUUID
}
logger.info(JSON.stringify(payload))
return res.status(200).json(
{
message: userToEditParameters.username + ' was successfully updated.',
updated: updatedUser
}
)
} catch (err) {
next(err)
}
}
async function deleteUser (req, res, next) {
try {
const userRepo = req.ctx.repositories.getBaseUserRepository()
const orgRepo = req.ctx.repositories.getBaseOrgRepository()
const userUUID = req.ctx.params.identifier
const user = await userRepo.findUserByUUID(userUUID)
if (!user) {
logger.info({ uuid: req.ctx.uuid, message: 'User DNE' })
return res.status(404).json(error.userDne(userUUID))
}
await userRepo.deleteUserByUUID(userUUID)
const payload = {
action: 'delete_registry_user',
change: user.username + ' was successfully deleted.',
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))
const responseMessage = {
message: user.username + ' was successfully deleted.'
}
return res.status(200).json(responseMessage)
} catch (err) {
next(err)
}
}
async function grantRole (req, res, next) {
const session = await mongoose.startSession()
try {
const orgShortName = req.ctx.params.shortname
const username = req.ctx.params.username
const role = req.ctx.body.role
const callingUser = req.ctx.user
const callingOrg = req.ctx.org
const userRepo = req.ctx.repositories.getBaseUserRepository()
const orgRepo = req.ctx.repositories.getBaseOrgRepository()
// Right now, we only allow users to be admin
if (role !== 'ADMIN') {
return res.status(400).json(
{
error: 'BAD_INPUT',
message: 'Invalid role request. Granting of this role is not supported.'
})
}
// Check if target org exists
const targetOrgUUID = await orgRepo.getOrgUUID(orgShortName)
if (!targetOrgUUID) {
return res.status(404).json(error.orgDnePathParam(orgShortName))
}
// Check if target user exists in target org
const targetUser = await userRepo.findOneByUsernameAndOrgShortname(username, orgShortName)
if (!targetUser) {
return res.status(404).json(error.userDne(username))
}
const isSecretariat = await orgRepo.isSecretariatByShortName(callingOrg)
const isAdmin = await userRepo.isAdmin(callingUser, callingOrg)
if (callingOrg !== orgShortName && !isSecretariat) {
return res.status(403).json(error.notSameOrgOrSecretariat())
}
if (!isSecretariat && !isAdmin) {
return res.status(403).json(error.notOrgAdminOrSecretariatUpdate())
}
try {
session.startTransaction()
await orgRepo.addAdmin(orgShortName, targetUser.UUID, { session })
await session.commitTransaction()
} catch (error) {
await session.abortTransaction()
throw error
} finally {
await session.endSession()
}
logger.info({ uuid: req.ctx.uuid, message: `Role ${role} granted to user ${username} in org ${orgShortName}` })
return res.status(200).json({ message: `Role ${role} granted to user ${username}.` })
} catch (err) {
next(err)
}
}
async function revokeRole (req, res, next) {
const session = await mongoose.startSession()
try {
const orgShortName = req.ctx.params.shortname
const username = req.ctx.params.username
const role = req.ctx.body.role
const callingUser = req.ctx.user
const callingOrg = req.ctx.org
const userRepo = req.ctx.repositories.getBaseUserRepository()
const orgRepo = req.ctx.repositories.getBaseOrgRepository()
// Right now, we only allow users to be admin
if (role !== 'ADMIN') {
return res.status(400).json(
{
error: 'BAD_INPUT',
message: 'Invalid role request. Revocation of this role is not supported.'
})
}
// Check if target org exists
const targetOrgUUID = await orgRepo.getOrgUUID(orgShortName)
if (!targetOrgUUID) {
return res.status(404).json(error.orgDnePathParam(orgShortName))
}
// Check if target user exists in target org
const targetUser = await userRepo.findOneByUsernameAndOrgShortname(username, orgShortName)
if (!targetUser) {
return res.status(404).json(error.userDne(username))
}
const isSecretariat = await orgRepo.isSecretariatByShortName(callingOrg)
const isAdmin = await userRepo.isAdmin(callingUser, callingOrg)
if (callingOrg !== orgShortName && !isSecretariat) {
return res.status(403).json(error.notSameOrgOrSecretariat())
}
if (!isSecretariat && !isAdmin) {
return res.status(403).json(error.notOrgAdminOrSecretariatUpdate())
}
// Prevent Self-Demotion
const callingUserUUID = await userRepo.getUserUUID(callingUser, callingOrg)
if (callingUserUUID === targetUser.UUID) {
return res.status(403).json({ error: 'NOT_ALLOWED_TO_SELF_DEMOTE', message: 'You cannot remove the ADMIN role from yourself.' })
}
try {
session.startTransaction()
await orgRepo.removeAdmin(orgShortName, targetUser.UUID, { session })
await session.commitTransaction()
} catch (error) {
await session.abortTransaction()
throw error
} finally {
await session.endSession()
}
logger.info({ uuid: req.ctx.uuid, message: `Role ${role} revoked from user ${username} in org ${orgShortName}` })
return res.status(200).json({ message: `Role ${role} revoked from user ${username}.` })
} catch (err) {
next(err)
}
}
module.exports = {
ALL_USERS: getAllUsers,
SINGLE_USER: getUser,
CREATE_USER: createUser,
UPDATE_USER: updateUser,
DELETE_USER: deleteUser,
GRANT_ROLE: grantRole,
REVOKE_ROLE: revokeRole
}