audit-log.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. const error = require('../lib/error');
  2. const auditLogModel = require('../models/audit-log');
  3. const internalAuditLog = {
  4. /**
  5. * All logs
  6. *
  7. * @param {Access} access
  8. * @param {Array} [expand]
  9. * @param {String} [search_query]
  10. * @returns {Promise}
  11. */
  12. getAll: (access, expand, search_query) => {
  13. return access.can('auditlog:list')
  14. .then(() => {
  15. let 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') {
  23. query.where(function () {
  24. this.where('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 error.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(auditLogModel
  58. .query()
  59. .insert({
  60. user_id: data.user_id,
  61. action: data.action,
  62. object_type: data.object_type || '',
  63. object_id: data.object_id || 0,
  64. meta: data.meta || {}
  65. }));
  66. }
  67. });
  68. }
  69. };
  70. module.exports = internalAuditLog;