@autofleet/shtinker 1.2.1-beta → 1.2.2-beta

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@autofleet/shtinker",
3
- "version": "1.2.1-beta",
3
+ "version": "1.2.2-beta",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
@@ -9,12 +9,6 @@ import logger from './logger';
9
9
 
10
10
  const CUSTOM_FIELDS_PROPERTY = 'customFields';
11
11
 
12
- const getAuditContext = () => {
13
- const currentTrace = getCurrentTrace();
14
- const auditContext = currentTrace?.context?.get(AUDIT_LOG_CONTEXT_KEY);
15
- return auditContext;
16
- };
17
-
18
12
  const isEmpty = (field) => {
19
13
  if ([null, undefined].includes(field)) {
20
14
  return true;
@@ -80,8 +74,11 @@ class AuditLogger {
80
74
  Object.entries(this.sequelize.models).forEach(([modelName, modelType]) => {
81
75
  modelType.addHook('afterSave', async (instance: any, options: any) => {
82
76
  try {
83
- const auditContext = getAuditContext();
77
+ const currentTrace = getCurrentTrace();
78
+ const auditContext = currentTrace?.context?.get(AUDIT_LOG_CONTEXT_KEY);
84
79
  if (auditContext) {
80
+ auditContext.entityId = instance.id;
81
+ currentTrace.context.set(AUDIT_LOG_CONTEXT_KEY, auditContext);
85
82
  const changedFieldsRows = getChangedFieldsRows(instance, options);
86
83
  const changedCustomFieldsRows = getChangedCustomFieldsRows(instance);
87
84
  const payload: AuditLogPayload = {
package/src/index.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { getCurrentPayload as getCurrentTrace } from '@autofleet/zehut';
2
+ import { Request, Response, NextFunction } from 'express';
2
3
  import AuditLogger from './audit-logger';
3
4
  import { ActionOrigin, AuditLogContext, AuditLoggerOptions } from './types';
4
5
  import { AUDIT_LOG_CONTEXT_KEY, AUTOMATION_ID_HEADER, USER_CONTEXT_KEY } from './const';
@@ -18,29 +19,36 @@ export const enableAuditing = (options: AuditLoggerOptions) => {
18
19
  export const setAuditContext = (
19
20
  entityType: string,
20
21
  action: string,
21
- ) => async (req: any, res: any, next: any): Promise<any> => {
22
+ ) => async (req: Request, res: Response, next: NextFunction): Promise<any> => {
22
23
  try {
23
- if (process.env.DISABLE_AUDIT_LOGS === 'true') {
24
- return next();
25
- }
26
- logger.info('shtinker automation context', { contextData: req.headers[AUTOMATION_ID_HEADER] });
27
24
  const currentTrace = getCurrentTrace();
28
- if (currentTrace && currentTrace.context && currentTrace.context.get) {
29
- const user = currentTrace.context.get(USER_CONTEXT_KEY);
30
- const { performedBy, actionOrigin } = user?.id
31
- ? { performedBy: user.id, actionOrigin: ActionOrigin.USER }
32
- : { performedBy: req.headers[AUTOMATION_ID_HEADER] ?? null, actionOrigin: req.headers[AUTOMATION_ID_HEADER] ? ActionOrigin.AUTOMATION : null };
33
- const auditLogContext: AuditLogContext = {
34
- entityType,
35
- action,
36
- endpoint: req.url,
37
- method: req.method,
38
- performedBy,
39
- actionOrigin,
40
- };
41
- currentTrace.context.set(AUDIT_LOG_CONTEXT_KEY, auditLogContext);
42
- await auditLogger.sendAuditLogContext(auditLogContext);
25
+ if (process.env.DISABLE_AUDIT_LOGS === 'true' || !currentTrace?.context?.get) {
26
+ return next();
43
27
  }
28
+ const user = currentTrace.context.get?.(USER_CONTEXT_KEY);
29
+ const { performedBy, actionOrigin } = user?.id
30
+ ? { performedBy: user.id, actionOrigin: ActionOrigin.USER }
31
+ : { performedBy: req.headers[AUTOMATION_ID_HEADER] ?? null, actionOrigin: req.headers[AUTOMATION_ID_HEADER] ? ActionOrigin.AUTOMATION : null };
32
+ const auditLogContext: AuditLogContext = {
33
+ entityType,
34
+ action,
35
+ endpoint: req.url,
36
+ method: req.method,
37
+ performedBy,
38
+ actionOrigin,
39
+ };
40
+
41
+ currentTrace.context.set(AUDIT_LOG_CONTEXT_KEY, auditLogContext);
42
+ const sendAuditLogContextEvent = async () => {
43
+ try {
44
+ await auditLogger.sendAuditLogContext(auditLogContext);
45
+ } finally {
46
+ req.removeListener('end', sendAuditLogContextEvent);
47
+ req.removeListener('error', sendAuditLogContextEvent);
48
+ }
49
+ };
50
+ req.once('end', sendAuditLogContextEvent);
51
+ req.once('error', sendAuditLogContextEvent);
44
52
  } catch (err) {
45
53
  logger.error('coudln\'t set audit context', err);
46
54
  }
package/src/types.ts CHANGED
@@ -10,6 +10,7 @@ export type AuditLoggerOptions = {
10
10
 
11
11
  export interface AuditLogContext {
12
12
  entityType: string;
13
+ entityId?: string;
13
14
  action: string;
14
15
  performedBy: string;
15
16
  endpoint: string;
@@ -1,6 +0,0 @@
1
- import { Router } from 'express';
2
- declare const _default: ({ router, entiyScopedModelMap, }: {
3
- router: Router;
4
- entiyScopedModelMap: Array<any>;
5
- }) => Promise<void>;
6
- export default _default;
package/dist/audit-api.js DELETED
@@ -1,36 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- const errors_1 = require("@autofleet/errors");
16
- const audit_ms_1 = __importDefault(require("./audit-ms"));
17
- exports.default = ({ router, entiyScopedModelMap, }) => __awaiter(void 0, void 0, void 0, function* () {
18
- if (entiyScopedModelMap) {
19
- Object.entries(entiyScopedModelMap).forEach(([entity, ScopedModel]) => {
20
- router.get(`${entity}/:id/audit`, (req, res) => __awaiter(void 0, void 0, void 0, function* () {
21
- try {
22
- const { id } = req.params;
23
- const entityData = yield ScopedModel.findByPk(id);
24
- if (!entityData) {
25
- return (0, errors_1.handleError)(new errors_1.ResourceNotFoundError(), res);
26
- }
27
- const auditData = audit_ms_1.default.getByEntityId(id);
28
- return res.json(auditData);
29
- }
30
- catch (err) {
31
- return (0, errors_1.handleError)(new errors_1.UnexpectedError(err), res);
32
- }
33
- }));
34
- });
35
- }
36
- });
@@ -1,11 +0,0 @@
1
- import { AuditLogPayload, AuditLoggerOptions, AuditLogContext } from './types';
2
- declare class AuditLogger {
3
- private rabbit;
4
- private sequelize;
5
- private logger;
6
- constructor(options: AuditLoggerOptions);
7
- registerHooks(): void;
8
- sendAuditLogContext(context: AuditLogContext): Promise<void>;
9
- sendAuditLogRows(payload: AuditLogPayload): Promise<void>;
10
- }
11
- export default AuditLogger;
@@ -1,95 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- const zehut_1 = require("@autofleet/zehut");
16
- const const_1 = require("./const");
17
- const logger_1 = __importDefault(require("./logger"));
18
- const getAuditContext = () => {
19
- var _a;
20
- const currentTrace = (0, zehut_1.getCurrentPayload)();
21
- const auditContext = (_a = currentTrace === null || currentTrace === void 0 ? void 0 : currentTrace.context) === null || _a === void 0 ? void 0 : _a.get(const_1.AUDIT_LOG_CONTEXT_KEY);
22
- return auditContext;
23
- };
24
- const isEmpty = (field) => {
25
- if ([null, undefined].includes(field)) {
26
- return true;
27
- }
28
- if (Array.isArray(field)) {
29
- return field.length === 0;
30
- }
31
- if (typeof field === 'object' && !(field instanceof Date)) {
32
- return Object.keys(field).length === 0;
33
- }
34
- return false;
35
- };
36
- const filterOutEmptyFields = (fields, instance) => fields.filter((field) => !isEmpty(instance.get(field)) || !isEmpty(instance.previous(field)));
37
- const getChangedFields = (instance, options) => {
38
- // When bulk updating in sequelize using the "returning" option, the instance.changed() stops working.
39
- // It's a known issut with sequelize.
40
- const changedProperties = options.returning ? options.fields : instance.changed();
41
- return filterOutEmptyFields(changedProperties, instance);
42
- };
43
- class AuditLogger {
44
- constructor(options) {
45
- this.rabbit = options.rabbit;
46
- this.sequelize = options.sequelize;
47
- this.logger = options.logger;
48
- }
49
- registerHooks() {
50
- Object.entries(this.sequelize.models).forEach(([modelName, modelType]) => {
51
- modelType.addHook('afterSave', (instance, options) => __awaiter(this, void 0, void 0, function* () {
52
- try {
53
- const auditContext = getAuditContext();
54
- if (auditContext) {
55
- const changedProperties = getChangedFields(instance, options);
56
- const payload = {
57
- entityType: modelName,
58
- entityId: instance.id,
59
- rows: changedProperties.map((property) => ({
60
- property,
61
- previousValue: instance.previous(property),
62
- newValue: instance.get(property),
63
- })),
64
- };
65
- this.sendAuditLogRows(payload);
66
- }
67
- }
68
- catch (error) {
69
- logger_1.default.error('Failed to send audit log rows', error);
70
- }
71
- }));
72
- });
73
- }
74
- sendAuditLogContext(context) {
75
- return __awaiter(this, void 0, void 0, function* () {
76
- try {
77
- yield this.rabbit.sendToQueue(const_1.AUDIT_LOG_CONTEXT_QUEUE, context);
78
- }
79
- catch (err) {
80
- logger_1.default.error('Failed to send audit log context', err);
81
- }
82
- });
83
- }
84
- sendAuditLogRows(payload) {
85
- return __awaiter(this, void 0, void 0, function* () {
86
- try {
87
- yield this.rabbit.sendToQueue(const_1.AUDIT_LOG_ROWS_QUEUE, payload);
88
- }
89
- catch (err) {
90
- logger_1.default.error('Failed to send audit log rows', err);
91
- }
92
- });
93
- }
94
- }
95
- exports.default = AuditLogger;
@@ -1,4 +0,0 @@
1
- declare const _default: {
2
- getByEntityId: (entityId: string) => any;
3
- };
4
- export default _default;
package/dist/audit-ms.js DELETED
@@ -1,14 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const network_1 = __importDefault(require("@autofleet/network"));
7
- const auditMs = new network_1.default({ serviceName: 'AUDIT_MS', timeout: 1000 * 60 });
8
- const getByEntityId = (entityId) => {
9
- const { data } = auditMs.get(`api/v1/audit-logs/${entityId}`);
10
- return data;
11
- };
12
- exports.default = {
13
- getByEntityId,
14
- };
package/dist/const.d.ts DELETED
@@ -1,4 +0,0 @@
1
- export declare const AUDIT_LOG_CONTEXT_QUEUE = "audit-log-context";
2
- export declare const AUDIT_LOG_ROWS_QUEUE = "audit-log-rows";
3
- export declare const AUDIT_LOG_CONTEXT_KEY = "auditLogContext";
4
- export declare const USER_CONTEXT_KEY = "userObject";
package/dist/const.js DELETED
@@ -1,7 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.USER_CONTEXT_KEY = exports.AUDIT_LOG_CONTEXT_KEY = exports.AUDIT_LOG_ROWS_QUEUE = exports.AUDIT_LOG_CONTEXT_QUEUE = void 0;
4
- exports.AUDIT_LOG_CONTEXT_QUEUE = 'audit-log-context';
5
- exports.AUDIT_LOG_ROWS_QUEUE = 'audit-log-rows';
6
- exports.AUDIT_LOG_CONTEXT_KEY = 'auditLogContext';
7
- exports.USER_CONTEXT_KEY = 'userObject';
package/dist/index.d.ts DELETED
@@ -1,11 +0,0 @@
1
- import AuditLogger from './audit-logger';
2
- import { AuditLoggerOptions } from './types';
3
- export declare const enableAuditing: (options: AuditLoggerOptions) => void;
4
- export declare const setAuditContext: (entityType: string, action: string) => (req: any, res: any, next: any) => Promise<any>;
5
- export declare const setRabbitAuditContext: (entityType: string, action: string) => (endpoint: string, { userId, automationId }: {
6
- userId: any;
7
- automationId: any;
8
- }) => Promise<any>;
9
- export * from './types';
10
- export * from './const';
11
- export default AuditLogger;
package/dist/index.js DELETED
@@ -1,91 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
17
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
18
- return new (P || (P = Promise))(function (resolve, reject) {
19
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
20
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
21
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
22
- step((generator = generator.apply(thisArg, _arguments || [])).next());
23
- });
24
- };
25
- var __importDefault = (this && this.__importDefault) || function (mod) {
26
- return (mod && mod.__esModule) ? mod : { "default": mod };
27
- };
28
- Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.setRabbitAuditContext = exports.setAuditContext = exports.enableAuditing = void 0;
30
- const zehut_1 = require("@autofleet/zehut");
31
- const audit_logger_1 = __importDefault(require("./audit-logger"));
32
- const types_1 = require("./types");
33
- const const_1 = require("./const");
34
- const audit_api_1 = __importDefault(require("./audit-api"));
35
- const logger_1 = __importDefault(require("./logger"));
36
- let auditLogger;
37
- const enableAuditing = (options) => {
38
- auditLogger = new audit_logger_1.default(options);
39
- (0, audit_api_1.default)(options);
40
- auditLogger.registerHooks();
41
- };
42
- exports.enableAuditing = enableAuditing;
43
- const setAuditContext = (entityType, action) => (req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
44
- try {
45
- const currentTrace = (0, zehut_1.getCurrentPayload)();
46
- if (currentTrace && currentTrace.context && currentTrace.context.get) {
47
- const user = currentTrace.context.get(const_1.USER_CONTEXT_KEY);
48
- const { performedBy, actionOrigin } = (user === null || user === void 0 ? void 0 : user.id)
49
- ? { performedBy: user.id, actionOrigin: types_1.ActionOrigin.USER }
50
- : { performedBy: req.headers['x-af-automation-id'], actionOrigin: types_1.ActionOrigin.AUTOMATION };
51
- const auditLogContext = {
52
- entityType,
53
- action,
54
- endpoint: req.url,
55
- method: req.method,
56
- performedBy,
57
- actionOrigin,
58
- };
59
- currentTrace.context.set(const_1.AUDIT_LOG_CONTEXT_KEY, auditLogContext);
60
- yield auditLogger.sendAuditLogContext(auditLogContext);
61
- }
62
- }
63
- catch (err) {
64
- logger_1.default.error('coudln\'t set audit context', err);
65
- }
66
- return next();
67
- });
68
- exports.setAuditContext = setAuditContext;
69
- const setRabbitAuditContext = (entityType, action) => (endpoint, { userId, automationId }) => __awaiter(void 0, void 0, void 0, function* () {
70
- var _a;
71
- console.log({ automationId });
72
- const currentTrace = (0, zehut_1.getCurrentPayload)();
73
- const user = currentTrace.context.get(const_1.USER_CONTEXT_KEY);
74
- const contextAutomationId = currentTrace.context.get('x-af-automation-id');
75
- if ((_a = currentTrace === null || currentTrace === void 0 ? void 0 : currentTrace.context) === null || _a === void 0 ? void 0 : _a.get) {
76
- const auditLogContext = {
77
- entityType,
78
- action,
79
- endpoint,
80
- method: 'rabbit',
81
- performedBy: (user === null || user === void 0 ? void 0 : user.id) || contextAutomationId,
82
- actionOrigin: userId ? types_1.ActionOrigin.USER : types_1.ActionOrigin.AUTOMATION,
83
- };
84
- currentTrace.context.set(const_1.AUDIT_LOG_CONTEXT_KEY, auditLogContext);
85
- yield auditLogger.sendAuditLogContext(auditLogContext);
86
- }
87
- });
88
- exports.setRabbitAuditContext = setRabbitAuditContext;
89
- __exportStar(require("./types"), exports);
90
- __exportStar(require("./const"), exports);
91
- exports.default = audit_logger_1.default;
package/dist/logger.d.ts DELETED
@@ -1,2 +0,0 @@
1
- declare const _default: import("@autofleet/logger").LoggerInstanceManager;
2
- export default _default;
package/dist/logger.js DELETED
@@ -1,7 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const logger_1 = __importDefault(require("@autofleet/logger"));
7
- exports.default = (0, logger_1.default)(null);
package/dist/types.d.ts DELETED
@@ -1,53 +0,0 @@
1
- import { Sequelize } from 'sequelize-typescript';
2
- import RabbitMq from '@autofleet/rabbit';
3
- export type AuditLoggerOptions = {
4
- rabbit: RabbitMq;
5
- sequelize: Sequelize;
6
- logger: any;
7
- };
8
- export interface AuditLogContext {
9
- entityType: string;
10
- action: string;
11
- performedBy: string;
12
- endpoint: string;
13
- method: string;
14
- actionOrigin?: string;
15
- }
16
- export interface AuditLogRow {
17
- property: string;
18
- previousValue: any;
19
- newValue: any;
20
- }
21
- export interface AuditLogPayload {
22
- entityType: string;
23
- entityId: string;
24
- rows: AuditLogRow[];
25
- }
26
- export declare enum Action {
27
- CREATE = "create",
28
- BULK_CREATE = "bulk-create",
29
- BULK_EDIT = "bulk-edit",
30
- DELETE = "delete",
31
- UPDATE = "update",
32
- CANCEL = "cancel",
33
- FAIL = "fail",
34
- UNASSIGN = "unassign",
35
- BULK_ASSIGN = "bulk-assign",
36
- REASSIGN = "reassign",
37
- DISPATCH = "dispatch",
38
- BULK_DISPATCH = "bulk-dispatch",
39
- BULK_UPSERT = "bulk-upsert",
40
- UPSERT = "upsert",
41
- JOIN = "join",
42
- MOVE = "move"
43
- }
44
- export declare enum EntityType {
45
- RIDE = "Ride",
46
- VEHICLE = "Vehicle",
47
- DRIVER = "Driver",
48
- PRICE_CALCULATION = "PriceCalculation"
49
- }
50
- export declare enum ActionOrigin {
51
- USER = "user",
52
- AUTOMATION = "automation"
53
- }
package/dist/types.js DELETED
@@ -1,34 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ActionOrigin = exports.EntityType = exports.Action = void 0;
4
- var Action;
5
- (function (Action) {
6
- Action["CREATE"] = "create";
7
- Action["BULK_CREATE"] = "bulk-create";
8
- Action["BULK_EDIT"] = "bulk-edit";
9
- Action["DELETE"] = "delete";
10
- Action["UPDATE"] = "update";
11
- Action["CANCEL"] = "cancel";
12
- Action["FAIL"] = "fail";
13
- Action["UNASSIGN"] = "unassign";
14
- Action["BULK_ASSIGN"] = "bulk-assign";
15
- Action["REASSIGN"] = "reassign";
16
- Action["DISPATCH"] = "dispatch";
17
- Action["BULK_DISPATCH"] = "bulk-dispatch";
18
- Action["BULK_UPSERT"] = "bulk-upsert";
19
- Action["UPSERT"] = "upsert";
20
- Action["JOIN"] = "join";
21
- Action["MOVE"] = "move";
22
- })(Action = exports.Action || (exports.Action = {}));
23
- var EntityType;
24
- (function (EntityType) {
25
- EntityType["RIDE"] = "Ride";
26
- EntityType["VEHICLE"] = "Vehicle";
27
- EntityType["DRIVER"] = "Driver";
28
- EntityType["PRICE_CALCULATION"] = "PriceCalculation";
29
- })(EntityType = exports.EntityType || (exports.EntityType = {}));
30
- var ActionOrigin;
31
- (function (ActionOrigin) {
32
- ActionOrigin["USER"] = "user";
33
- ActionOrigin["AUTOMATION"] = "automation";
34
- })(ActionOrigin = exports.ActionOrigin || (exports.ActionOrigin = {}));