adminforth 1.2.1 → 1.2.3
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/dataConnectors/postgres.ts +12 -0
- package/dist/dataConnectors/postgres.js +13 -0
- package/dist/index.js +12 -1001
- package/dist/modules/configValidator.js +408 -0
- package/dist/modules/restApi.js +625 -0
- package/index.ts +16 -1122
- package/modules/configValidator.ts +452 -0
- package/modules/restApi.ts +709 -0
- package/package.json +1 -1
- package/types/AdminForthConfig.ts +15 -0
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
|
|
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`);
|
|
@@ -572,612 +188,7 @@ class AdminForth {
|
|
|
572
188
|
});
|
|
573
189
|
}
|
|
574
190
|
setupEndpoints(server) {
|
|
575
|
-
|
|
576
|
-
noAuth: true,
|
|
577
|
-
method: 'POST',
|
|
578
|
-
path: '/login',
|
|
579
|
-
handler: (_b) => __awaiter(this, [_b], void 0, function* ({ body, response }) {
|
|
580
|
-
var _c, _d, _e, _f;
|
|
581
|
-
const INVALID_MESSAGE = 'Invalid username or password';
|
|
582
|
-
const { username, password } = body;
|
|
583
|
-
let adminUser;
|
|
584
|
-
let toReturn = { ok: true, allowedLogin: true };
|
|
585
|
-
let token;
|
|
586
|
-
if (username === this.config.rootUser.username && password === this.config.rootUser.password) {
|
|
587
|
-
this.auth.setAuthCookie({ response, username, pk: null });
|
|
588
|
-
adminUser = { isRoot: true, dbUser: null, pk: null, username: this.config.rootUser.username };
|
|
589
|
-
}
|
|
590
|
-
else {
|
|
591
|
-
// get resource from db
|
|
592
|
-
if (!this.config.auth) {
|
|
593
|
-
throw new Error('No config.auth defined');
|
|
594
|
-
}
|
|
595
|
-
const userResource = this.config.resources.find((res) => res.resourceId === this.config.auth.resourceId);
|
|
596
|
-
// if there is no passwordHashField, in columns, add it, with backendOnly and showIn: []
|
|
597
|
-
if (!userResource.dataSourceColumns.find((col) => col.name === this.config.auth.passwordHashField)) {
|
|
598
|
-
userResource.dataSourceColumns.push({
|
|
599
|
-
name: this.config.auth.passwordHashField,
|
|
600
|
-
backendOnly: true,
|
|
601
|
-
showIn: [],
|
|
602
|
-
type: _a.Types.STRING,
|
|
603
|
-
});
|
|
604
|
-
console.log('Adding passwordHashField to userResource', userResource);
|
|
605
|
-
}
|
|
606
|
-
const userRecord = (_c = (yield this.connectors[userResource.dataSource].getData({
|
|
607
|
-
resource: userResource,
|
|
608
|
-
filters: [
|
|
609
|
-
{ field: this.config.auth.usernameField, operator: AdminForthFilterOperators.EQ, value: username },
|
|
610
|
-
],
|
|
611
|
-
limit: 1,
|
|
612
|
-
offset: 0,
|
|
613
|
-
sort: [],
|
|
614
|
-
})).data) === null || _c === void 0 ? void 0 : _c[0];
|
|
615
|
-
if (!userRecord) {
|
|
616
|
-
return { error: 'User not found' };
|
|
617
|
-
}
|
|
618
|
-
const passwordHash = userRecord[this.config.auth.passwordHashField];
|
|
619
|
-
const valid = yield AdminForthAuth.verifyPassword(password, passwordHash);
|
|
620
|
-
if (valid) {
|
|
621
|
-
adminUser = {
|
|
622
|
-
isRoot: false, dbUser: userRecord,
|
|
623
|
-
pk: userRecord[userResource.columns.find((col) => col.primaryKey).name],
|
|
624
|
-
username,
|
|
625
|
-
};
|
|
626
|
-
const beforeLoginConfirmation = this.config.auth.beforeLoginConfirmation;
|
|
627
|
-
if (beforeLoginConfirmation === null || beforeLoginConfirmation === void 0 ? void 0 : beforeLoginConfirmation.length) {
|
|
628
|
-
for (const hook of beforeLoginConfirmation) {
|
|
629
|
-
const resp = yield hook({ adminUser, response });
|
|
630
|
-
if ((_d = resp === null || resp === void 0 ? void 0 : resp.body) === null || _d === void 0 ? void 0 : _d.redirectTo) {
|
|
631
|
-
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 };
|
|
632
|
-
break;
|
|
633
|
-
}
|
|
634
|
-
}
|
|
635
|
-
}
|
|
636
|
-
if (toReturn.allowedLogin) {
|
|
637
|
-
this.auth.setAuthCookie({ response, username, pk: userRecord[userResource.columns.find((col) => col.primaryKey).name] });
|
|
638
|
-
}
|
|
639
|
-
}
|
|
640
|
-
else {
|
|
641
|
-
return { error: INVALID_MESSAGE };
|
|
642
|
-
}
|
|
643
|
-
}
|
|
644
|
-
return toReturn;
|
|
645
|
-
})
|
|
646
|
-
});
|
|
647
|
-
server.endpoint({
|
|
648
|
-
method: 'POST',
|
|
649
|
-
path: '/check_auth',
|
|
650
|
-
handler: (_g) => __awaiter(this, [_g], void 0, function* ({ adminUser }) {
|
|
651
|
-
return { ok: true };
|
|
652
|
-
}),
|
|
653
|
-
});
|
|
654
|
-
server.endpoint({
|
|
655
|
-
noAuth: true,
|
|
656
|
-
method: 'POST',
|
|
657
|
-
path: '/logout',
|
|
658
|
-
handler: (_h) => __awaiter(this, [_h], void 0, function* ({ response }) {
|
|
659
|
-
this.auth.removeAuthCookie(response);
|
|
660
|
-
return { ok: true };
|
|
661
|
-
}),
|
|
662
|
-
});
|
|
663
|
-
server.endpoint({
|
|
664
|
-
noAuth: true,
|
|
665
|
-
method: 'GET',
|
|
666
|
-
path: '/get_public_config',
|
|
667
|
-
handler: (_j) => __awaiter(this, [_j], void 0, function* ({ body }) {
|
|
668
|
-
var _k;
|
|
669
|
-
// find resource
|
|
670
|
-
if (!this.config.auth) {
|
|
671
|
-
throw new Error('No config.auth defined');
|
|
672
|
-
}
|
|
673
|
-
const usernameField = this.config.auth.usernameField;
|
|
674
|
-
const resource = this.config.resources.find((res) => res.resourceId === this.config.auth.resourceId);
|
|
675
|
-
const usernameColumn = resource.columns.find((col) => col.name === usernameField);
|
|
676
|
-
return {
|
|
677
|
-
brandName: this.config.customization.brandName,
|
|
678
|
-
usernameFieldName: usernameColumn.label,
|
|
679
|
-
loginBackgroundImage: this.config.auth.loginBackgroundImage,
|
|
680
|
-
title: (_k = this.config.customization) === null || _k === void 0 ? void 0 : _k.title,
|
|
681
|
-
};
|
|
682
|
-
}),
|
|
683
|
-
});
|
|
684
|
-
server.endpoint({
|
|
685
|
-
method: 'GET',
|
|
686
|
-
path: '/get_base_config',
|
|
687
|
-
handler: (_l) => __awaiter(this, [_l], void 0, function* ({ input, adminUser, cookies }) {
|
|
688
|
-
var _m, _o;
|
|
689
|
-
let username = '';
|
|
690
|
-
let userFullName = '';
|
|
691
|
-
if (adminUser.isRoot) {
|
|
692
|
-
username = this.config.rootUser.username;
|
|
693
|
-
}
|
|
694
|
-
else {
|
|
695
|
-
const dbUser = adminUser.dbUser;
|
|
696
|
-
username = dbUser[this.config.auth.usernameField];
|
|
697
|
-
userFullName = dbUser[this.config.auth.userFullNameField];
|
|
698
|
-
}
|
|
699
|
-
const userData = {
|
|
700
|
-
[this.config.auth.usernameField]: username,
|
|
701
|
-
[this.config.auth.userFullNameField]: userFullName
|
|
702
|
-
};
|
|
703
|
-
const checkIsMenuItemVisible = (menuItem) => {
|
|
704
|
-
if (typeof menuItem.visible === 'function') {
|
|
705
|
-
const toReturn = menuItem.visible(adminUser);
|
|
706
|
-
if (typeof toReturn !== 'boolean') {
|
|
707
|
-
throw new Error(`'visible' function of ${menuItem.label || menuItem.type} must return boolean value`);
|
|
708
|
-
}
|
|
709
|
-
return toReturn;
|
|
710
|
-
}
|
|
711
|
-
};
|
|
712
|
-
let newMenu = [];
|
|
713
|
-
for (let menuItem of this.config.menu) {
|
|
714
|
-
let newMenuItem = Object.assign({}, menuItem);
|
|
715
|
-
if (menuItem.visible) {
|
|
716
|
-
if (!checkIsMenuItemVisible(menuItem)) {
|
|
717
|
-
continue;
|
|
718
|
-
}
|
|
719
|
-
}
|
|
720
|
-
if (menuItem.children) {
|
|
721
|
-
let newChildren = [];
|
|
722
|
-
for (let child of menuItem.children) {
|
|
723
|
-
let newChild = Object.assign({}, child);
|
|
724
|
-
if (child.visible) {
|
|
725
|
-
if (!checkIsMenuItemVisible(child)) {
|
|
726
|
-
continue;
|
|
727
|
-
}
|
|
728
|
-
}
|
|
729
|
-
newChildren.push(newChild);
|
|
730
|
-
}
|
|
731
|
-
newMenuItem = Object.assign(Object.assign({}, newMenuItem), { children: newChildren });
|
|
732
|
-
}
|
|
733
|
-
newMenu.push(newMenuItem);
|
|
734
|
-
}
|
|
735
|
-
return {
|
|
736
|
-
user: userData,
|
|
737
|
-
resources: this.config.resources.map((res) => ({
|
|
738
|
-
resourceId: res.resourceId,
|
|
739
|
-
label: res.label,
|
|
740
|
-
})),
|
|
741
|
-
menu: newMenu,
|
|
742
|
-
config: {
|
|
743
|
-
brandName: this.config.customization.brandName,
|
|
744
|
-
brandLogo: this.config.customization.brandLogo,
|
|
745
|
-
datesFormat: this.config.customization.datesFormat,
|
|
746
|
-
deleteConfirmation: this.config.deleteConfirmation,
|
|
747
|
-
auth: this.config.auth,
|
|
748
|
-
usernameField: this.config.auth.usernameField,
|
|
749
|
-
title: (_m = this.config.customization) === null || _m === void 0 ? void 0 : _m.title,
|
|
750
|
-
emptyFieldPlaceholder: (_o = this.config.customization) === null || _o === void 0 ? void 0 : _o.emptyFieldPlaceholder,
|
|
751
|
-
},
|
|
752
|
-
adminUser,
|
|
753
|
-
version: ADMINFORTH_VERSION,
|
|
754
|
-
};
|
|
755
|
-
}),
|
|
756
|
-
});
|
|
757
|
-
function interpretResource(adminUser, resource, meta, source) {
|
|
758
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
759
|
-
var _b;
|
|
760
|
-
if (process.env.HEAVY_DEBUG) {
|
|
761
|
-
console.log('🪲Interpreting resource', resource.resourceId, source);
|
|
762
|
-
}
|
|
763
|
-
const allowedActions = {};
|
|
764
|
-
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]) {
|
|
765
|
-
if (process.env.HEAVY_DEBUG) {
|
|
766
|
-
console.log('🪲checking for allowed call', key, 'value:', value, 'typeof', typeof value);
|
|
767
|
-
}
|
|
768
|
-
// if callable then call
|
|
769
|
-
if (typeof value === 'function') {
|
|
770
|
-
allowedActions[key] = yield value({ adminUser, resource, meta, source });
|
|
771
|
-
}
|
|
772
|
-
else {
|
|
773
|
-
allowedActions[key] = value;
|
|
774
|
-
}
|
|
775
|
-
})));
|
|
776
|
-
return { allowedActions };
|
|
777
|
-
});
|
|
778
|
-
}
|
|
779
|
-
function checkAccess(action, allowedActions) {
|
|
780
|
-
const allowed = allowedActions[action];
|
|
781
|
-
if (allowed !== true) {
|
|
782
|
-
return { error: typeof allowed === 'string' ? allowed : 'Action is not allowed', allowed: false };
|
|
783
|
-
}
|
|
784
|
-
return { allowed: true };
|
|
785
|
-
}
|
|
786
|
-
server.endpoint({
|
|
787
|
-
method: 'POST',
|
|
788
|
-
path: '/get_resource',
|
|
789
|
-
handler: (_p) => __awaiter(this, [_p], void 0, function* ({ body, adminUser }) {
|
|
790
|
-
const { resourceId } = body;
|
|
791
|
-
if (!this.statuses.dbDiscover) {
|
|
792
|
-
return { error: 'Database discovery not started' };
|
|
793
|
-
}
|
|
794
|
-
if (this.statuses.dbDiscover !== 'done') {
|
|
795
|
-
return { error: 'Database discovery is still in progress, please try later' };
|
|
796
|
-
}
|
|
797
|
-
const resource = this.config.resources.find((res) => res.resourceId == resourceId);
|
|
798
|
-
if (!resource) {
|
|
799
|
-
return { error: `Resource ${resourceId} not found` };
|
|
800
|
-
}
|
|
801
|
-
const { allowedActions } = yield interpretResource(adminUser, resource, {}, ActionCheckSource.DisplayButtons);
|
|
802
|
-
// exclude "plugins" key
|
|
803
|
-
return {
|
|
804
|
-
resource: Object.assign(Object.assign({}, resource), { plugins: undefined, options: Object.assign(Object.assign({}, resource.options), { allowedActions }) })
|
|
805
|
-
};
|
|
806
|
-
}),
|
|
807
|
-
});
|
|
808
|
-
server.endpoint({
|
|
809
|
-
method: 'POST',
|
|
810
|
-
path: '/get_resource_data',
|
|
811
|
-
handler: (_q) => __awaiter(this, [_q], void 0, function* ({ body, adminUser }) {
|
|
812
|
-
var _r, _s, _t, _u;
|
|
813
|
-
const { resourceId, source } = body;
|
|
814
|
-
if (['show', 'list'].includes(source) === false) {
|
|
815
|
-
return { error: 'Invalid source, should be list or show' };
|
|
816
|
-
}
|
|
817
|
-
if (!this.statuses.dbDiscover) {
|
|
818
|
-
return { error: 'Database discovery not started' };
|
|
819
|
-
}
|
|
820
|
-
if (this.statuses.dbDiscover !== 'done') {
|
|
821
|
-
return { error: 'Database discovery is still in progress, please try later' };
|
|
822
|
-
}
|
|
823
|
-
const resource = this.config.resources.find((res) => res.resourceId == resourceId);
|
|
824
|
-
if (!resource) {
|
|
825
|
-
return { error: `Resource ${resourceId} not found` };
|
|
826
|
-
}
|
|
827
|
-
const { allowedActions } = yield interpretResource(adminUser, resource, { requestBody: body }, ActionCheckSource.DisplayButtons);
|
|
828
|
-
const { allowed, error } = checkAccess(source, allowedActions);
|
|
829
|
-
if (!allowed) {
|
|
830
|
-
return { error };
|
|
831
|
-
}
|
|
832
|
-
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)) {
|
|
833
|
-
const resp = yield hook({ resource, query: body, adminUser });
|
|
834
|
-
if (!resp || (!resp.ok && !resp.error)) {
|
|
835
|
-
throw new Error(`Hook must return object with {ok: true} or { error: 'Error' } `);
|
|
836
|
-
}
|
|
837
|
-
if (resp.error) {
|
|
838
|
-
return { error: resp.error };
|
|
839
|
-
}
|
|
840
|
-
}
|
|
841
|
-
const { limit, offset, filters, sort } = body;
|
|
842
|
-
for (const filter of (filters || [])) {
|
|
843
|
-
if (!Object.values(AdminForthFilterOperators).includes(filter.operator)) {
|
|
844
|
-
throw new Error(`Operator '${filter.operator}' is not allowed`);
|
|
845
|
-
}
|
|
846
|
-
if (!resource.columns.some((col) => col.name === filter.field)) {
|
|
847
|
-
throw new Error(`Field '${filter.field}' is not in resource '${resource.resourceId}'. Available fields: ${resource.columns.map((col) => col.name).join(', ')}`);
|
|
848
|
-
}
|
|
849
|
-
if (filter.operator === AdminForthFilterOperators.IN || filter.operator === AdminForthFilterOperators.NIN) {
|
|
850
|
-
if (!Array.isArray(filter.value)) {
|
|
851
|
-
throw new Error(`Value for operator '${filter.operator}' should be an array`);
|
|
852
|
-
}
|
|
853
|
-
}
|
|
854
|
-
if (filter.operator === AdminForthFilterOperators.IN && filter.value.length === 0) {
|
|
855
|
-
// nonsense
|
|
856
|
-
return { data: [], total: 0 };
|
|
857
|
-
}
|
|
858
|
-
}
|
|
859
|
-
const data = yield this.connectors[resource.dataSource].getData({
|
|
860
|
-
resource,
|
|
861
|
-
limit,
|
|
862
|
-
offset,
|
|
863
|
-
filters,
|
|
864
|
-
sort,
|
|
865
|
-
});
|
|
866
|
-
// for foreign keys, add references
|
|
867
|
-
yield Promise.all(resource.columns.filter((col) => col.foreignResource).map((col) => __awaiter(this, void 0, void 0, function* () {
|
|
868
|
-
const targetResource = this.config.resources.find((res) => res.resourceId == col.foreignResource.resourceId);
|
|
869
|
-
const targetConnector = this.connectors[targetResource.dataSource];
|
|
870
|
-
const targetResourcePkField = targetResource.columns.find((col) => col.primaryKey).name;
|
|
871
|
-
const pksUnique = [...new Set(data.data.map((item) => item[col.name]))];
|
|
872
|
-
if (pksUnique.length === 0) {
|
|
873
|
-
return;
|
|
874
|
-
}
|
|
875
|
-
const targetData = yield targetConnector.getData({
|
|
876
|
-
resource: targetResource,
|
|
877
|
-
limit: limit,
|
|
878
|
-
offset: 0,
|
|
879
|
-
filters: [
|
|
880
|
-
{
|
|
881
|
-
field: targetResourcePkField,
|
|
882
|
-
operator: AdminForthFilterOperators.IN,
|
|
883
|
-
value: pksUnique,
|
|
884
|
-
}
|
|
885
|
-
],
|
|
886
|
-
sort: [],
|
|
887
|
-
});
|
|
888
|
-
const targetDataMap = targetData.data.reduce((acc, item) => {
|
|
889
|
-
acc[item[targetResourcePkField]] = {
|
|
890
|
-
label: targetResource.recordLabel(item),
|
|
891
|
-
pk: item[targetResourcePkField],
|
|
892
|
-
};
|
|
893
|
-
return acc;
|
|
894
|
-
}, {});
|
|
895
|
-
data.data.forEach((item) => {
|
|
896
|
-
item[col.name] = targetDataMap[item[col.name]];
|
|
897
|
-
});
|
|
898
|
-
})));
|
|
899
|
-
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)) {
|
|
900
|
-
const resp = yield hook({ resource, response: data.data, adminUser });
|
|
901
|
-
if (!resp || (!resp.ok && !resp.error)) {
|
|
902
|
-
throw new Error(`Hook must return object with {ok: true} or { error: 'Error' } `);
|
|
903
|
-
}
|
|
904
|
-
if (resp.error) {
|
|
905
|
-
return { error: resp.error };
|
|
906
|
-
}
|
|
907
|
-
}
|
|
908
|
-
// remove all columns which are not defined in resources, or defined but backendOnly
|
|
909
|
-
data.data.forEach((item) => {
|
|
910
|
-
Object.keys(item).forEach((key) => {
|
|
911
|
-
if (!resource.columns.find((col) => col.name === key) || resource.columns.find((col) => col.name === key && col.backendOnly)) {
|
|
912
|
-
delete item[key];
|
|
913
|
-
}
|
|
914
|
-
});
|
|
915
|
-
});
|
|
916
|
-
data.data.forEach((item) => {
|
|
917
|
-
item._label = resource.recordLabel(item);
|
|
918
|
-
});
|
|
919
|
-
return Object.assign(Object.assign({}, data), { options: resource === null || resource === void 0 ? void 0 : resource.options });
|
|
920
|
-
}),
|
|
921
|
-
});
|
|
922
|
-
server.endpoint({
|
|
923
|
-
method: 'POST',
|
|
924
|
-
path: '/get_resource_foreign_data',
|
|
925
|
-
handler: (_v) => __awaiter(this, [_v], void 0, function* ({ body, adminUser }) {
|
|
926
|
-
var _w, _x, _y, _z;
|
|
927
|
-
const { resourceId, column } = body;
|
|
928
|
-
if (!this.statuses.dbDiscover) {
|
|
929
|
-
return { error: 'Database discovery not started' };
|
|
930
|
-
}
|
|
931
|
-
if (this.statuses.dbDiscover !== 'done') {
|
|
932
|
-
return { error: 'Database discovery is still in progress, please try later' };
|
|
933
|
-
}
|
|
934
|
-
const resource = this.config.resources.find((res) => res.resourceId == resourceId);
|
|
935
|
-
if (!resource) {
|
|
936
|
-
return { error: `Resource '${resourceId}' not found` };
|
|
937
|
-
}
|
|
938
|
-
const columnConfig = resource.columns.find((col) => col.name == column);
|
|
939
|
-
if (!columnConfig) {
|
|
940
|
-
return { error: `Column "${column}' not found in resource with resourceId '${resourceId}'` };
|
|
941
|
-
}
|
|
942
|
-
if (!columnConfig.foreignResource) {
|
|
943
|
-
return { error: `Column '${column}' in resource '${resourceId}' is not a foreign key` };
|
|
944
|
-
}
|
|
945
|
-
const targetResourceId = columnConfig.foreignResource.resourceId;
|
|
946
|
-
const targetResource = this.config.resources.find((res) => res.resourceId == targetResourceId);
|
|
947
|
-
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)) {
|
|
948
|
-
const resp = yield hook({ query: body, adminUser, resource: targetResource });
|
|
949
|
-
if (!resp || (!resp.ok && !resp.error)) {
|
|
950
|
-
throw new Error(`Hook must return object with {ok: true} or { error: 'Error' } `);
|
|
951
|
-
}
|
|
952
|
-
if (resp.error) {
|
|
953
|
-
return { error: resp.error };
|
|
954
|
-
}
|
|
955
|
-
}
|
|
956
|
-
const { limit, offset, filters, sort } = body;
|
|
957
|
-
const dbDataItems = yield this.connectors[targetResource.dataSource].getData({
|
|
958
|
-
resource: targetResource,
|
|
959
|
-
limit,
|
|
960
|
-
offset,
|
|
961
|
-
filters: filters || [],
|
|
962
|
-
sort: sort || [],
|
|
963
|
-
});
|
|
964
|
-
const items = dbDataItems.data.map((item) => {
|
|
965
|
-
const pk = item[targetResource.columns.find((col) => col.primaryKey).name];
|
|
966
|
-
const labler = targetResource.recordLabel;
|
|
967
|
-
return {
|
|
968
|
-
value: pk,
|
|
969
|
-
label: labler(item),
|
|
970
|
-
_item: item, // user might need it in hook to form new label
|
|
971
|
-
};
|
|
972
|
-
});
|
|
973
|
-
const response = {
|
|
974
|
-
items
|
|
975
|
-
};
|
|
976
|
-
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)) {
|
|
977
|
-
const resp = yield hook({ response, adminUser, resource: targetResource });
|
|
978
|
-
if (!resp || (!resp.ok && !resp.error)) {
|
|
979
|
-
throw new Error(`Hook must return object with {ok: true} or { error: 'Error' } `);
|
|
980
|
-
}
|
|
981
|
-
if (resp.error) {
|
|
982
|
-
return { error: resp.error };
|
|
983
|
-
}
|
|
984
|
-
}
|
|
985
|
-
return response;
|
|
986
|
-
}),
|
|
987
|
-
});
|
|
988
|
-
server.endpoint({
|
|
989
|
-
method: 'POST',
|
|
990
|
-
path: '/get_min_max_for_columns',
|
|
991
|
-
handler: (_0) => __awaiter(this, [_0], void 0, function* ({ body }) {
|
|
992
|
-
const { resourceId } = body;
|
|
993
|
-
if (!this.statuses.dbDiscover) {
|
|
994
|
-
return { error: 'Database discovery not started' };
|
|
995
|
-
}
|
|
996
|
-
if (this.statuses.dbDiscover !== 'done') {
|
|
997
|
-
return { error: 'Database discovery is still in progress, please try later' };
|
|
998
|
-
}
|
|
999
|
-
const resource = this.config.resources.find((res) => res.resourceId == resourceId);
|
|
1000
|
-
if (!resource) {
|
|
1001
|
-
return { error: `Resource '${resourceId}' not found` };
|
|
1002
|
-
}
|
|
1003
|
-
const item = yield this.connectors[resource.dataSource].getMinMaxForColumns({
|
|
1004
|
-
resource,
|
|
1005
|
-
columns: resource.columns.filter((col) => [
|
|
1006
|
-
AdminForthDataTypes.INTEGER,
|
|
1007
|
-
AdminForthDataTypes.FLOAT,
|
|
1008
|
-
AdminForthDataTypes.DATE,
|
|
1009
|
-
AdminForthDataTypes.DATETIME,
|
|
1010
|
-
AdminForthDataTypes.TIME,
|
|
1011
|
-
AdminForthDataTypes.DECIMAL,
|
|
1012
|
-
].includes(col.type) && col.allowMinMaxQuery === true),
|
|
1013
|
-
});
|
|
1014
|
-
return item;
|
|
1015
|
-
}),
|
|
1016
|
-
});
|
|
1017
|
-
server.endpoint({
|
|
1018
|
-
method: 'POST',
|
|
1019
|
-
path: '/create_record',
|
|
1020
|
-
handler: (_1) => __awaiter(this, [_1], void 0, function* ({ body, adminUser }) {
|
|
1021
|
-
const resource = this.config.resources.find((res) => res.resourceId == body['resourceId']);
|
|
1022
|
-
if (!resource) {
|
|
1023
|
-
return { error: `Resource '${body['resourceId']}' not found` };
|
|
1024
|
-
}
|
|
1025
|
-
const { allowedActions } = yield interpretResource(adminUser, resource, { requestBody: body }, ActionCheckSource.CreateRequest);
|
|
1026
|
-
const { allowed, error } = checkAccess(AllowedActionsEnum.create, allowedActions);
|
|
1027
|
-
if (!allowed) {
|
|
1028
|
-
return { error };
|
|
1029
|
-
}
|
|
1030
|
-
const { record } = body;
|
|
1031
|
-
const response = yield this.createResourceRecord({ resource, record, adminUser });
|
|
1032
|
-
if (response.error) {
|
|
1033
|
-
return { error: response.error };
|
|
1034
|
-
}
|
|
1035
|
-
const connector = this.connectors[resource.dataSource];
|
|
1036
|
-
return {
|
|
1037
|
-
newRecordId: record[connector.getPrimaryKey(resource)]
|
|
1038
|
-
};
|
|
1039
|
-
})
|
|
1040
|
-
});
|
|
1041
|
-
server.endpoint({
|
|
1042
|
-
method: 'POST',
|
|
1043
|
-
path: '/update_record',
|
|
1044
|
-
handler: (_2) => __awaiter(this, [_2], void 0, function* ({ body, adminUser }) {
|
|
1045
|
-
var _3, _4, _5, _6;
|
|
1046
|
-
const resource = this.config.resources.find((res) => res.resourceId == body['resourceId']);
|
|
1047
|
-
if (!resource) {
|
|
1048
|
-
return { error: `Resource '${body['resourceId']}' not found` };
|
|
1049
|
-
}
|
|
1050
|
-
const recordId = body['recordId'];
|
|
1051
|
-
const connector = this.connectors[resource.dataSource];
|
|
1052
|
-
const oldRecord = yield connector.getRecordByPrimaryKey(resource, recordId);
|
|
1053
|
-
if (!oldRecord) {
|
|
1054
|
-
const primaryKeyColumn = resource.columns.find((col) => col.primaryKey);
|
|
1055
|
-
return { error: `Record with ${primaryKeyColumn.name} ${recordId} not found` };
|
|
1056
|
-
}
|
|
1057
|
-
const record = body['record'];
|
|
1058
|
-
const { allowedActions } = yield interpretResource(adminUser, resource, { requestBody: body, newRecord: record, oldRecord }, ActionCheckSource.EditRequest);
|
|
1059
|
-
const { allowed, error } = checkAccess(AllowedActionsEnum.edit, allowedActions);
|
|
1060
|
-
if (!allowed) {
|
|
1061
|
-
return { error };
|
|
1062
|
-
}
|
|
1063
|
-
// execute hook if needed
|
|
1064
|
-
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)) {
|
|
1065
|
-
const resp = yield hook({ resource, record, adminUser });
|
|
1066
|
-
if (!resp || (!resp.ok && !resp.error)) {
|
|
1067
|
-
throw new Error(`Hook beforeSave must return object with {ok: true} or { error: 'Error' } `);
|
|
1068
|
-
}
|
|
1069
|
-
if (resp.error) {
|
|
1070
|
-
return { error: resp.error };
|
|
1071
|
-
}
|
|
1072
|
-
}
|
|
1073
|
-
const newValues = {};
|
|
1074
|
-
for (const recordField in record) {
|
|
1075
|
-
if (record[recordField] !== oldRecord[recordField]) {
|
|
1076
|
-
const column = resource.columns.find((col) => col.name === recordField);
|
|
1077
|
-
if (column) {
|
|
1078
|
-
if (!column.virtual) {
|
|
1079
|
-
newValues[recordField] = connector.setFieldValue(column, record[recordField]);
|
|
1080
|
-
}
|
|
1081
|
-
}
|
|
1082
|
-
else {
|
|
1083
|
-
newValues[recordField] = record[recordField];
|
|
1084
|
-
}
|
|
1085
|
-
}
|
|
1086
|
-
}
|
|
1087
|
-
if (Object.keys(newValues).length > 0) {
|
|
1088
|
-
yield connector.updateRecord({ resource, recordId, newValues });
|
|
1089
|
-
}
|
|
1090
|
-
// execute hook if needed
|
|
1091
|
-
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)) {
|
|
1092
|
-
const resp = yield hook({ resource, record, adminUser, oldRecord });
|
|
1093
|
-
if (!resp || (!resp.ok && !resp.error)) {
|
|
1094
|
-
throw new Error(`Hook afterSave must return object with {ok: true} or { error: 'Error' } `);
|
|
1095
|
-
}
|
|
1096
|
-
if (resp.error) {
|
|
1097
|
-
return { error: resp.error };
|
|
1098
|
-
}
|
|
1099
|
-
}
|
|
1100
|
-
return {
|
|
1101
|
-
newRecordId: recordId
|
|
1102
|
-
};
|
|
1103
|
-
})
|
|
1104
|
-
});
|
|
1105
|
-
server.endpoint({
|
|
1106
|
-
method: 'POST',
|
|
1107
|
-
path: '/delete_record',
|
|
1108
|
-
handler: (_7) => __awaiter(this, [_7], void 0, function* ({ body, adminUser }) {
|
|
1109
|
-
var _8, _9, _10, _11;
|
|
1110
|
-
const resource = this.config.resources.find((res) => res.resourceId == body['resourceId']);
|
|
1111
|
-
const record = yield this.connectors[resource.dataSource].getRecordByPrimaryKey(resource, body['primaryKey']);
|
|
1112
|
-
if (!resource) {
|
|
1113
|
-
return { error: `Resource '${body['resourceId']}' not found` };
|
|
1114
|
-
}
|
|
1115
|
-
if (!record) {
|
|
1116
|
-
return { error: `Record with ${body['primaryKey']} not found` };
|
|
1117
|
-
}
|
|
1118
|
-
if (resource.options.allowedActions.delete === false) {
|
|
1119
|
-
return { error: `Resource '${resource.resourceId}' does not allow delete action` };
|
|
1120
|
-
}
|
|
1121
|
-
const { allowedActions } = yield interpretResource(adminUser, resource, { requestBody: body }, ActionCheckSource.DeleteRequest);
|
|
1122
|
-
const { allowed, error } = checkAccess(AllowedActionsEnum.delete, allowedActions);
|
|
1123
|
-
if (!allowed) {
|
|
1124
|
-
return { error };
|
|
1125
|
-
}
|
|
1126
|
-
// execute hook if needed
|
|
1127
|
-
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)) {
|
|
1128
|
-
const resp = yield hook({ resource, record, adminUser });
|
|
1129
|
-
if (!resp || (!resp.ok && !resp.error)) {
|
|
1130
|
-
throw new Error(`Hook beforeSave must return object with {ok: true} or { error: 'Error' } `);
|
|
1131
|
-
}
|
|
1132
|
-
if (resp.error) {
|
|
1133
|
-
return { error: resp.error };
|
|
1134
|
-
}
|
|
1135
|
-
}
|
|
1136
|
-
const connector = this.connectors[resource.dataSource];
|
|
1137
|
-
yield connector.deleteRecord({ resource, recordId: body['primaryKey'] });
|
|
1138
|
-
// execute hook if needed
|
|
1139
|
-
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)) {
|
|
1140
|
-
const resp = yield hook({ resource, record, adminUser });
|
|
1141
|
-
if (!resp || (!resp.ok && !resp.error)) {
|
|
1142
|
-
throw new Error(`Hook afterSave must return object with {ok: true} or { error: 'Error' } `);
|
|
1143
|
-
}
|
|
1144
|
-
if (resp.error) {
|
|
1145
|
-
return { error: resp.error };
|
|
1146
|
-
}
|
|
1147
|
-
}
|
|
1148
|
-
return {
|
|
1149
|
-
recordId: body['primaryKey']
|
|
1150
|
-
};
|
|
1151
|
-
})
|
|
1152
|
-
});
|
|
1153
|
-
server.endpoint({
|
|
1154
|
-
method: 'POST',
|
|
1155
|
-
path: '/start_bulk_action',
|
|
1156
|
-
handler: (_12) => __awaiter(this, [_12], void 0, function* ({ body }) {
|
|
1157
|
-
const { resourceId, actionId, recordIds } = body;
|
|
1158
|
-
const resource = this.config.resources.find((res) => res.resourceId == resourceId);
|
|
1159
|
-
if (!resource) {
|
|
1160
|
-
return { error: `Resource '${resourceId}' not found` };
|
|
1161
|
-
}
|
|
1162
|
-
const action = resource.options.bulkActions.find((act) => act.id == actionId);
|
|
1163
|
-
if (!action) {
|
|
1164
|
-
return { error: `Action '${actionId}' not found` };
|
|
1165
|
-
}
|
|
1166
|
-
else {
|
|
1167
|
-
yield action.action({ selectedIds: recordIds });
|
|
1168
|
-
}
|
|
1169
|
-
return {
|
|
1170
|
-
actionId,
|
|
1171
|
-
recordIds,
|
|
1172
|
-
resourceId,
|
|
1173
|
-
status: 'success'
|
|
1174
|
-
};
|
|
1175
|
-
})
|
|
1176
|
-
});
|
|
1177
|
-
// setup endpoints for all plugins
|
|
1178
|
-
this.activatedPlugins.forEach((plugin) => {
|
|
1179
|
-
plugin.setupEndpoints(server);
|
|
1180
|
-
});
|
|
191
|
+
this.restApi.registerEndpoints(server);
|
|
1181
192
|
}
|
|
1182
193
|
}
|
|
1183
194
|
_a = AdminForth, _AdminForth_defaultConfig = new WeakMap();
|