audit-log.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. const error = require('../lib/error');
  2. const auditLogModel = require('../models/audit-log');
  3. const {castJsonIfNeed} = require('../lib/helpers');
  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')
  15. .then(() => {
  16. let query = auditLogModel
  17. .query()
  18. .orderBy('created_on', 'DESC')
  19. .orderBy('id', 'DESC')
  20. .limit(100)
  21. .allowGraph('[user]');
  22. // Query is used for searching
  23. if (typeof search_query === 'string' && search_query.length > 0) {
  24. query.where(function () {
  25. this.where(castJsonIfNeed('meta'), 'like', '%' + search_query + '%');
  26. });
  27. }
  28. if (typeof expand !== 'undefined' && expand !== null) {
  29. query.withGraphFetched('[' + expand.join(', ') + ']');
  30. }
  31. return query;
  32. });
  33. },
  34. /**
  35. * This method should not be publicly used, it doesn't check certain things. It will be assumed
  36. * that permission to add to audit log is already considered, however the access token is used for
  37. * default user id determination.
  38. *
  39. * @param {Access} access
  40. * @param {Object} data
  41. * @param {String} data.action
  42. * @param {Number} [data.user_id]
  43. * @param {Number} [data.object_id]
  44. * @param {Number} [data.object_type]
  45. * @param {Object} [data.meta]
  46. * @returns {Promise}
  47. */
  48. add: (access, data) => {
  49. return new Promise((resolve, reject) => {
  50. // Default the user id
  51. if (typeof data.user_id === 'undefined' || !data.user_id) {
  52. data.user_id = access.token.getUserId(1);
  53. }
  54. if (typeof data.action === 'undefined' || !data.action) {
  55. reject(new error.InternalValidationError('Audit log entry must contain an Action'));
  56. } else {
  57. // Make sure at least 1 of the IDs are set and action
  58. resolve(auditLogModel
  59. .query()
  60. .insert({
  61. user_id: data.user_id,
  62. action: data.action,
  63. object_type: data.object_type || '',
  64. object_id: data.object_id || 0,
  65. meta: data.meta || {}
  66. }));
  67. }
  68. });
  69. }
  70. };
  71. module.exports = internalAuditLog;