audit-log.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import errs from "../lib/error.js";
  2. import { castJsonIfNeed } from "../lib/helpers.js";
  3. import auditLogModel from "../models/audit-log.js";
  4. const internalAuditLog = {
  5. /**
  6. * All logs
  7. *
  8. * @param {Access} access
  9. * @param {Array} [expand]
  10. * @param {String} [searchQuery]
  11. * @returns {Promise}
  12. */
  13. getAll: async (access, expand, searchQuery) => {
  14. await access.can("auditlog:list");
  15. const query = auditLogModel
  16. .query()
  17. .orderBy("created_on", "DESC")
  18. .orderBy("id", "DESC")
  19. .limit(100)
  20. .allowGraph("[user]");
  21. // Query is used for searching
  22. if (typeof searchQuery === "string" && searchQuery.length > 0) {
  23. query.where(function () {
  24. this.where(castJsonIfNeed("meta"), "like", `%${searchQuery}`);
  25. });
  26. }
  27. if (typeof expand !== "undefined" && expand !== null) {
  28. query.withGraphFetched(`[${expand.join(", ")}]`);
  29. }
  30. return await query;
  31. },
  32. /**
  33. * This method should not be publicly used, it doesn't check certain things. It will be assumed
  34. * that permission to add to audit log is already considered, however the access token is used for
  35. * default user id determination.
  36. *
  37. * @param {Access} access
  38. * @param {Object} data
  39. * @param {String} data.action
  40. * @param {Number} [data.user_id]
  41. * @param {Number} [data.object_id]
  42. * @param {Number} [data.object_type]
  43. * @param {Object} [data.meta]
  44. * @returns {Promise}
  45. */
  46. add: async (access, data) => {
  47. if (typeof data.user_id === "undefined" || !data.user_id) {
  48. data.user_id = access.token.getUserId(1);
  49. }
  50. if (typeof data.action === "undefined" || !data.action) {
  51. throw new errs.InternalValidationError("Audit log entry must contain an Action");
  52. }
  53. // Make sure at least 1 of the IDs are set and action
  54. return await auditLogModel.query().insert({
  55. user_id: data.user_id,
  56. action: data.action,
  57. object_type: data.object_type || "",
  58. object_id: data.object_id || 0,
  59. meta: data.meta || {},
  60. });
  61. },
  62. };
  63. export default internalAuditLog;