audit-log.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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} [search_query]
  11. * @returns {Promise}
  12. */
  13. getAll: (access, expand, search_query) => {
  14. return access.can("auditlog:list").then(() => {
  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 search_query === "string" && search_query.length > 0) {
  23. query.where(function () {
  24. this.where(castJsonIfNeed("meta"), "like", `%${search_query}`);
  25. });
  26. }
  27. if (typeof expand !== "undefined" && expand !== null) {
  28. query.withGraphFetched(`[${expand.join(", ")}]`);
  29. }
  30. return query;
  31. });
  32. },
  33. /**
  34. * This method should not be publicly used, it doesn't check certain things. It will be assumed
  35. * that permission to add to audit log is already considered, however the access token is used for
  36. * default user id determination.
  37. *
  38. * @param {Access} access
  39. * @param {Object} data
  40. * @param {String} data.action
  41. * @param {Number} [data.user_id]
  42. * @param {Number} [data.object_id]
  43. * @param {Number} [data.object_type]
  44. * @param {Object} [data.meta]
  45. * @returns {Promise}
  46. */
  47. add: (access, data) => {
  48. return new Promise((resolve, reject) => {
  49. // Default the user id
  50. if (typeof data.user_id === "undefined" || !data.user_id) {
  51. data.user_id = access.token.getUserId(1);
  52. }
  53. if (typeof data.action === "undefined" || !data.action) {
  54. reject(new errs.InternalValidationError("Audit log entry must contain an Action"));
  55. } else {
  56. // Make sure at least 1 of the IDs are set and action
  57. resolve(
  58. auditLogModel.query().insert({
  59. user_id: data.user_id,
  60. action: data.action,
  61. object_type: data.object_type || "",
  62. object_id: data.object_id || 0,
  63. meta: data.meta || {},
  64. }),
  65. );
  66. }
  67. });
  68. },
  69. };
  70. export default internalAuditLog;