-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.ts
More file actions
334 lines (287 loc) · 13.1 KB
/
index.ts
File metadata and controls
334 lines (287 loc) · 13.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
import type {
AdminForthResource,
IAdminForth,
AdminUser,
} from "adminforth";
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc.js';
import { AdminForthPlugin, AllowedActionsEnum, AdminForthSortDirections, AdminForthDataTypes, HttpExtra, ActionCheckSource, Filters, } from "adminforth";
import { PluginOptions } from "./types.js";
dayjs.extend(utc);
export default class AuditLogPlugin extends AdminForthPlugin {
options: PluginOptions;
adminforth: IAdminForth;
auditLogResource: string;
constructor(options: PluginOptions) {
super(options, import.meta.url);
this.options = options;
this.shouldHaveSingleInstancePerWholeApp = () => true;
}
instanceUniqueRepresentation(pluginOptions: any) : string {
return `single`;
}
static defaultError = 'Sorry, you do not have access to this resource.'
async getIpAndCountry(headers: Record<string, any>): Promise<{ country: string | null, clientIp: string | null }> {
let clientIp: string | null = null;
if (this.options.resourceColumns.resourceIpColumnName) {
clientIp = this.adminforth.auth.getClientIp(headers);
}
let country: string | null = null;
if (this.options.resourceColumns.resourceCountryColumnName && clientIp) {
country = await this.getClientIpCountry(headers, clientIp);
}
return { country, clientIp };
}
async getClientIpCountry(headers: Record<string, any>, clientIp: string | null): Promise<string | null> {
const headersLower = Object.keys(headers).reduce((acc: Record<string, any>, key: string) => {
acc[key.toLowerCase()] = headers[key];
return acc;
}, {});
if (this.options.isoCountryCodeRequestHeader) {
const cfCountry = headersLower[this.options.isoCountryCodeRequestHeader.toLowerCase()];
if (cfCountry && cfCountry !== 'XX') {
return cfCountry.toUpperCase();
}
}
// DB CHECK
const ipCol = this.options.resourceColumns.resourceIpColumnName;
const countryCol = this.options.resourceColumns.resourceCountryColumnName;
//TODO fix ts-ignore after release new adminforth version with proper types
//@ts-ignore
const existingLog = await this.adminforth.resource(this.auditLogResource).get(Filters.AND(Filters.EQ(ipCol, clientIp), Filters.IS_NOT_EMPTY(countryCol)));
if (existingLog) {
return existingLog[countryCol];
}
// API Request
try {
const apiUrl = `https://ipinfo.io/${clientIp}/json`;
const response = await fetch(apiUrl);
if (response.status !== 200) {
return null;
}
const data: any = await response.json();
const country = data.country;
if (country && typeof country === 'string' && country.length === 2) {
return country.toUpperCase();
}
} catch (e) {
console.error('Error fetching IP country', e);
}
return null;
}
createLogRecord = async (resource: AdminForthResource, action: AllowedActionsEnum | string, data: Object, user: AdminUser, oldRecord?: Object, extra?: HttpExtra) => {
if (user.isExternalUser) {
// audit log does not support logging for external (non-adminforth) users.
return { ok: true };
}
const recordIdFieldName = resource.columns.find((c) => c.primaryKey === true)?.name;
const recordId = data?.[recordIdFieldName] || oldRecord?.[recordIdFieldName];
const connector = this.adminforth.connectors[resource.dataSource];
const newRecord = action == AllowedActionsEnum.delete ? {} : (await connector.getRecordByPrimaryKey(resource, recordId)) || {};
if (action !== AllowedActionsEnum.delete) {
oldRecord = oldRecord ? JSON.parse(JSON.stringify(oldRecord)) : {};
} else {
oldRecord = data
}
if (action !== AllowedActionsEnum.delete) {
const columnsNamesList = resource.columns.map((c) => c.name);
columnsNamesList.forEach((key) => {
if (JSON.stringify(oldRecord[key]) == JSON.stringify(newRecord[key])) {
delete oldRecord[key];
delete newRecord[key];
}
});
}
const checks = await Promise.all(
resource.columns.map(async (c) => {
if (typeof c.backendOnly === "function") {
const result = await c.backendOnly({
adminUser: user,
resource,
meta: {},
source: ActionCheckSource.ShowRequest,
adminforth: this.adminforth,
});
return { col: c, result };
}
return { col: c, result: c.backendOnly ?? false };
})
);
const backendOnlyColumns = checks
.filter(({ result }) => result === true)
.map(({ col }) => col);
backendOnlyColumns.forEach((c) => {
if (JSON.stringify(oldRecord[c.name]) != JSON.stringify(newRecord[c.name])) {
if (action !== AllowedActionsEnum.delete) {
newRecord[c.name] = '<hidden value after>'
}
if (action !== AllowedActionsEnum.create) {
oldRecord[c.name] = '<hidden value before>'
}
} else {
delete oldRecord[c.name];
delete newRecord[c.name];
}
});
const { country, clientIp } = await this.getIpAndCountry(extra?.headers || {});
const record = {
[this.options.resourceColumns.resourceIdColumnName]: resource.resourceId,
[this.options.resourceColumns.resourceActionColumnName]: action,
[this.options.resourceColumns.resourceDataColumnName]: { 'oldRecord': oldRecord || {}, 'newRecord': newRecord },
[this.options.resourceColumns.resourceUserIdColumnName]: user.pk,
[this.options.resourceColumns.resourceRecordIdColumnName]: recordId,
// utc iso string
[this.options.resourceColumns.resourceCreatedColumnName]: dayjs.utc().format(),
...(clientIp ? {[this.options.resourceColumns.resourceIpColumnName]: clientIp} : {}),
...(country ? {[this.options.resourceColumns.resourceCountryColumnName]: country } : {}),
}
const auditLogResource = this.adminforth.config.resources.find((r) => r.resourceId === this.auditLogResource);
await this.adminforth.createResourceRecord({ resource: auditLogResource, record, adminUser: user});
return {ok: true};
}
/**
* Create a custom action in the audit log resource
* @param resourceId - The resourceId of the resource that the action is being performed on. Can be null if the action is not related to a specific resource.
* @param recordId - The recordId of the record that the action is being performed on. Can be null if the action is not related to a specific record.
* @param actionId - The id of the action being performed, can be random string
* @param data - The data to be stored in the audit log
* @param user - The adminUser user performing the action
*/
logCustomAction = async (params: {
resourceId: string | null,
recordId: string | null,
actionId: string,
oldData: Object | null,
data: Object,
user: AdminUser,
headers?: Record<string, string>
}) => {
const { resourceId, recordId, actionId, oldData, data, user, headers } = params;
if (user.isExternalUser) {
return { ok: true };
}
// if type of params is not object, throw error
if (typeof params !== 'object') {
throw new Error('params must be an object, please check AdminFoirth AuditLog custom action documentation')
}
if (resourceId) {
const resource = this.adminforth.config.resources.find((r) => r.resourceId === resourceId);
if (!resource) {
const similarResource = this.adminforth.config.resources.find((r) => r.resourceId.includes(resourceId));
throw new Error(`Resource ${resourceId} not found. Did you mean ${similarResource.resourceId}?`)
}
}
const { country, clientIp } = await this.getIpAndCountry(headers || {});
const record = {
[this.options.resourceColumns.resourceIdColumnName]: resourceId,
[this.options.resourceColumns.resourceActionColumnName]: actionId,
[this.options.resourceColumns.resourceDataColumnName]: { 'oldRecord': oldData || {}, 'newRecord': data },
[this.options.resourceColumns.resourceUserIdColumnName]: user.pk,
[this.options.resourceColumns.resourceRecordIdColumnName]: recordId,
[this.options.resourceColumns.resourceCreatedColumnName]: dayjs.utc().format(),
...(clientIp ? {[this.options.resourceColumns.resourceIpColumnName]: clientIp} : {}),
...(country ? {[this.options.resourceColumns.resourceCountryColumnName]: country } : {}),
}
const auditLogResource = this.adminforth.config.resources.find((r) => r.resourceId === this.auditLogResource);
await this.adminforth.createResourceRecord({ resource: auditLogResource, record, adminUser: user});
}
modifyResourceConfig(adminforth: IAdminForth, resourceConfig: AdminForthResource) {
super.modifyResourceConfig(adminforth, resourceConfig);
this.adminforth = adminforth;
const auditLogResourceData = this.adminforth.config.resources.find((r) => r.resourceId === resourceConfig.resourceId);
const columnToModify = auditLogResourceData.columns.find((c) => c.name === this.options.resourceColumns.resourceIdColumnName);
this.auditLogResource = resourceConfig.resourceId;
const existingResources = [];
this.adminforth.config.resources.forEach((resource) => {
existingResources.push({value: resource.resourceId, label: resource.label});
if (this.options.excludeResourceIds?.includes(resource.resourceId)) {
return;
}
resource.options = resource.options || {} as any;
if (!resource.options.actions) {
resource.options.actions = [];
}
if (resource.resourceId !== this.auditLogResource) {
const historyActionId = 'audit_log_history_btn';
if (!resource.options.actions.find((a) => a.id === historyActionId)) {
resource.options.actions.push({
id: historyActionId,
name: 'Edit History',
showIn: {
list: false,
showButton: false,
showThreeDotsMenu: true
},
action: async () => ({ ok: true }),
customComponent: {
file: this.componentPath('RelatedLogsLink.vue'),
meta: {
pluginInstanceId: this.pluginInstanceId,
auditLogResourceId: this.auditLogResource,
resourceColumns: this.options.resourceColumns,
pkName: resource.columns.find((c) => c.primaryKey)?.name || 'id',
title: 'Edit History'
}
}
});
}
}
if (this.auditLogResource === resource.resourceId) {
let diffColumn = resource.columns.find((c) => c.name === this.options.resourceColumns.resourceDataColumnName);
if (!diffColumn) {
throw new Error(`Column ${this.options.resourceColumns.resourceDataColumnName} not found in ${resource.label}`)
}
if (diffColumn.type !== AdminForthDataTypes.JSON) {
throw new Error(`Column ${this.options.resourceColumns.resourceDataColumnName} must be of type 'json'`)
}
diffColumn.showIn = {
show: true,
list: false,
edit: false,
create: false,
filter: false,
};
diffColumn.components = {
show: {
file: this.componentPath('AuditLogView.vue'),
meta: {
...this.options,
pluginInstanceId: this.pluginInstanceId
}
}
}
resource.options.defaultSort = {
columnName: this.options.resourceColumns.resourceCreatedColumnName,
direction: AdminForthSortDirections.desc
}
return;
};
resource.hooks.edit.afterSave.push(async ({ resource, updates, adminUser, oldRecord, extra }) => {
return await this.createLogRecord(resource, 'edit' as AllowedActionsEnum, updates, adminUser, oldRecord, extra)
});
resource.hooks.delete.afterSave.push(async ({ resource, record, adminUser, extra }) => {
return await this.createLogRecord(resource, 'delete' as AllowedActionsEnum, record, adminUser, record, extra)
});
resource.hooks.create.afterSave.push(async ({ resource, record, adminUser, extra }) => {
return await this.createLogRecord(resource, 'create' as AllowedActionsEnum, record, adminUser, undefined, extra)
});
if (resource.resourceId !== this.auditLogResource) {
resource.options.pageInjections = resource.options.pageInjections || {};
resource.options.pageInjections.list = resource.options.pageInjections.list || {};
if (!resource.options.pageInjections.list.threeDotsDropdownItems) {
resource.options.pageInjections.list.threeDotsDropdownItems = [];
}
(resource.options.pageInjections.list.threeDotsDropdownItems as any[]).push({
file: this.componentPath('RelatedLogsLink.vue'),
meta: {
auditLogResourceId: this.auditLogResource,
resourceColumns: this.options.resourceColumns,
pkName: resource.columns.find((c) => c.primaryKey)?.name || 'id',
title: 'Edit History'
}
});
}
})
columnToModify.enum = existingResources;
}
}