-
Notifications
You must be signed in to change notification settings - Fork 122
Expand file tree
/
Copy pathaudit.controller.js
More file actions
413 lines (357 loc) · 13.8 KB
/
Copy pathaudit.controller.js
File metadata and controls
413 lines (357 loc) · 13.8 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
const mongoose = require('mongoose')
const logger = require('../../middleware/logger')
const errors = require('./error')
const error = new errors.AuditControllerError()
const validateUUID = require('uuid').validate
/**
* Create a new audit document
* Called by POST /api/audit/org/
*/
async function createAuditDocumentForOrg (req, res, next) {
try {
const session = await mongoose.startSession()
const repo = req.ctx.repositories.getAuditRepository()
const orgRepo = req.ctx.repositories.getBaseOrgRepository()
const body = req.ctx.body
let returnValue
if (body?.uuid ?? null) {
return res.status(400).json(error.uuidProvided('audit'))
}
if (!body.target_uuid) {
logger.info({ uuid: req.ctx.uuid, message: 'Missing required field: target_uuid' })
return res.status(400).json(error.missingRequiredField('target_uuid'))
}
if (!validateUUID(body.target_uuid)) {
logger.info({ uuid: req.ctx.uuid, message: 'Invalid target_uuid format' })
return res.status(400).json(error.invalidUUID('target_uuid'))
}
try {
session.startTransaction()
// Validate the audit document against the schema
const auditValidation = await repo.validateAudit(body, { session })
if (!auditValidation.isValid) {
logger.error({ uuid: req.ctx.uuid, message: 'Audit document validation FAILED' })
await session.abortTransaction()
return res.status(400).json(
error.invalidAuditObject()
)
}
// Check if audit document already exists
const exists = await repo.findOneByTargetUUID(body.target_uuid, { session })
if (exists) {
logger.info({ uuid: req.ctx.uuid, message: `Audit document was not created because one already exists for target_uuid: ${body.target_uuid}` })
await session.abortTransaction()
return res.status(400).json(error.auditExists(body.target_uuid))
}
// Check if target org exists first
const targetOrg = await orgRepo.getOrg(body.target_uuid, true, { session })
if (!targetOrg) {
logger.info({ uuid: req.ctx.uuid, message: `No organization found with UUID ${body.target_uuid}` })
await session.abortTransaction()
return res.status(404).json(error.orgDne(body.target_uuid))
}
// Validate initial history entries if provided
if (body.history && body.history.length > 0) {
for (const entry of body.history) {
if (!entry.audit_object) {
logger.info({ uuid: req.ctx.uuid, message: 'Missing audit_object in history entry' })
await session.abortTransaction()
return res.status(400).json(error.missingRequiredField('audit_object'))
}
if (!entry.change_author) {
logger.info({ uuid: req.ctx.uuid, message: 'Missing change_author in history entry' })
await session.abortTransaction()
return res.status(400).json(error.missingRequiredField('change_author'))
}
// Process entry immediately after validation
returnValue = await repo.appendToAuditHistoryForOrg(
body.target_uuid,
entry.audit_object,
entry.change_author,
{ session, upsert: true }
)
}
} else {
// Create audit document with initial empty entry or default entry
returnValue = await repo.appendToAuditHistoryForOrg(
body.target_uuid,
body.audit_object || {},
body.change_author || req.ctx.org,
{ session, upsert: true }
)
}
await session.commitTransaction()
logger.info({
uuid: req.ctx.uuid,
message: `Audit document created for target_uuid ${body.target_uuid}`,
audit_uuid: returnValue.uuid
})
} catch (err) {
console.error('REAL ERROR WAS:', err.stack); try { await session.abortTransaction() } catch (e) {}; throw err
} finally {
await session.endSession()
}
return res.status(200).json({ message: 'Audit ' + returnValue.uuid + ' was successfully created.', created: returnValue })
} catch (err) {
next(err)
}
}
/**
* Append a new entry to the audit history (Secretariat only)
* Called by PUT /api/audit/org/
* Allows for multiple appends in a single request
*/
async function appendToAuditHistoryForOrg (req, res, next) {
try {
const session = await mongoose.startSession()
const repo = req.ctx.repositories.getAuditRepository()
const orgRepo = req.ctx.repositories.getBaseOrgRepository()
const body = req.ctx.body
let returnValue
// Requiring target_uuid to validate audit_object easily.
// TODO: will need to query by uuid instead if target_uuid should be optional in the future
if (!body.target_uuid) {
logger.info({ uuid: req.ctx.uuid, message: 'Missing required field: target_uuid' })
return res.status(400).json(error.missingRequiredField('target_uuid'))
}
if (!validateUUID(body.target_uuid)) {
logger.info({ uuid: req.ctx.uuid, message: 'Invalid target_uuid format' })
return res.status(400).json(error.invalidUUID('target_uuid'))
}
try {
session.startTransaction()
// Validate the audit document against the schema
const auditValidation = await repo.validateAudit(body, { session })
if (!auditValidation.isValid) {
logger.error({ uuid: req.ctx.uuid, message: 'Audit document validation FAILED' })
await session.abortTransaction()
return res.status(400).json(
error.invalidAuditObject()
)
}
// Check if target org exists first
const targetOrg = await orgRepo.getOrg(body.target_uuid, true, { session })
if (!targetOrg) {
logger.info({ uuid: req.ctx.uuid, message: `No organization found with UUID ${body.target_uuid}` })
await session.abortTransaction()
return res.status(404).json(error.orgDne(body.target_uuid))
}
// Process each history entry
for (const entry of body.history) {
if (!entry.audit_object) {
logger.info({ uuid: req.ctx.uuid, message: 'Missing audit_object in history entry' })
await session.abortTransaction()
return res.status(400).json(error.missingRequiredField('audit_object'))
}
// Append this history entry
returnValue = await repo.appendToAuditHistoryForOrg(
body.target_uuid,
entry.audit_object,
entry.change_author,
{ session }
)
if (!returnValue) {
logger.info({ uuid: req.ctx.uuid, message: `No audit document found for target_uuid ${body.target_uuid}` })
await session.abortTransaction()
return res.status(404).json(error.auditDneByTarget(body.target_uuid))
}
}
await session.commitTransaction()
logger.info({
uuid: req.ctx.uuid,
message: `${body.history.length} audit entry(ies) appended for target_uuid ${body.target_uuid}`,
change_author: body.change_author
})
} catch (err) {
await session.abortTransaction()
throw err
} finally {
await session.endSession()
}
return res.status(200).json({
message: `${body.history.length} audit entry(ies) for ${body.target_uuid} was successfully appended.`,
updated: returnValue
})
} catch (err) {
next(err)
}
}
/**
* Get all audit documents
* Called by GET /api/audit/org/
*/
async function getAllOrgAuditDocuments (req, res, next) {
try {
const session = await mongoose.startSession()
const repo = req.ctx.repositories.getAuditRepository()
let returnValue
try {
returnValue = await repo.findAllAuditDocuments({ session })
} finally {
await session.endSession()
}
logger.info({ uuid: req.ctx.uuid, message: 'All audit documents sent to user' })
return res.status(200).json(returnValue)
} catch (err) {
next(err)
}
}
/**
* Get audit document by its document UUID
* Called by GET /api/audit/org/document/:document_uuid
*/
async function getOrgAuditByDocumentUUID (req, res, next) {
try {
const session = await mongoose.startSession()
const repo = req.ctx.repositories.getAuditRepository()
const documentUUID = req.ctx.params.document_uuid
let returnValue
if (!documentUUID) {
logger.info({ uuid: req.ctx.uuid, message: 'Missing audit uuid parameter' })
return res.status(400).json(error.missingRequiredField('document_uuid'))
}
if (!validateUUID(documentUUID)) {
logger.info({ uuid: req.ctx.uuid, message: 'Invalid document_uuid format' })
return res.status(400).json(error.invalidUUID('document_uuid'))
}
try {
returnValue = await repo.findOneByUUID(documentUUID, { session })
if (!returnValue) {
logger.info({ uuid: req.ctx.uuid, message: `No audit document found with UUID ${documentUUID}` })
return res.status(404).json(error.auditDneByDocument(documentUUID))
}
} finally {
await session.endSession()
}
logger.info({ uuid: req.ctx.uuid, message: `Audit document ${documentUUID} sent to user` })
return res.status(200).json(returnValue)
} catch (err) {
next(err)
}
}
/**
* Get audit history by target identifier (shortname or UUID)
* Called by GET /api/audit/org/:identifier
*/
async function getOrgAuditByOrgIdentifier (req, res, next) {
try {
const session = await mongoose.startSession()
const repo = req.ctx.repositories.getAuditRepository()
const orgRepo = req.ctx.repositories.getBaseOrgRepository()
const identifier = req.ctx.params.org_identifier
const identifierIsUUID = validateUUID(identifier)
let returnValue
if (!identifier) {
return res.status(400).json(error.missingRequiredField('identifier'))
}
try {
session.startTransaction()
// Find the target organization by either UUID or shortname
const targetOrg = identifierIsUUID
? await orgRepo.findOneByUUID(identifier, { session })
: await orgRepo.findOneByShortName(identifier, { session })
if (!targetOrg) {
logger.info({
uuid: req.ctx.uuid,
message: `No organization found with ${identifierIsUUID ? 'UUID' : 'shortname'} ${identifier}; returning empty audit history.`
})
await session.abortTransaction()
return res.status(200).json([])
}
// Get the org's UUID for audit lookup
const targetUUID = targetOrg.UUID
returnValue = await repo.findOneByTargetUUID(targetUUID, { session })
if (!returnValue) {
logger.info({
uuid: req.ctx.uuid,
message: `No audit history found for organization ${identifier} (UUID: ${targetUUID})`
})
await session.abortTransaction()
return res.status(404).json(error.auditDneByTarget(identifier))
}
await session.commitTransaction()
} catch (err) {
await session.abortTransaction()
throw err
} finally {
await session.endSession()
}
logger.info({
uuid: req.ctx.uuid,
message: `Audit history for ${identifierIsUUID ? 'UUID' : 'shortname'} ${identifier} sent to user ${req.ctx.user}`
})
return res.status(200).json(returnValue)
} catch (err) {
next(err)
}
}
/**
* Get last X changes for an organization
* Called by GET /api/audit/org/:target_uuid/:number_of_changes
*/
async function getLastXChanges (req, res, next) {
try {
const session = await mongoose.startSession()
const repo = req.ctx.repositories.getAuditRepository()
const orgRepo = req.ctx.repositories.getBaseOrgRepository()
const identifier = req.ctx.params.org_identifier
const identifierIsUUID = validateUUID(identifier)
const numberOfChanges = parseInt(req.ctx.params.number_of_changes)
let returnValue
if (!identifier) {
return res.status(400).json(error.missingRequiredField('identifier'))
}
if (isNaN(numberOfChanges) || numberOfChanges < 1) {
logger.info({ uuid: req.ctx.uuid, message: 'Invalid number_of_changes parameter' })
return res.status(400).json(error.invalidNumberOfChanges())
}
try {
session.startTransaction()
// Find the target organization by either UUID or shortname
const targetOrg = identifierIsUUID
? await orgRepo.findOneByUUID(identifier, { session })
: await orgRepo.findOneByShortName(identifier, { session })
if (!targetOrg) {
logger.info({
uuid: req.ctx.uuid,
message: `No organization found with ${identifierIsUUID ? 'UUID' : 'shortname'} ${identifier}`
})
await session.abortTransaction()
return res.status(404).json(error.orgDne(identifier))
}
// Get the org's UUID for audit lookup
const targetUUID = targetOrg.UUID
const lastChanges = await repo.getLastXChanges(targetUUID, numberOfChanges, { session })
if (!lastChanges || lastChanges.length === 0) {
logger.info({ uuid: req.ctx.uuid, message: `No audit history found for organization ${targetUUID}` })
await session.abortTransaction()
return res.status(404).json(error.auditDneByTarget(targetUUID))
}
returnValue = {
target_uuid: targetUUID,
changes: lastChanges
}
await session.commitTransaction()
} catch (err) {
await session.abortTransaction()
throw err
} finally {
await session.endSession()
}
logger.info({
uuid: req.ctx.uuid,
message: `Last ${numberOfChanges} changes for ${identifier} sent to user ${req.ctx.user}`
})
return res.status(200).json(returnValue)
} catch (err) {
next(err)
}
}
module.exports = {
AUDIT_CREATE_SINGLE: createAuditDocumentForOrg,
AUDIT_UPDATE: appendToAuditHistoryForOrg,
AUDIT_GET_ALL: getAllOrgAuditDocuments,
AUDIT_GET_BY_UUID: getOrgAuditByDocumentUUID,
AUDIT_GET_BY_ORG_IDENTIFIER: getOrgAuditByOrgIdentifier,
AUDIT_GET_LAST: getLastXChanges
}