adminforth 1.1.107 → 1.2.2

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/dist/index.js CHANGED
@@ -18,14 +18,12 @@ import MongoConnector from './dataConnectors/mongo.js';
18
18
  import PostgresConnector from './dataConnectors/postgres.js';
19
19
  import SQLiteConnector from './dataConnectors/sqlite.js';
20
20
  import CodeInjector from './modules/codeInjector.js';
21
- import { guessLabelFromName } from './modules/utils.js';
22
21
  import ExpressServer from './servers/express.js';
23
- import { v1 as uuid } from 'uuid';
24
- import fs from 'fs';
25
22
  import { ADMINFORTH_VERSION, listify } from './modules/utils.js';
26
- import { AdminForthFilterOperators, AdminForthDataTypes, AdminForthResourcePages, AllowedActionsEnum, ActionCheckSource } from './types/AdminForthConfig.js';
27
- import path from 'path';
23
+ import { AdminForthFilterOperators, AdminForthDataTypes, AdminForthResourcePages } from './types/AdminForthConfig.js';
28
24
  import AdminForthPlugin from './basePlugin.js';
25
+ import ConfigValidator from './modules/configValidator.js';
26
+ import AdminForthRestAPI from './modules/restApi.js';
29
27
  //get array from enum AdminForthResourcePages
30
28
  export { AdminForthPlugin };
31
29
  class AdminForth {
@@ -35,14 +33,18 @@ class AdminForth {
35
33
  });
36
34
  this.config = Object.assign(Object.assign({}, __classPrivateFieldGet(this, _AdminForth_defaultConfig, "f")), config);
37
35
  this.codeInjector = new CodeInjector(this);
36
+ this.configValidator = new ConfigValidator(this, this.config);
37
+ this.restApi = new AdminForthRestAPI(this);
38
38
  this.activatedPlugins = [];
39
- this.validateConfig();
39
+ this.configValidator.validateConfig();
40
40
  this.activatePlugins();
41
- this.validateConfig(); // revalidate after plugins
41
+ this.configValidator.validateConfig(); // revalidate after plugins
42
42
  this.express = new ExpressServer(this);
43
43
  this.auth = new AdminForthAuth(this);
44
44
  this.connectors = {};
45
- this.statuses = {};
45
+ this.statuses = {
46
+ dbDiscover: 'running',
47
+ };
46
48
  console.log(`🚀 AdminForth v${ADMINFORTH_VERSION} starting up`);
47
49
  }
48
50
  activatePlugins() {
@@ -54,392 +56,6 @@ class AdminForth {
54
56
  }
55
57
  ;
56
58
  }
