UserAuditLogHandler.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. const OError = require('@overleaf/o-error')
  2. const { User } = require('../../models/User')
  3. const MAX_AUDIT_LOG_ENTRIES = 200
  4. /**
  5. * Add an audit log entry
  6. *
  7. * The entry should include at least the following fields:
  8. *
  9. * - userId: the user on behalf of whom the operation was performed
  10. * - operation: a string identifying the type of operation
  11. * - initiatorId: who performed the operation
  12. * - ipAddress: the IP address of the initiator
  13. * - info: an object detailing what happened
  14. */
  15. async function addEntry(userId, operation, initiatorId, ipAddress, info = {}) {
  16. if (!operation || !ipAddress)
  17. throw new OError('missing required audit log data', {
  18. operation,
  19. initiatorId,
  20. ipAddress
  21. })
  22. if (!initiatorId && operation !== 'reset-password')
  23. throw new OError('missing initiatorId for audit log', {
  24. operation,
  25. ipAddress
  26. })
  27. const timestamp = new Date()
  28. const entry = {
  29. operation,
  30. initiatorId,
  31. info,
  32. ipAddress,
  33. timestamp
  34. }
  35. const result = await User.updateOne(
  36. { _id: userId },
  37. {
  38. $push: {
  39. auditLog: { $each: [entry], $slice: -MAX_AUDIT_LOG_ENTRIES }
  40. }
  41. }
  42. ).exec()
  43. if (result.nModified === 0) {
  44. throw new OError('user not found', { userId })
  45. }
  46. }
  47. const UserAuditLogHandler = {
  48. promises: {
  49. addEntry
  50. }
  51. }
  52. module.exports = UserAuditLogHandler