57
- checkCustomFileExists(filePath) {
58
- if (filePath.startsWith('@@/')) {
59
- const checkPath = path.join(this.config.customization.customComponentsDir, filePath.replace('@@/', ''));
60
- if (!fs.existsSync(checkPath)) {
61
- return [`File file ${filePath} does not exist in ${this.config.customization.customComponentsDir}`];
62
- }
63
- }
64
- return [];
65
- }
66
- validateComponent(component, errors, ignoreExistsCheck = false) {
67
- if (!component) {
68
- return component;
69
- }
70
- let obj;
71
- if (typeof component === 'string') {
72
- obj = { file: component, meta: {} };
73
- }
74
- else {
75
- obj = component;
76
- }
77
- if (!ignoreExistsCheck) {
78
- errors.push(...this.checkCustomFileExists(obj.file));
79
- }
80
- return obj;
81
- }
82
- validateConfig() {
83
- var _b;
84
- const errors = [];
85
- if (this.config.rootUser) {
86
- if (!this.config.rootUser.username) {
87
- throw new Error('rootUser.username is required');
88
- }
89
- if (!this.config.rootUser.password) {
90
- throw new Error('rootUser.password is required');
91
- }
92
- console.log('\n ⚠️⚠️⚠️ [INSECURE ALERT] config.rootUser is set, please create a new user and remove config.rootUser from config ASAP when you are in production\n');
93
- }
94
- if (!this.config.customization.customComponentsDir) {
95
- this.config.customization.customComponentsDir = './custom';
96
- }
97
- try {
98
- // check customComponentsDir exists
99
- fs.accessSync(this.config.customization.customComponentsDir, fs.constants.R_OK);
100
- }
101
- catch (e) {
102
- this.config.customization.customComponentsDir = undefined;
103
- }
104
- if (!this.config.auth) {
105
- if (!this.config.auth.resourceId) {
106
- throw new Error('No config.auth.resourceId defined');
107
- }
108
- if (!this.config.auth.passwordHashField) {
109
- throw new Error('No config.auth.passwordHashField defined');
110
- }
111
- if (!this.config.auth.usernameField) {
112
- throw new Error('No config.auth.usernameField defined');
113
- }
114
- if (this.config.auth.loginBackgroundImage) {
115
- errors.push(...this.checkCustomFileExists(this.config.auth.loginBackgroundImage));
116
- }
117
- const userResource = this.config.resources.find((res) => res.resourceId === this.config.auth.resourceId);
118
- if (!userResource) {
119
- throw new Error(`Resource with id "${this.config.auth.resourceId}" not found`);
120
- }
121
- if (!this.config.auth.beforeLoginConfirmation) {
122
- this.config.auth.beforeLoginConfirmation = [];
123
- }
124
- }
125
- if (!this.config.customization) {
126
- this.config.customization = {};
127
- }
128
- if (!this.config.customization.customComponentsDir) {
129
- this.config.customization.customComponentsDir = './custom';
130
- }
131
- try {
132
- // check customComponentsDir exists
133
- fs.accessSync(this.config.customization.customComponentsDir, fs.constants.R_OK);
134
- }
135
- catch (e) {
136
- this.config.customization.customComponentsDir = undefined;
137
- }
138
- if (this.config.customization.customPages) {
139
- this.config.customization.customPages.forEach((page, i) => {
140
- // validate component if it's not plugin injection
141
- if (this.codeInjector.allComponentNames.hasOwnProperty(page.component)) {
142
- const validatedPage = this.validateComponent(page.component, errors, true);
143
- }
144
- });
145
- }
146
- else {
147
- this.config.customization.customPages = [];
148
- }
149
- if (!this.config.baseUrl) {
150
- this.config.baseUrl = '';
151
- }
152
- if (!this.config.baseUrl.endsWith('/')) {
153
- this.baseUrlSlashed = this.config.baseUrl + '/';
154
- }
155
- else {
156
- this.baseUrlSlashed = this.config.baseUrl;
157
- }
158
- if (((_b = this.config) === null || _b === void 0 ? void 0 : _b.customization.brandName) === undefined) {
159
- this.config.customization.brandName = 'AdminForth';
160
- }
161
- if (this.config.customization.brandLogo) {
162
- errors.push(...this.checkCustomFileExists(this.config.customization.brandLogo));
163
- }
164
- if (this.config.customization.favicon) {
165
- errors.push(...this.checkCustomFileExists(this.config.customization.favicon));
166
- }
167
- if (!this.config.customization.datesFormat) {
168
- this.config.customization.datesFormat = 'MMM D, YYYY HH:mm:ss';
169
- }
170
- if (this.config.resources) {
171
- this.config.resources.forEach((res) => {
172
- var _b, _c, _d;
173
- if (!res.table) {
174
- errors.push(`Resource "${res.dataSource}" is missing table`);
175
- }
176
- // if recordLabel is not callable, throw error
177
- if (res.recordLabel && typeof res.recordLabel !== 'function') {
178
- errors.push(`Resource "${res.dataSource}" recordLabel is not a function`);
179
- }
180
- if (!res.recordLabel) {
181
- res.recordLabel = (item) => {
182
- const pkVal = item[res.columns.find((col) => col.primaryKey).name];
183
- return `${res.label} ${pkVal}`;
184
- };
185
- }
186
- res.resourceId = res.resourceId || res.table;
187
- res.label = res.label || res.table.charAt(0).toUpperCase() + res.table.slice(1);
188
- if (!res.dataSource) {
189
- errors.push(`Resource "${res.resourceId}" is missing dataSource`);
190
- }
191
- if (!res.columns) {
192
- res.columns = [];
193
- }
194
- res.columns.forEach((col) => {
195
- var _b, _c, _d, _e;
196
- col.label = col.label || guessLabelFromName(col.name);
197
- //define default sortable
198
- if (!Object.keys(col).includes('sortable')) {
199
- col.sortable = true;
200
- }
201
- if (col.showIn && !Array.isArray(col.showIn)) {
202
- errors.push(`Resource "${res.resourceId}" column "${col.name}" showIn must be an array`);
203
- }
204
- // check col.required is string or object
205
- if (col.required && !((typeof col.required === 'boolean') || (typeof col.required === 'object'))) {
206
- errors.push(`Resource "${res.resourceId}" column "${col.name}" required must be a string or object`);
207
- }
208
- // if it is object check the keys are one of ['create', 'edit']
209
- if (typeof col.required === 'object') {
210
- const wrongRequiredOn = Object.keys(col.required).find((c) => !['create', 'edit'].includes(c));
211
- if (wrongRequiredOn) {
212
- errors.push(`Resource "${res.resourceId}" column "${col.name}" has invalid required value "${wrongRequiredOn}", allowed keys are 'create', 'edit']`);
213
- }
214
- }
215
- // same for editingNote
216
- if (col.editingNote && !((typeof col.editingNote === 'string') || (typeof col.editingNote === 'object'))) {
217
- errors.push(`Resource "${res.resourceId}" column "${col.name}" editingNote must be a string or object`);
218
- }
219
- if (typeof col.editingNote === 'object') {
220
- const wrongEditingNoteOn = Object.keys(col.editingNote).find((c) => !['create', 'edit'].includes(c));
221
- if (wrongEditingNoteOn) {
222
- errors.push(`Resource "${res.resourceId}" column "${col.name}" has invalid editingNote value "${wrongEditingNoteOn}", allowed keys are 'create', 'edit']`);
223
- }
224
- }
225
- const wrongShowIn = col.showIn && col.showIn.find((c) => AdminForthResourcePages[c] === undefined);
226
- if (wrongShowIn) {
227
- errors.push(`Resource "${res.resourceId}" column "${col.name}" has invalid showIn value "${wrongShowIn}", allowed values are ${Object.keys(AdminForthResourcePages).join(', ')}`);
228
- }
229
- col.showIn = col.showIn || Object.values(AdminForthResourcePages);
230
- if (col.foreignResource) {
231
- const befHook = (_c = (_b = col.foreignResource.hooks) === null || _b === void 0 ? void 0 : _b.dropdownList) === null || _c === void 0 ? void 0 : _c.beforeDatasourceRequest;
232
- if (befHook) {
233
- if (!Array.isArray(befHook)) {
234
- col.foreignResource.hooks.dropdownList.beforeDatasourceRequest = [befHook];
235
- }
236
- }
237
- const aftHook = (_e = (_d = col.foreignResource.hooks) === null || _d === void 0 ? void 0 : _d.dropdownList) === null || _e === void 0 ? void 0 : _e.afterDatasourceResponse;
238
- if (aftHook) {
239
- if (!Array.isArray(aftHook)) {
240
- col.foreignResource.hooks.dropdownList.afterDatasourceResponse = [aftHook];
241
- }
242
- }
243
- }
244
- });
245
- if (!res.options) {
246
- res.options = { bulkActions: [], allowedActions: {} };
247
- }
248
- if (!res.options.allowedActions) {
249
- res.options.allowedActions = {
250
- all: true,
251
- };
252
- }
253
- if (Object.keys(res.options.allowedActions).includes('all')) {
254
- if (Object.keys(res.options.allowedActions).length > 1) {
255
- errors.push(`Resource "${res.resourceId}" allowedActions cannot have "all" and other keys at same time: ${Object.keys(res.options.allowedActions).join(', ')}`);
256
- }
257
- for (const key of Object.keys(AllowedActionsEnum)) {
258
- if (key !== 'all') {
259
- res.options.allowedActions[key] = res.options.allowedActions.all;
260
- }
261
- }
262
- delete res.options.allowedActions.all;
263
- }
264
- else {
265
- // by default allow all actions
266
- for (const key of Object.keys(AllowedActionsEnum)) {
267
- if (!Object.keys(res.options.allowedActions).includes(key)) {
268
- res.options.allowedActions[key] = true;
269
- }
270
- }
271
- }
272
- //check if resource has bulkActions
273
- let bulkActions = ((_b = res === null || res === void 0 ? void 0 : res.options) === null || _b === void 0 ? void 0 : _b.bulkActions) || [];
274
- if (!Array.isArray(bulkActions)) {
275
- errors.push(`Resource "${res.resourceId}" bulkActions must be an array`);
276
- bulkActions = [];
277
- }
278
- if (((_d = (_c = res.options) === null || _c === void 0 ? void 0 : _c.allowedActions) === null || _d === void 0 ? void 0 : _d.delete) && !bulkActions.find((action) => action.label === 'Delete checked')) {
279
- bulkActions.push({
280
- label: `Delete checked`,
281
- state: 'danger',
282
- icon: 'flowbite:trash-bin-outline',
283
- action: (_e) => __awaiter(this, [_e], void 0, function* ({ selectedIds }) {
284
- const connector = this.connectors[res.dataSource];
285
- yield Promise.all(selectedIds.map((recordId) => __awaiter(this, void 0, void 0, function* () {
286
- yield connector.deleteRecord({ resource: res, recordId });
287
- })));
288
- })
289
- });
290
- }
291
- const newBulkActions = bulkActions.map((action) => {
292
- return Object.assign(action, { id: uuid() });
293
- });
294
- res.options.bulkActions = newBulkActions;
295
- // if pageInjection is a string, make array with one element. Also check file exists
296
- const possibleInjections = ['beforeBreadcrumbs', 'afterBreadcrumbs', 'bottom'];
297
- if (res.options.pageInjections) {
298
- Object.entries(res.options.pageInjections).map(([key, value]) => {
299
- Object.entries(value).map(([injection, target]) => {
300
- if (possibleInjections.includes(injection)) {
301
- if (!Array.isArray(res.options.pageInjections[key][injection])) {
302
- // not array
303
- res.options.pageInjections[key][injection] = [target];
304
- }
305
- res.options.pageInjections[key][injection].forEach((target, i) => {
306
- res.options.pageInjections[key][injection][i] = this.validateComponent(target, errors);
307
- });
308
- }
309
- else {
310
- errors.push(`Resource "${res.resourceId}" has invalid pageInjection key "${injection}", Supported keys are ${possibleInjections.join(', ')}`);
311
- }
312
- });
313
- });
314
- }
315
- // transform all hooks Functions to array of functions
316
- if (!res.hooks) {
317
- res.hooks = {};
318
- }
319
- for (const hookName of ['show', 'list']) {
320
- if (!res.hooks[hookName]) {
321
- res.hooks[hookName] = {};
322
- }
323
- if (!res.hooks[hookName].beforeDatasourceRequest) {
324
- res.hooks[hookName].beforeDatasourceRequest = [];
325
- }
326
- if (!Array.isArray(res.hooks[hookName].beforeDatasourceRequest)) {
327
- res.hooks[hookName].beforeDatasourceRequest = [res.hooks[hookName].beforeDatasourceRequest];
328
- }
329
- if (!res.hooks[hookName].afterDatasourceResponse) {
330
- res.hooks[hookName].afterDatasourceResponse = [];
331
- }
332
- if (!Array.isArray(res.hooks[hookName].afterDatasourceResponse)) {
333
- res.hooks[hookName].afterDatasourceResponse = [res.hooks[hookName].afterDatasourceResponse];
334
- }
335
- }
336
- for (const hookName of ['create', 'edit', 'delete']) {
337
- if (!res.hooks[hookName]) {
338
- res.hooks[hookName] = {};
339
- }
340
- if (!res.hooks[hookName].beforeSave) {
341
- res.hooks[hookName].beforeSave = [];
342
- }
343
- if (!Array.isArray(res.hooks[hookName].beforeSave)) {
344
- res.hooks[hookName].beforeSave = [res.hooks[hookName].beforeSave];
345
- }
346
- if (!res.hooks[hookName].afterSave) {
347
- res.hooks[hookName].afterSave = [];
348
- }
349
- if (!Array.isArray(res.hooks[hookName].afterSave)) {
350
- res.hooks[hookName].afterSave = [res.hooks[hookName].afterSave];
351
- }
352
- }
353
- });
354
- if (!this.config.menu) {
355
- errors.push('No config.menu defined');
356
- }
357
- // check if there is only one homepage: true in menu, recursivly
358
- let homepages = 0;
359
- const browseMenu = (menu) => {
360
- menu.forEach((item) => {
361
- if (item.component && item.resourceId) {
362
- errors.push(`Menu item cannot have both component and resourceId: ${JSON.stringify(item)}`);
363
- }
364
- if (item.component && !item.path) {
365
- errors.push(`Menu item with component must have path : ${JSON.stringify(item)}`);
366
- }
367
- if (item.type === 'resource' && !item.resourceId) {
368
- errors.push(`Menu item with type 'resource' must have resourceId : ${JSON.stringify(item)}`);
369
- }
370
- if (item.resourceId && !this.config.resources.find((res) => res.resourceId === item.resourceId)) {
371
- errors.push(`Menu item with type 'resourceId' has resourceId which is not in resources: ${JSON.stringify(item)}`);
372
- }
373
- if (item.type === 'component' && !item.component) {
374
- errors.push(`Menu item with type 'component' must have component : ${JSON.stringify(item)}`);
375
- }
376
- // make sure component starts with @@
377
- if (item.component) {
378
- if (!item.component.startsWith('@@')) {
379
- errors.push(`Menu item component must start with @@ : ${JSON.stringify(item)}`);
380
- }
381
- const path = item.component.replace('@@', this.config.customization.customComponentsDir);
382
- if (!fs.existsSync(path)) {
383
- errors.push(`Menu item component "${item.component.replace('@@', '')}" does not exist in "${this.config.customization.customComponentsDir}"`);
384
- }
385
- }
386
- if (item.homepage) {
387
- homepages++;
388
- if (homepages > 1) {
389
- errors.push('There must be only one homepage: true in menu, found second one in ' + JSON.stringify(item));
390
- }
391
- }
392
- if (item.children) {
393
- browseMenu(item.children);
394
- }
395
- });
396
- };
397
- browseMenu(this.config.menu);
398
- }
399
- // check for duplicate resourceIds and show which ones are duplicated
400
- const resourceIds = this.config.resources.map((res) => res.resourceId);
401
- const uniqueResourceIds = new Set(resourceIds);
402
- if (uniqueResourceIds.size != resourceIds.length) {
403
- const duplicates = resourceIds.filter((item, index) => resourceIds.indexOf(item) != index);
404
- errors.push(`Duplicate fields "resourceId" or "table": ${duplicates.join(', ')}`);
405
- }
406
- //add ids for onSelectedAllActions for each resource
407
- if (errors.length > 0) {
408
- throw new Error(`Invalid AdminForth config: ${errors.join(', ')}`);
409
- }
410
- // check is all custom components files exists
411
- for (const resource of this.config.resources) {
412
- for (const column of resource.columns) {
413
- if (column.components) {
414
- for (const [key, comp] of Object.entries(column.components)) {
415
- let ignoreExistsCheck = false;
416
- if (this.codeInjector.allComponentNames[comp.file]) {
417
- // not obvious, but if we are in this if, it means that this is plugin component
418
- // and there is no sense to check if it exists in users folder
419
- ignoreExistsCheck = true;
420
- }
421
- column.components[key] = this.validateComponent(comp, errors, ignoreExistsCheck);
422
- }
423
- }
424
- }
425
- }
426
- }
427
- postProcessAfterDiscover(resource) {
428
- resource.columns.forEach((column) => {
429
- // if db/user says column is required in boolean, exapd
430
- if (typeof column.required === 'boolean') {
431
- column.required = { create: column.required, edit: column.required };
432
- }
433
- if (!column.required) {
434
- column.required = { create: false, edit: false };
435
- }
436
- // same for editingNote
437
- if (typeof column.editingNote === 'string') {
438
- column.editingNote = { create: column.editingNote, edit: column.editingNote };
439
- }
440
- });
441
- resource.dataSourceColumns = resource.columns.filter((col) => !col.virtual);
442
- }
443
59
  discoverDatabases() {
444
60
  return __awaiter(this, void 0, void 0, function* () {
445
61
  this.statuses.dbDiscover = 'running';
@@ -476,7 +92,7 @@ class AdminForth {
476
92
  // first find discovered values, but allow override
477
93
  res.columns[i] = Object.assign(Object.assign({}, fieldTypes[col.name]), col);
478
94
  });
479
- this.postProcessAfterDiscover(res);
95
+ this.configValidator.postProcessAfterDiscover(res);
480
96
  // check if primaryKey column is present
481
97
  if (!res.columns.some((col) => col.primaryKey)) {
482
98
  throw new Error(`Resource '${res.table}' has no column defined or auto-discovered. Please set 'primaryKey: true' in a columns which has unique value for each record and index`);
@@ -520,7 +136,9 @@ class AdminForth {
520
136
  });
521
137
  }
522
138
  }
523
- if (((_c = column.required) === null || _c === void 0 ? void 0 : _c.create) && record[column.name] === undefined) {
139
+ if (((_c = column.required) === null || _c === void 0 ? void 0 : _c.create) &&
140
+ record[column.name] === undefined &&
141
+ column.showIn.includes(AdminForthResourcePages.create)) {
524
142
  return { error: `Column '${column.name}' is required` };
525
143
  }
526
144
  if (column.isUnique) {
@@ -553,6 +171,7 @@ class AdminForth {
553
171
  }
554
172
  }
555
173
  const connector = this.connectors[resource.dataSource];
174
+ process.env.HEAVY_DEBUG && console.log('🪲🪲🪲🪲 creating record createResourceRecord', record);
556
175
  yield connector.createRecord({ resource, record });
557
176
  // execute hook if needed
558
177
  for (const hook of listify((_g = (_f = resource.hooks) === null || _f === void 0 ? void 0 : _f.create) === null || _g === void 0 ? void 0 : _g.afterSave)) {
@@ -565,612 +184,11 @@ class AdminForth {
565
184
  return { error: resp.error };
566
185
  }
567
186
  }
187
+ return { ok: true };
568
188
  });
569
189
  }
570
190
  setupEndpoints(server) {
571
- server.endpoint({
572
- noAuth: true,
573
- method: 'POST',
574
- path: '/login',
575
- handler: (_b) => __awaiter(this, [_b], void 0, function* ({ body, response }) {
576
- var _c, _d, _e, _f;
577
- const INVALID_MESSAGE = 'Invalid username or password';
578
- const { username, password } = body;
579
- let adminUser;
580
- let toReturn = { ok: true, allowedLogin: true };
581
- let token;
582
- if (username === this.config.rootUser.username && password === this.config.rootUser.password) {
583
- this.auth.setAuthCookie({ response, username, pk: null });
584
- adminUser = { isRoot: true, dbUser: null, pk: null, username: this.config.rootUser.username };
585
- }
586
- else {
587
- // get resource from db
588
- if (!this.config.auth) {
589
- throw new Error('No config.auth defined');
590
- }
591
- const userResource = this.config.resources.find((res) => res.resourceId === this.config.auth.resourceId);
592
- // if there is no passwordHashField, in columns, add it, with backendOnly and showIn: []
593
- if (!userResource.dataSourceColumns.find((col) => col.name === this.config.auth.passwordHashField)) {
594
- userResource.dataSourceColumns.push({
595
- name: this.config.auth.passwordHashField,
596
- backendOnly: true,
597
- showIn: [],
598
- type: _a.Types.STRING,
599
- });
600
- console.log('Adding passwordHashField to userResource', userResource);
601
- }
602
- const userRecord = (_c = (yield this.connectors[userResource.dataSource].getData({
603
- resource: userResource,
604
- filters: [
605
- { field: this.config.auth.usernameField, operator: AdminForthFilterOperators.EQ, value: username },
606
- ],
607
- limit: 1,
608
- offset: 0,
609
- sort: [],
610
- })).data) === null || _c === void 0 ? void 0 : _c[0];
611
- if (!userRecord) {
612
- return { error: 'User not found' };
613
- }
614
- const passwordHash = userRecord[this.config.auth.passwordHashField];
615
- const valid = yield AdminForthAuth.verifyPassword(password, passwordHash);
616
- if (valid) {
617
- adminUser = {
618
- isRoot: false, dbUser: userRecord,
619
- pk: userRecord[userResource.columns.find((col) => col.primaryKey).name],
620
- username,
621
- };
622
- const beforeLoginConfirmation = this.config.auth.beforeLoginConfirmation;
623
- if (beforeLoginConfirmation === null || beforeLoginConfirmation === void 0 ? void 0 : beforeLoginConfirmation.length) {
624
- for (const hook of beforeLoginConfirmation) {
625
- const resp = yield hook({ adminUser, response });
626
- if ((_d = resp === null || resp === void 0 ? void 0 : resp.body) === null || _d === void 0 ? void 0 : _d.redirectTo) {
627
- toReturn = { ok: resp.ok, redirectTo: (_e = resp === null || resp === void 0 ? void 0 : resp.body) === null || _e === void 0 ? void 0 : _e.redirectTo, allowedLogin: (_f = resp === null || resp === void 0 ? void 0 : resp.body) === null || _f === void 0 ? void 0 : _f.allowedLogin };
628
- break;
629
- }
630
- }
631
- }
632
- if (toReturn.allowedLogin) {
633
- this.auth.setAuthCookie({ response, username, pk: userRecord[userResource.columns.find((col) => col.primaryKey).name] });
634
- }
635
- }
636
- else {
637
- return { error: INVALID_MESSAGE };
638
- }
639
- }
640
- return toReturn;
641
- })
642
- });
643
- server.endpoint({
644
- method: 'POST',
645
- path: '/check_auth',
646
- handler: (_g) => __awaiter(this, [_g], void 0, function* ({ adminUser }) {
647
- return { ok: true };
648
- }),
649
- });
650
- server.endpoint({
651
- noAuth: true,
652
- method: 'POST',
653
- path: '/logout',
654
- handler: (_h) => __awaiter(this, [_h], void 0, function* ({ response }) {
655
- this.auth.removeAuthCookie(response);
656
- return { ok: true };
657
- }),
658
- });
659
- server.endpoint({
660
- noAuth: true,
661
- method: 'GET',
662
- path: '/get_public_config',
663
- handler: (_j) => __awaiter(this, [_j], void 0, function* ({ body }) {
664
- var _k;
665
- // find resource
666
- if (!this.config.auth) {
667
- throw new Error('No config.auth defined');
668
- }
669
- const usernameField = this.config.auth.usernameField;
670
- const resource = this.config.resources.find((res) => res.resourceId === this.config.auth.resourceId);
671
- const usernameColumn = resource.columns.find((col) => col.name === usernameField);
672
- return {
673
- brandName: this.config.customization.brandName,
674
- usernameFieldName: usernameColumn.label,
675
- loginBackgroundImage: this.config.auth.loginBackgroundImage,
676
- title: (_k = this.config.customization) === null || _k === void 0 ? void 0 : _k.title,
677
- };
678
- }),
679
- });
680
- server.endpoint({
681
- method: 'GET',
682
- path: '/get_base_config',
683
- handler: (_l) => __awaiter(this, [_l], void 0, function* ({ input, adminUser, cookies }) {
684
- var _m, _o;
685
- let username = '';
686
- let userFullName = '';
687
- if (adminUser.isRoot) {
688
- username = this.config.rootUser.username;
689
- }
690
- else {
691
- const dbUser = adminUser.dbUser;
692
- username = dbUser[this.config.auth.usernameField];
693
- userFullName = dbUser[this.config.auth.userFullNameField];
694
- }
695
- const userData = {
696
- [this.config.auth.usernameField]: username,
697
- [this.config.auth.userFullNameField]: userFullName
698
- };
699
- const checkIsMenuItemVisible = (menuItem) => {
700
- if (typeof menuItem.visible === 'function') {
701
- const toReturn = menuItem.visible(adminUser);
702
- if (typeof toReturn !== 'boolean') {
703
- throw new Error(`'visible' function of ${menuItem.label || menuItem.type} must return boolean value`);
704
- }
705
- return toReturn;
706
- }
707
- };
708
- let newMenu = [];
709
- for (let menuItem of this.config.menu) {
710
- let newMenuItem = Object.assign({}, menuItem);
711
- if (menuItem.visible) {
712
- if (!checkIsMenuItemVisible(menuItem)) {
713
- continue;
714
- }
715
- }
716
- if (menuItem.children) {
717
- let newChildren = [];
718
- for (let child of menuItem.children) {
719
- let newChild = Object.assign({}, child);
720
- if (child.visible) {
721
- if (!checkIsMenuItemVisible(child)) {
722
- continue;
723
- }
724
- }
725
- newChildren.push(newChild);
726
- }
727
- newMenuItem = Object.assign(Object.assign({}, newMenuItem), { children: newChildren });
728
- }
729
- newMenu.push(newMenuItem);
730
- }
731
- return {
732
- user: userData,
733
- resources: this.config.resources.map((res) => ({
734
- resourceId: res.resourceId,
735
- label: res.label,
736
- })),
737
- menu: newMenu,
738
- config: {
739
- brandName: this.config.customization.brandName,
740
- brandLogo: this.config.customization.brandLogo,
741
- datesFormat: this.config.customization.datesFormat,
742
- deleteConfirmation: this.config.deleteConfirmation,
743
- auth: this.config.auth,
744
- usernameField: this.config.auth.usernameField,
745
- title: (_m = this.config.customization) === null || _m === void 0 ? void 0 : _m.title,
746
- emptyFieldPlaceholder: (_o = this.config.customization) === null || _o === void 0 ? void 0 : _o.emptyFieldPlaceholder,
747
- },
748
- adminUser,
749
- version: ADMINFORTH_VERSION,
750
- };
751
- }),
752
- });
753
- function interpretResource(adminUser, resource, meta, source) {
754
- return __awaiter(this, void 0, void 0, function* () {
755
- var _b;
756
- if (process.env.HEAVY_DEBUG) {
757
- console.log('🪲Interpreting resource', resource.resourceId, source);
758
- }
759
- const allowedActions = {};
760
- yield Promise.all(Object.entries(((_b = resource.options) === null || _b === void 0 ? void 0 : _b.allowedActions) || {}).map((_c) => __awaiter(this, [_c], void 0, function* ([key, value]) {
761
- if (process.env.HEAVY_DEBUG) {
762
- console.log('🪲checking for allowed call', key, 'value:', value, 'typeof', typeof value);
763
- }
764
- // if callable then call
765
- if (typeof value === 'function') {
766
- allowedActions[key] = yield value({ adminUser, resource, meta, source });
767
- }
768
- else {
769
- allowedActions[key] = value;
770
- }
771
- })));
772
- return { allowedActions };
773
- });
774
- }
775
- function checkAccess(action, allowedActions) {
776
- const allowed = allowedActions[action];
777
- if (allowed !== true) {
778
- return { error: typeof allowed === 'string' ? allowed : 'Action is not allowed', allowed: false };
779
- }
780
- return { allowed: true };
781
- }
782
- server.endpoint({
783
- method: 'POST',
784
- path: '/get_resource',
785
- handler: (_p) => __awaiter(this, [_p], void 0, function* ({ body, adminUser }) {
786
- const { resourceId } = body;
787
- if (!this.statuses.dbDiscover) {
788
- return { error: 'Database discovery not started' };
789
- }
790
- if (this.statuses.dbDiscover !== 'done') {
791
- return { error: 'Database discovery is still in progress, please try later' };
792
- }
793
- const resource = this.config.resources.find((res) => res.resourceId == resourceId);
794
- if (!resource) {
795
- return { error: `Resource ${resourceId} not found` };
796
- }
797
- const { allowedActions } = yield interpretResource(adminUser, resource, {}, ActionCheckSource.DisplayButtons);
798
- // exclude "plugins" key
799
- return {
800
- resource: Object.assign(Object.assign({}, resource), { plugins: undefined, options: Object.assign(Object.assign({}, resource.options), { allowedActions }) })
801
- };
802
- }),
803
- });
804
- server.endpoint({
805
- method: 'POST',
806
- path: '/get_resource_data',
807
- handler: (_q) => __awaiter(this, [_q], void 0, function* ({ body, adminUser }) {
808
- var _r, _s, _t, _u;
809
- const { resourceId, source } = body;
810
- if (['show', 'list'].includes(source) === false) {
811
- return { error: 'Invalid source, should be list or show' };
812
- }
813
- if (!this.statuses.dbDiscover) {
814
- return { error: 'Database discovery not started' };
815
- }
816
- if (this.statuses.dbDiscover !== 'done') {
817
- return { error: 'Database discovery is still in progress, please try later' };
818
- }
819
- const resource = this.config.resources.find((res) => res.resourceId == resourceId);
820
- if (!resource) {
821
- return { error: `Resource ${resourceId} not found` };
822
- }
823
- const { allowedActions } = yield interpretResource(adminUser, resource, { requestBody: body }, ActionCheckSource.DisplayButtons);
824
- const { allowed, error } = checkAccess(source, allowedActions);
825
- if (!allowed) {
826
- return { error };
827
- }
828
- for (const hook of listify((_s = (_r = resource.hooks) === null || _r === void 0 ? void 0 : _r[source]) === null || _s === void 0 ? void 0 : _s.beforeDatasourceRequest)) {
829
- const resp = yield hook({ resource, query: body, adminUser });
830
- if (!resp || (!resp.ok && !resp.error)) {
831
- throw new Error(`Hook must return object with {ok: true} or { error: 'Error' } `);
832
- }
833
- if (resp.error) {
834
- return { error: resp.error };
835
- }
836
- }
837
- const { limit, offset, filters, sort } = body;
838
- for (const filter of (filters || [])) {
839
- if (!Object.values(AdminForthFilterOperators).includes(filter.operator)) {
840
- throw new Error(`Operator '${filter.operator}' is not allowed`);
841
- }
842
- if (!resource.columns.some((col) => col.name === filter.field)) {
843
- throw new Error(`Field '${filter.field}' is not in resource '${resource.resourceId}'. Available fields: ${resource.columns.map((col) => col.name).join(', ')}`);
844
- }
845
- if (filter.operator === AdminForthFilterOperators.IN || filter.operator === AdminForthFilterOperators.NIN) {
846
- if (!Array.isArray(filter.value)) {
847
- throw new Error(`Value for operator '${filter.operator}' should be an array`);
848
- }
849
- }
850
- if (filter.operator === AdminForthFilterOperators.IN && filter.value.length === 0) {
851
- // nonsense
852
- return { data: [], total: 0 };
853
- }
854
- }
855
- const data = yield this.connectors[resource.dataSource].getData({
856
- resource,
857
- limit,
858
- offset,
859
- filters,
860
- sort,
861
- });
862
- // for foreign keys, add references
863
- yield Promise.all(resource.columns.filter((col) => col.foreignResource).map((col) => __awaiter(this, void 0, void 0, function* () {
864
- const targetResource = this.config.resources.find((res) => res.resourceId == col.foreignResource.resourceId);
865
- const targetConnector = this.connectors[targetResource.dataSource];
866
- const targetResourcePkField = targetResource.columns.find((col) => col.primaryKey).name;
867
- const pksUnique = [...new Set(data.data.map((item) => item[col.name]))];
868
- if (pksUnique.length === 0) {
869
- return;
870
- }
871
- const targetData = yield targetConnector.getData({
872
- resource: targetResource,
873
- limit: limit,
874
- offset: 0,
875
- filters: [
876
- {
877
- field: targetResourcePkField,
878
- operator: AdminForthFilterOperators.IN,
879
- value: pksUnique,
880
- }
881
- ],
882
- sort: [],
883
- });
884
- const targetDataMap = targetData.data.reduce((acc, item) => {
885
- acc[item[targetResourcePkField]] = {
886
- label: targetResource.recordLabel(item),
887
- pk: item[targetResourcePkField],
888
- };
889
- return acc;
890
- }, {});
891
- data.data.forEach((item) => {
892
- item[col.name] = targetDataMap[item[col.name]];
893
- });
894
- })));
895
- for (const hook of listify((_u = (_t = resource.hooks) === null || _t === void 0 ? void 0 : _t[source]) === null || _u === void 0 ? void 0 : _u.afterDatasourceResponse)) {
896
- const resp = yield hook({ resource, response: data.data, adminUser });
897
- if (!resp || (!resp.ok && !resp.error)) {
898
- throw new Error(`Hook must return object with {ok: true} or { error: 'Error' } `);
899
- }
900
- if (resp.error) {
901
- return { error: resp.error };
902
- }
903
- }
904
- // remove all columns which are not defined in resources, or defined but backendOnly
905
- data.data.forEach((item) => {
906
- Object.keys(item).forEach((key) => {
907
- if (!resource.columns.find((col) => col.name === key) || resource.columns.find((col) => col.name === key && col.backendOnly)) {
908
- delete item[key];
909
- }
910
- });
911
- });
912
- data.data.forEach((item) => {
913
- item._label = resource.recordLabel(item);
914
- });
915
- return Object.assign(Object.assign({}, data), { options: resource === null || resource === void 0 ? void 0 : resource.options });
916
- }),
917
- });
918
- server.endpoint({
919
- method: 'POST',
920
- path: '/get_resource_foreign_data',
921
- handler: (_v) => __awaiter(this, [_v], void 0, function* ({ body, adminUser }) {
922
- var _w, _x, _y, _z;
923
- const { resourceId, column } = body;
924
- if (!this.statuses.dbDiscover) {
925
- return { error: 'Database discovery not started' };
926
- }
927
- if (this.statuses.dbDiscover !== 'done') {
928
- return { error: 'Database discovery is still in progress, please try later' };
929
- }
930
- const resource = this.config.resources.find((res) => res.resourceId == resourceId);
931
- if (!resource) {
932
- return { error: `Resource '${resourceId}' not found` };
933
- }
934
- const columnConfig = resource.columns.find((col) => col.name == column);
935
- if (!columnConfig) {
936
- return { error: `Column "${column}' not found in resource with resourceId '${resourceId}'` };
937
- }
938
- if (!columnConfig.foreignResource) {
939
- return { error: `Column '${column}' in resource '${resourceId}' is not a foreign key` };
940
- }
941
- const targetResourceId = columnConfig.foreignResource.resourceId;
942
- const targetResource = this.config.resources.find((res) => res.resourceId == targetResourceId);
943
- for (const hook of listify((_x = (_w = columnConfig.foreignResource.hooks) === null || _w === void 0 ? void 0 : _w.dropdownList) === null || _x === void 0 ? void 0 : _x.beforeDatasourceRequest)) {
944
- const resp = yield hook({ query: body, adminUser, resource: targetResource });
945
- if (!resp || (!resp.ok && !resp.error)) {
946
- throw new Error(`Hook must return object with {ok: true} or { error: 'Error' } `);
947
- }
948
- if (resp.error) {
949
- return { error: resp.error };
950
- }
951
- }
952
- const { limit, offset, filters, sort } = body;
953
- const dbDataItems = yield this.connectors[targetResource.dataSource].getData({
954
- resource: targetResource,
955
- limit,
956
- offset,
957
- filters: filters || [],
958
- sort: sort || [],
959
- });
960
- const items = dbDataItems.data.map((item) => {
961
- const pk = item[targetResource.columns.find((col) => col.primaryKey).name];
962
- const labler = targetResource.recordLabel;
963
- return {
964
- value: pk,
965
- label: labler(item),
966
- _item: item, // user might need it in hook to form new label
967
- };
968
- });
969
- const response = {
970
- items
971
- };
972
- for (const hook of listify((_z = (_y = columnConfig.foreignResource.hooks) === null || _y === void 0 ? void 0 : _y.dropdownList) === null || _z === void 0 ? void 0 : _z.afterDatasourceResponse)) {
973
- const resp = yield hook({ response, adminUser, resource: targetResource });
974
- if (!resp || (!resp.ok && !resp.error)) {
975
- throw new Error(`Hook must return object with {ok: true} or { error: 'Error' } `);
976
- }
977
- if (resp.error) {
978
- return { error: resp.error };
979
- }
980
- }
981
- return response;
982
- }),
983
- });
984
- server.endpoint({
985
- method: 'POST',
986
- path: '/get_min_max_for_columns',
987
- handler: (_0) => __awaiter(this, [_0], void 0, function* ({ body }) {
988
- const { resourceId } = body;
989
- if (!this.statuses.dbDiscover) {
990
- return { error: 'Database discovery not started' };
991
- }
992
- if (this.statuses.dbDiscover !== 'done') {
993
- return { error: 'Database discovery is still in progress, please try later' };
994
- }
995
- const resource = this.config.resources.find((res) => res.resourceId == resourceId);
996
- if (!resource) {
997
- return { error: `Resource '${resourceId}' not found` };
998
- }
999
- const item = yield this.connectors[resource.dataSource].getMinMaxForColumns({
1000
- resource,
1001
- columns: resource.columns.filter((col) => [
1002
- AdminForthDataTypes.INTEGER,
1003
- AdminForthDataTypes.FLOAT,
1004
- AdminForthDataTypes.DATE,
1005
- AdminForthDataTypes.DATETIME,
1006
- AdminForthDataTypes.TIME,
1007
- AdminForthDataTypes.DECIMAL,
1008
- ].includes(col.type) && col.allowMinMaxQuery === true),
1009
- });
1010
- return item;
1011
- }),
1012
- });
1013
- server.endpoint({
1014
- method: 'POST',
1015
- path: '/create_record',
1016
- handler: (_1) => __awaiter(this, [_1], void 0, function* ({ body, adminUser }) {
1017
- const resource = this.config.resources.find((res) => res.resourceId == body['resourceId']);
1018
- if (!resource) {
1019
- return { error: `Resource '${body['resourceId']}' not found` };
1020
- }
1021
- const { allowedActions } = yield interpretResource(adminUser, resource, { requestBody: body }, ActionCheckSource.CreateRequest);
1022
- const { allowed, error } = checkAccess(AllowedActionsEnum.create, allowedActions);
1023
- if (!allowed) {
1024
- return { error };
1025
- }
1026
- const { record } = body;
1027
- yield this.createResourceRecord({ resource, record, adminUser });
1028
- const connector = this.connectors[resource.dataSource];
1029
- return {
1030
- newRecordId: body['record'][connector.getPrimaryKey(resource)]
1031
- };
1032
- })
1033
- });
1034
- server.endpoint({
1035
- method: 'POST',
1036
- path: '/update_record',
1037
- handler: (_2) => __awaiter(this, [_2], void 0, function* ({ body, adminUser }) {
1038
- var _3, _4, _5, _6;
1039
- const resource = this.config.resources.find((res) => res.resourceId == body['resourceId']);
1040
- if (!resource) {
1041
- return { error: `Resource '${body['resourceId']}' not found` };
1042
- }
1043
- const recordId = body['recordId'];
1044
- const connector = this.connectors[resource.dataSource];
1045
- const oldRecord = yield connector.getRecordByPrimaryKey(resource, recordId);
1046
- if (!oldRecord) {
1047
- const primaryKeyColumn = resource.columns.find((col) => col.primaryKey);
1048
- return { error: `Record with ${primaryKeyColumn.name} ${recordId} not found` };
1049
- }
1050
- const record = body['record'];
1051
- const { allowedActions } = yield interpretResource(adminUser, resource, { requestBody: body, newRecord: record, oldRecord }, ActionCheckSource.EditRequest);
1052
- const { allowed, error } = checkAccess(AllowedActionsEnum.edit, allowedActions);
1053
- if (!allowed) {
1054
- return { error };
1055
- }
1056
- // execute hook if needed
1057
- for (const hook of listify((_4 = (_3 = resource.hooks) === null || _3 === void 0 ? void 0 : _3.edit) === null || _4 === void 0 ? void 0 : _4.beforeSave)) {
1058
- const resp = yield hook({ resource, record, adminUser });
1059
- if (!resp || (!resp.ok && !resp.error)) {
1060
- throw new Error(`Hook beforeSave must return object with {ok: true} or { error: 'Error' } `);
1061
- }
1062
- if (resp.error) {
1063
- return { error: resp.error };
1064
- }
1065
- }
1066
- const newValues = {};
1067
- for (const recordField in record) {
1068
- if (record[recordField] !== oldRecord[recordField]) {
1069
- const column = resource.columns.find((col) => col.name === recordField);
1070
- if (column) {
1071
- if (!column.virtual) {
1072
- newValues[recordField] = connector.setFieldValue(column, record[recordField]);
1073
- }
1074
- }
1075
- else {
1076
- newValues[recordField] = record[recordField];
1077
- }
1078
- }
1079
- }
1080
- if (Object.keys(newValues).length > 0) {
1081
- yield connector.updateRecord({ resource, recordId, newValues });
1082
- }
1083
- // execute hook if needed
1084
- for (const hook of listify((_6 = (_5 = resource.hooks) === null || _5 === void 0 ? void 0 : _5.edit) === null || _6 === void 0 ? void 0 : _6.afterSave)) {
1085
- const resp = yield hook({ resource, record, adminUser, oldRecord });
1086
- if (!resp || (!resp.ok && !resp.error)) {
1087
- throw new Error(`Hook afterSave must return object with {ok: true} or { error: 'Error' } `);
1088
- }
1089
- if (resp.error) {
1090
- return { error: resp.error };
1091
- }
1092
- }
1093
- return {
1094
- newRecordId: recordId
1095
- };
1096
- })
1097
- });
1098
- server.endpoint({
1099
- method: 'POST',
1100
- path: '/delete_record',
1101
- handler: (_7) => __awaiter(this, [_7], void 0, function* ({ body, adminUser }) {
1102
- var _8, _9, _10, _11;
1103
- const resource = this.config.resources.find((res) => res.resourceId == body['resourceId']);
1104
- const record = yield this.connectors[resource.dataSource].getRecordByPrimaryKey(resource, body['primaryKey']);
1105
- if (!resource) {
1106
- return { error: `Resource '${body['resourceId']}' not found` };
1107
- }
1108
- if (!record) {
1109
- return { error: `Record with ${body['primaryKey']} not found` };
1110
- }
1111
- if (resource.options.allowedActions.delete === false) {
1112
- return { error: `Resource '${resource.resourceId}' does not allow delete action` };
1113
- }
1114
- const { allowedActions } = yield interpretResource(adminUser, resource, { requestBody: body }, ActionCheckSource.DeleteRequest);
1115
- const { allowed, error } = checkAccess(AllowedActionsEnum.delete, allowedActions);
1116
- if (!allowed) {
1117
- return { error };
1118
- }
1119
- // execute hook if needed
1120
- for (const hook of listify((_9 = (_8 = resource.hooks) === null || _8 === void 0 ? void 0 : _8.delete) === null || _9 === void 0 ? void 0 : _9.beforeSave)) {
1121
- const resp = yield hook({ resource, record, adminUser });
1122
- if (!resp || (!resp.ok && !resp.error)) {
1123
- throw new Error(`Hook beforeSave must return object with {ok: true} or { error: 'Error' } `);
1124
- }
1125
- if (resp.error) {
1126
- return { error: resp.error };
1127
- }
1128
- }
1129
- const connector = this.connectors[resource.dataSource];
1130
- yield connector.deleteRecord({ resource, recordId: body['primaryKey'] });
1131
- // execute hook if needed
1132
- for (const hook of listify((_11 = (_10 = resource.hooks) === null || _10 === void 0 ? void 0 : _10.delete) === null || _11 === void 0 ? void 0 : _11.afterSave)) {
1133
- const resp = yield hook({ resource, record, adminUser });
1134
- if (!resp || (!resp.ok && !resp.error)) {
1135
- throw new Error(`Hook afterSave must return object with {ok: true} or { error: 'Error' } `);
1136
- }
1137
- if (resp.error) {
1138
- return { error: resp.error };
1139
- }
1140
- }
1141
- return {
1142
- recordId: body['primaryKey']
1143
- };
1144
- })
1145
- });
1146
- server.endpoint({
1147
- method: 'POST',
1148
- path: '/start_bulk_action',
1149
- handler: (_12) => __awaiter(this, [_12], void 0, function* ({ body }) {
1150
- const { resourceId, actionId, recordIds } = body;
1151
- const resource = this.config.resources.find((res) => res.resourceId == resourceId);
1152
- if (!resource) {
1153
- return { error: `Resource '${resourceId}' not found` };
1154
- }
1155
- const action = resource.options.bulkActions.find((act) => act.id == actionId);
1156
- if (!action) {
1157
- return { error: `Action '${actionId}' not found` };
1158
- }
1159
- else {
1160
- yield action.action({ selectedIds: recordIds });
1161
- }
1162
- return {
1163
- actionId,
1164
- recordIds,
1165
- resourceId,
1166
- status: 'success'
1167
- };
1168
- })
1169
- });
1170
- // setup endpoints for all plugins
1171
- this.activatedPlugins.forEach((plugin) => {
1172
- plugin.setupEndpoints(server);
1173
- });
191
+ this.restApi.registerEndpoints(server);
1174
192
  }
1175
193
  }
1176
194
  _a = AdminForth, _AdminForth_defaultConfig = new WeakMap();