-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathrestApi.ts
More file actions
1686 lines (1544 loc) · 69.2 KB
/
restApi.ts
File metadata and controls
1686 lines (1544 loc) · 69.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
type IAdminForth,
type IHttpServer,
BeforeLoginConfirmationFunction,
AdminForthResource,
AllowedActionValue,
AllowedActions,
AfterDataSourceResponseFunction,
BeforeDataSourceRequestFunction,
IAdminForthRestAPI,
IAdminForthSort,
HttpExtra,
IAdminForthAndOrFilter,
BackendOnlyInput,
Filters,
} from "../types/Back.js";
import {cascadeChildrenDelete} from './utils.js'
import { afLogger } from "./logger.js";
import { ADMINFORTH_VERSION, listify, md5hash, getLoginPromptHTML, hookResponseError } from './utils.js';
import AdminForthAuth from "../auth.js";
import { ActionCheckSource, AdminForthConfigMenuItem, AdminForthDataTypes, AdminForthFilterOperators, AdminForthResourceColumnInputCommon, AdminForthResourceCommon, AdminForthResourcePages,
AdminUser, AllowedActionsEnum, AllowedActionsResolved,
AnnouncementBadgeResponse,
GetBaseConfigResponse,
ShowInResolved} from "../types/Common.js";
import { filtersTools } from "../modules/filtersTools.js";
import is_ip_private from 'private-ip'
async function resolveBoolOrFn(
val: BackendOnlyInput | undefined,
ctx: {
adminUser: AdminUser;
resource: AdminForthResource;
meta: any;
source: ActionCheckSource;
adminforth: IAdminForth;
}
): Promise<boolean> {
if (typeof val === 'function') {
return !!(await (val)(ctx));
}
return !!val;
}
async function isBackendOnly(
col: AdminForthResource['columns'][number],
ctx: {
adminUser: AdminUser;
resource: AdminForthResource;
meta: any;
source: ActionCheckSource;
adminforth: IAdminForth;
}
): Promise<boolean> {
return await resolveBoolOrFn(col.backendOnly, ctx);
}
async function isShown(
col: AdminForthResource['columns'][number],
page: 'list' | 'show' | 'edit' | 'create' | 'filter',
ctx: Parameters<typeof isBackendOnly>[1]
): Promise<boolean> {
const s = (col.showIn as any) || {};
if (s[page] !== undefined) return await resolveBoolOrFn(s[page], ctx);
if (s.all !== undefined) return await resolveBoolOrFn(s.all, ctx);
return true;
}
async function isFilledOnCreate( col: AdminForthResource['columns'][number] ): Promise<boolean> {
const fillOnCreate = !!col.fillOnCreate;
return fillOnCreate;
}
export async function interpretResource(
adminUser: AdminUser,
resource: AdminForthResource,
meta: any,
source: ActionCheckSource,
adminforth: IAdminForth
): Promise<{allowedActions: AllowedActionsResolved}> {
afLogger.trace(`🪲Interpreting resource, ${resource.resourceId}, ${source}, 'adminUser', ${adminUser}`);
const allowedActions = {} as AllowedActionsResolved;
// we need to compute only allowed actions for this source:
// 'show' needed for ActionCheckSource.showRequest and ActionCheckSource.editLoadRequest and ActionCheckSource.displayButtons
// 'edit' needed for ActionCheckSource.editRequest and ActionCheckSource.displayButtons
// 'delete' needed for ActionCheckSource.deleteRequest and ActionCheckSource.displayButtons and ActionCheckSource.bulkActionRequest
// 'list' needed for ActionCheckSource.listRequest
// 'create' needed for ActionCheckSource.createRequest and ActionCheckSource.displayButtons
// for bulk actions we need to check all actions because bulk action can use any of them e.g sync allowed with edit
const neededActions = {
[ActionCheckSource.ShowRequest]: ['show'],
[ActionCheckSource.EditRequest]: ['edit'],
[ActionCheckSource.EditLoadRequest]: ['show'],
[ActionCheckSource.DeleteRequest]: ['delete'],
[ActionCheckSource.ListRequest]: ['list'],
[ActionCheckSource.CreateRequest]: ['create'],
[ActionCheckSource.DisplayButtons]: ['show', 'edit', 'delete', 'create', 'filter'],
[ActionCheckSource.BulkActionRequest]: ['show', 'edit', 'delete', 'create', 'filter'],
[ActionCheckSource.CustomActionRequest]: ['show', 'edit', 'delete', 'create', 'filter'],
}[source];
await Promise.all(
Object.entries(resource.options.allowedActions).map(
async ([key, value]: [string, AllowedActionValue]) => {
if (!neededActions.includes(key as AllowedActionsEnum)) {
allowedActions[key] = false;
return;
}
// if callable then call
if (typeof value === 'function') {
allowedActions[key] = await value({ adminUser, resource, meta, source, adminforth });
} else {
allowedActions[key] = value;
}
})
);
return { allowedActions };
}
export default class AdminForthRestAPI implements IAdminForthRestAPI {
adminforth: IAdminForth;
constructor(adminforth: IAdminForth) {
this.adminforth = adminforth;
}
async processLoginCallbacks(adminUser: AdminUser, toReturn: { redirectTo?: string, allowedLogin:boolean, error?: string }, response: any, extra: HttpExtra, sessionDuration?: string) {
const beforeLoginConfirmation = this.adminforth.config.auth.beforeLoginConfirmation as (BeforeLoginConfirmationFunction[] | undefined);
for (const hook of listify(beforeLoginConfirmation)) {
const resp = await hook({
adminUser,
response,
adminforth: this.adminforth,
extra,
sessionDuration,
});
if (resp?.body?.redirectTo || resp?.error) {
// delete all items from toReturn and add these:
toReturn.redirectTo = resp?.body?.redirectTo;
toReturn.allowedLogin = resp?.body?.allowedLogin;
toReturn.error = resp?.error;
break;
}
}
}
checkAbortSignal(abortSignal: AbortSignal): boolean {
if (abortSignal.aborted) {
return true;
}
return false;
}
registerEndpoints(server: IHttpServer) {
server.endpoint({
noAuth: true,
method: 'POST',
path: '/login',
handler: async ({ body, response, headers, query, cookies, requestUrl, tr }) => {
const INVALID_MESSAGE = await tr('Invalid username or password', 'errors');
const { username, password, rememberMe } = body;
let adminUser: AdminUser;
let toReturn: { redirectTo?: string, allowedLogin:boolean, error?: string } = { allowedLogin: true };
// get resource from db
if (!this.adminforth.config.auth) {
throw new Error('No config.auth defined we need it to find user, please follow the docs');
}
const userResource = this.adminforth.config.resources.find((res) => res.resourceId === this.adminforth.config.auth.usersResourceId);
// if there is no passwordHashField, in columns, add it, with backendOnly and showIn: []
if (!userResource.dataSourceColumns.find((col) => col.name === this.adminforth.config.auth.passwordHashField)) {
userResource.dataSourceColumns.push({
name: this.adminforth.config.auth.passwordHashField,
backendOnly: true,
showIn: Object.values(AdminForthResourcePages).reduce((acc, page) => { return { ...acc, [page]: false } }, {} as ShowInResolved),
type: AdminForthDataTypes.STRING,
});
afLogger.info(`Adding passwordHashField to userResource, ${userResource}`);
}
const userRecord = (
await this.adminforth.connectors[userResource.dataSource].getData({
resource: userResource,
filters: { operator: AdminForthFilterOperators.AND, subFilters: [
{ field: this.adminforth.config.auth.usernameField, operator: AdminForthFilterOperators.EQ, value: username },
]},
limit: 1,
offset: 0,
sort: [],
})
).data?.[0];
if (!userRecord) {
return { error: INVALID_MESSAGE };
}
const passwordHash = userRecord[this.adminforth.config.auth.passwordHashField];
const valid = await AdminForthAuth.verifyPassword(password, passwordHash);
if (valid) {
adminUser = {
dbUser: userRecord,
pk: userRecord[userResource.columns.find((col) => col.primaryKey).name],
username,
};
const expireInDuration = rememberMe
? (this.adminforth.config.auth.rememberMeDuration || '30d')
: '1d';
await this.processLoginCallbacks(adminUser, toReturn, response, {
body, headers, query, cookies, requestUrl, response
}, expireInDuration);
if (toReturn.allowedLogin) {
this.adminforth.auth.setAuthCookie({
expireInDuration,
response,
username,
pk: userRecord[userResource.columns.find((col) => col.primaryKey).name]
});
}
} else {
return { error: INVALID_MESSAGE };
}
return toReturn;
}
});
server.endpoint({
method: 'POST',
path: '/check_auth',
handler: async ({ adminUser }) => {
return { ok: true };
},
});
server.endpoint({
noAuth: true,
method: 'POST',
path: '/logout',
handler: async ({ response }) => {
this.adminforth.auth.removeAuthCookie( response );
return { ok: true };
},
})
server.endpoint({
noAuth: true,
method: 'GET',
path: '/get_login_form_config',
handler: async ({ tr }) => {
const loginPromptHTML = await getLoginPromptHTML(this.adminforth.config.auth.loginPromptHTML);
return {
loginPromptHTML: await tr(loginPromptHTML, 'system.loginPromptHTML'),
}
}
})
server.endpoint({
noAuth: true,
method: 'GET',
path: '/get_public_config',
handler: async ({ tr }) => {
// TODO we need to remove this method and make get_config to return public and private parts for logged in user and only public for not logged in
// find resource
if (!this.adminforth.config.auth) {
throw new Error('No config.auth defined');
}
const usernameField = this.adminforth.config.auth.usernameField;
const resource = this.adminforth.config.resources.find((res) => res.resourceId === this.adminforth.config.auth.usersResourceId);
const usernameColumn = resource.columns.find((col) => col.name === usernameField);
return {
brandName: this.adminforth.config.customization.brandName,
usernameFieldName: usernameColumn.label,
loginBackgroundImage: this.adminforth.config.auth.loginBackgroundImage,
loginBackgroundPosition: this.adminforth.config.auth.loginBackgroundPosition,
removeBackgroundBlendMode: this.adminforth.config.auth.removeBackgroundBlendMode,
title: this.adminforth.config.customization?.title,
demoCredentials: this.adminforth.config.auth.demoCredentials,
loginPageInjections: this.adminforth.config.customization.loginPageInjections,
globalInjections: {
everyPageBottom: this.adminforth.config.customization.globalInjections.everyPageBottom,
sidebarTop: this.adminforth.config.customization.globalInjections.sidebarTop,
},
rememberMeDuration: this.adminforth.config.auth.rememberMeDuration,
singleTheme: this.adminforth.config.customization.singleTheme,
customHeadItems: this.adminforth.config.customization.customHeadItems,
};
},
});
server.endpoint({
method: 'GET',
path: '/get_base_config',
handler: async ({input, adminUser, cookies, tr, response}): Promise<GetBaseConfigResponse>=> {
let username = ''
let userFullName = ''
// find resource
if (!this.adminforth.config.auth) {
throw new Error('No config.auth defined');
}
response.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
response.setHeader('Pragma', 'no-cache');
response.setHeader('Expires', '0');
response.setHeader('Surrogate-Control', 'no-store');
const dbUser = adminUser.dbUser;
username = dbUser[this.adminforth.config.auth.usernameField];
userFullName = dbUser[this.adminforth.config.auth.userFullNameField];
const userResource = this.adminforth.config.resources.find((res) => res.resourceId === this.adminforth.config.auth.usersResourceId);
const usernameField = this.adminforth.config.auth.usernameField;
const usernameColumn = userResource.columns.find((col) => col.name === usernameField);
const userPk = dbUser[userResource.columns.find((col) => col.primaryKey).name];
const userAvatarUrl = await this.adminforth.config.auth.avatarUrl?.(adminUser);
const userData = {
[this.adminforth.config.auth.usernameField]: username,
[this.adminforth.config.auth.userFullNameField]: userFullName,
pk: userPk,
userAvatarUrl: userAvatarUrl || null,
};
const checkIsMenuItemVisible = (menuItem) => {
if (typeof menuItem.visible === 'function') {
const toReturn = menuItem.visible( adminUser ); // todo better to use { adminUser } for consistency with allowed actions
if (typeof toReturn !== 'boolean') {
throw new Error(`'visible' function of ${menuItem.label || menuItem.type } must return boolean value`);
}
return toReturn;
}
}
let newMenu = []
for (let menuItem of this.adminforth.config.menu) {
let newMenuItem = {...menuItem,}
if (menuItem.visible){
if (!checkIsMenuItemVisible(menuItem)){
continue
}
}
if (menuItem.children) {
let newChildren = []
for (let child of menuItem.children){
let newChild = {...child,}
if (child.visible){
if (!checkIsMenuItemVisible(child)){
continue
}
}
newChildren.push(newChild)
}
newMenuItem = {...newMenuItem, children: newChildren}
}
newMenu.push(newMenuItem)
}
const announcementBadge: AnnouncementBadgeResponse = this.adminforth.config.customization.announcementBadge?.(adminUser);
const settingPages = []
for ( const settingPage of this.adminforth.config.auth.userMenuSettingsPages || [] ) {
if ( settingPage.isVisible ) {
const isVisible = await settingPage.isVisible( adminUser );
settingPages.push( { ...settingPage, isVisible } );
}
}
let defaultUserExists = false;
if (username === 'adminforth') {
defaultUserExists = true;
}
const publicPart = {
brandName: this.adminforth.config.customization.brandName,
usernameFieldName: usernameColumn.label,
loginBackgroundImage: this.adminforth.config.auth.loginBackgroundImage,
loginBackgroundPosition: this.adminforth.config.auth.loginBackgroundPosition,
removeBackgroundBlendMode: this.adminforth.config.auth.removeBackgroundBlendMode,
title: this.adminforth.config.customization?.title,
demoCredentials: this.adminforth.config.auth.demoCredentials,
loginPageInjections: this.adminforth.config.customization.loginPageInjections,
rememberMeDuration: this.adminforth.config.auth.rememberMeDuration,
singleTheme: this.adminforth.config.customization.singleTheme,
customHeadItems: this.adminforth.config.customization.customHeadItems,
}
const loggedInPart = {
showBrandNameInSidebar: this.adminforth.config.customization.showBrandNameInSidebar,
showBrandLogoInSidebar: this.adminforth.config.customization.showBrandLogoInSidebar,
brandLogo: this.adminforth.config.customization.brandLogo,
iconOnlySidebar: this.adminforth.config.customization.iconOnlySidebar,
datesFormat: this.adminforth.config.customization.datesFormat,
timeFormat: this.adminforth.config.customization.timeFormat,
auth: this.adminforth.config.auth,
usernameField: this.adminforth.config.auth.usernameField,
title: this.adminforth.config.customization.title,
emptyFieldPlaceholder: this.adminforth.config.customization.emptyFieldPlaceholder,
announcementBadge,
globalInjections: this.adminforth.config.customization.globalInjections,
userFullnameField: this.adminforth.config.auth.userFullNameField,
settingPages: settingPages,
defaultUserExists: defaultUserExists,
}
// translate menu labels
const translateRoutines: Promise<void>[] = [];
const processItem = (menuItem) => {
if (menuItem.label) {
translateRoutines.push(
(async () => {
menuItem.label = await tr(menuItem.label, `menu.${menuItem.itemId}`);
})()
);
}
if (menuItem.badgeTooltip) {
translateRoutines.push(
(async () => {
menuItem.badgeTooltip = await tr(menuItem.badgeTooltip, `menu.${menuItem.itemId}`);
})()
);
}
if (menuItem.children) {
menuItem.children.forEach(processItem);
}
if (menuItem.pageLabel) {
translateRoutines.push(
(async () => {
menuItem.pageLabel = await tr(menuItem.pageLabel, `UserMenu.${menuItem.pageLabel}`);
})()
);
}
}
newMenu.forEach((menuItem) => {
processItem(menuItem);
});
if( this.adminforth.config.auth.userMenuSettingsPages) {
this.adminforth.config.auth.userMenuSettingsPages.forEach((page) => {
processItem(page);
});
}
await Promise.all(translateRoutines);
// strip all backendOnly fields or not described in adminForth fields from dbUser
// (when user defines column and does not set backendOnly, we assume it is not backendOnly)
const ctx = {
adminUser,
resource: userResource,
meta: {},
source: ActionCheckSource.ShowRequest,
adminforth: this.adminforth,
};
for (const key of Object.keys(adminUser.dbUser)) {
const col = userResource.columns.find((c) => c.name === key);
const bo = col ? await isBackendOnly(col, ctx) : true;
if (!col || bo) {
delete adminUser.dbUser[key];
}
}
return {
user: userData,
resources: this.adminforth.config.resources.map((res) => ({
resourceId: res.resourceId,
label: res.label,
})),
menu: newMenu,
config: {
...publicPart,
...loggedInPart,
},
adminUser,
version: ADMINFORTH_VERSION,
};
},
});
server.endpoint({
method: 'GET',
path: '/get_menu_badges',
handler: async ({ adminUser }) => {
const badges = {};
const badgeFunctions = [];
const adminforth = this.adminforth;
function processMenuItem(menuItem) {
if (menuItem.badge) {
if (typeof menuItem.badge === 'function') {
badgeFunctions.push(async () => {
badges[menuItem.itemId] = await menuItem.badge(adminUser, adminforth);
});
} else {
badges[menuItem.itemId] = menuItem.badge;
}
}
if (menuItem.children) {
menuItem.children.forEach(processMenuItem);
}
}
this.adminforth.config.menu.map((menuItem) => {
processMenuItem(menuItem)
})
await Promise.all(badgeFunctions.map((fn) => fn()));
return badges;
}
});
function checkAccess(action: AllowedActionsEnum, allowedActions: AllowedActions): { allowed: boolean, error?: string } {
const allowed = (allowedActions[action] as boolean | string | undefined);
if (allowed !== true) {
return { error: typeof allowed === 'string' ? allowed : 'Action is not allowed', allowed: false };
}
return { allowed: true };
}
server.endpoint({
method: 'POST',
path: '/get_resource',
handler: async ({ body, adminUser, tr }): Promise<{ resource?: AdminForthResourceCommon, error?: string }> => {
const { resourceId } = body;
if (!this.adminforth.statuses.dbDiscover) {
return { error: 'Database discovery not started' };
}
if (this.adminforth.statuses.dbDiscover !== 'done') {
return { error : 'Database discovery is still in progress, please try later' };
}
const resource = this.adminforth.config.resources.find((res) => res.resourceId == resourceId);
if (!resource) {
return { error: `Resource ${resourceId} not found` };
}
const { allowedActions } = await interpretResource(adminUser, resource, {}, ActionCheckSource.DisplayButtons, this.adminforth);
const allowedBulkActions = [];
await Promise.all(
resource.options.bulkActions.map(async (action) => {
if (action.allowed) {
const res = await action.allowed({ adminUser, resource, allowedActions });
if (res) {
allowedBulkActions.push(action);
}
} else {
allowedBulkActions.push(action);
}
})
);
// translate
const translateRoutines: Record<string, Promise<string>> = {};
translateRoutines.resLabel = tr(resource.label, `resource.${resource.resourceId}`);
resource.columns.forEach((col, i) => {
translateRoutines[`resCol${i}`] = tr(col.label, `resource.${resource.resourceId}`);
})
allowedBulkActions.forEach((action, i) => {
if (action.label) {
translateRoutines[`bulkAction${i}`] = tr(action.label, `resource.${resource.resourceId}`);
}
if (action.confirm) {
translateRoutines[`bulkActionConfirm${i}`] = tr(action.confirm, `resource.${resource.resourceId}`);
}
});
if (resource.options.fieldGroups) {
resource.options.fieldGroups.forEach((group, i) => {
if (group.groupName) {
translateRoutines[`fieldGroup${i}`] = tr(group.groupName, `resource.${resource.resourceId}.fieldGroup`);
}
});
}
const translated: Record<string, string> = {};
await Promise.all(
Object.entries(translateRoutines).map(async ([key, value]) => {
translated[key] = await value;
})
);
const toReturn = {
...resource,
label: translated.resLabel,
columns:
await Promise.all(
resource.columns.map(
async (inCol, i) => {
const col = JSON.parse(JSON.stringify(inCol));
let validation = null;
if (col.validation) {
validation = await Promise.all(
col.validation.map(async (val, index) => {
return {
...val,
validator: inCol.validation[index].validator ? true: false,
message: await tr(val.message, `resource.${resource.resourceId}`),
}
})
);
}
let enumItems = undefined;
if (col.enum) {
enumItems = await Promise.all(
col.enum.map(async (item) => {
return {
...item,
label: await tr(item.label, `resource.${resource.resourceId}.enum.${col.name}`),
}
})
);
}
const showIn = {} as ShowInResolved;
await Promise.all(
Object.entries(inCol.showIn).map(
async ([key, value]: [string, AllowedActionValue]) => {
// if callable then call
if (typeof value === 'function') {
showIn[key] = await value({ adminUser, resource, meta: {}, source: ActionCheckSource.DisplayButtons, adminforth: this.adminforth });
} else {
showIn[key] = value;
}
})
);
// TODO: better to move all coroutines to translationRoutines
if (col.editingNote?.create) {
col.editingNote.create = await tr(col.editingNote.create, `resource.${resource.resourceId}.editingNote`);
}
if (col.editingNote?.edit) {
col.editingNote.edit = await tr(col.editingNote.edit, `resource.${resource.resourceId}.editingNote`);
}
if (col.foreignResource?.unsetLabel) {
col.foreignResource.unsetLabel = await tr(col.foreignResource.unsetLabel, `resource.${resource.resourceId}.foreignResource.unsetLabel`);
}
if (inCol.suggestOnCreate && typeof inCol.suggestOnCreate === 'function') {
col.suggestOnCreate = await inCol.suggestOnCreate(adminUser);
}
return {
...col,
showIn,
validation,
label: translated[`resCol${i}`],
enum: enumItems,
}
}
),
),
options: {
...resource.options,
fieldGroups: resource.options.fieldGroups?.map((group, i) => ({
...group,
noTitle: group.noTitle ?? false,
groupName: translated[`fieldGroup${i}`] || group.groupName,
})),
bulkActions: allowedBulkActions.map(
(action, i) => ({
...action,
label: action.label ? translated[`bulkAction${i}`] : action.label,
confirm: action.confirm ? translated[`bulkActionConfirm${i}`] : action.confirm,
})
),
actions: resource.options.actions?.map((action) => ({
...action,
hasBulkHandler: !!action.bulkHandler,
bulkHandler: undefined,
})),
allowedActions,
}
}
delete toReturn.hooks;
delete toReturn.plugins;
return {
resource: toReturn,
};
},
});
server.endpoint({
method: 'POST',
path: '/get_resource_data',
handler: async ({ body, adminUser, headers, query, cookies, requestUrl, abortSignal }) => {
const { resourceId, source } = body;
if (['show', 'list', 'edit'].includes(source) === false) {
return { error: 'Invalid source, should be list or show' };
}
if (!this.adminforth.statuses.dbDiscover) {
return { error: 'Database discovery not started' };
}
if (this.adminforth.statuses.dbDiscover !== 'done') {
return { error : 'Database discovery is still in progress, please try later' };
}
const resource = this.adminforth.config.resources.find((res) => res.resourceId == resourceId);
if (!resource) {
return { error: `Resource ${resourceId} not found` };
}
const meta = { requestBody: body, pk: undefined };
if (source === 'edit' || source === 'show') {
meta.pk = body.filters.find((f) => f.field === resource.columns.find((col) => col.primaryKey).name)?.value;
}
const { allowedActions } = await interpretResource(
adminUser,
resource,
meta,
{
'show': ActionCheckSource.ShowRequest,
'list': ActionCheckSource.ListRequest,
'edit': ActionCheckSource.EditLoadRequest,
}[source],
this.adminforth
);
const { allowed, error } = checkAccess({
'show': AllowedActionsEnum.show,
'list': AllowedActionsEnum.list,
'edit': AllowedActionsEnum.show // here we check show, bacuse by convention show request is called for edit
}[source], allowedActions);
if (!allowed) {
return { error };
}
if (this.checkAbortSignal(abortSignal)) { return { error: 'Request aborted' }; }
const hookSource = {
'show': 'show',
'list': 'list',
'edit': 'show',
}[source];
for (const hook of listify(resource.hooks?.[hookSource]?.beforeDatasourceRequest as BeforeDataSourceRequestFunction[])) {
const filterTools = filtersTools.get(body);
body.filtersTools = filterTools;
if (this.checkAbortSignal(abortSignal)) { return { error: 'Request aborted' }; }
const resp = await (hook as BeforeDataSourceRequestFunction)({
resource,
query: body,
adminUser,
filtersTools: filterTools,
extra: {
body, query, headers, cookies, requestUrl
},
adminforth: this.adminforth,
});
const hookRespError = hookResponseError(resp);
if (hookRespError) {
return hookRespError;
}
}
const { limit, offset, filters, sort } = body;
// remove virtual fields from sort if still presented after beforeDatasourceRequest hook
const sortFiltered = sort.filter((sortItem: IAdminForthSort) => {
return !resource.columns.find((col) => col.name === sortItem.field && col.virtual);
});
// after beforeDatasourceRequest hook, filter can be anything
// so, we need to turn it into AndOr filter
// (validation and normalization of individual filters will be done inside getData)
const normalizedFilters = { operator: AdminForthFilterOperators.AND, subFilters: [] };
if (filters) {
if (typeof filters !== 'object') {
throw new Error(`Filter should be an array or an object`);
}
if (Array.isArray(filters)) {
// if filters are an array, they will be connected with "AND" operator by default
normalizedFilters.subFilters = filters;
} else if (filters.field) {
// assume filter is a SingleFilter
normalizedFilters.subFilters = [filters];
} else if (filters.subFilters) {
// assume filter is a AndOr filter
normalizedFilters.operator = filters.operator;
normalizedFilters.subFilters = filters.subFilters;
} else {
// wrong filter
throw new Error(`Wrong filter object value: ${JSON.stringify(filters)}`);
}
}
if (this.checkAbortSignal(abortSignal)) { return { error: 'Request aborted' }; }
const data = await this.adminforth.connectors[resource.dataSource].getData({
resource,
limit,
offset,
filters: normalizedFilters as IAdminForthAndOrFilter,
sort: sortFiltered,
getTotals: source === 'list',
});
// for foreign keys, add references
await Promise.all(
resource.columns.filter((col) => col.foreignResource).map(async (col) => {
let targetDataMap = {};
if (col.foreignResource.resourceId) {
const targetResource = this.adminforth.config.resources.find((res) => res.resourceId == col.foreignResource.resourceId);
const targetConnector = this.adminforth.connectors[targetResource.dataSource];
const targetResourcePkField = targetResource.columns.find((col) => col.primaryKey).name;
const pksUnique = [...new Set(data.data.reduce((pks, item) => {
if (col.isArray?.enabled) {
if (item[col.name]?.length) {
pks = pks.concat(item[col.name]);
}
} else {
pks.push(item[col.name]);
}
return pks;
}, []))];
if (pksUnique.length === 0) {
return;
}
if (this.checkAbortSignal(abortSignal)) { return { error: 'Request aborted' }; }
const targetData = await targetConnector.getData({
resource: targetResource,
limit: pksUnique.length,
offset: 0,
filters: { operator: AdminForthFilterOperators.AND, subFilters: [
{
field: targetResourcePkField,
operator: AdminForthFilterOperators.IN,
value: pksUnique,
}
]},
sort: [],
});
targetDataMap = targetData.data.reduce((acc, item) => {
acc[item[targetResourcePkField]] = {
label: targetResource.recordLabel(item),
pk: item[targetResourcePkField],
}
return acc;
}, {});
} else {
const targetResources = {};
const targetConnectors = {};
const targetResourcePkFields = {};
const pksUniques = {};
col.foreignResource.polymorphicResources.forEach((pr) => {
if (pr.resourceId === null) {
return;
}
const targetResource = this.adminforth.config.resources.find((res) => res.resourceId == pr.resourceId);
if (!targetResource) {
return;
}
targetResources[pr.whenValue] = targetResource;
targetConnectors[pr.whenValue] = this.adminforth.connectors[targetResources[pr.whenValue].dataSource];
targetResourcePkFields[pr.whenValue] = targetResources[pr.whenValue].columns.find((col) => col.primaryKey).name;
const pksUnique = [...new Set(data.data.filter((item) => item[col.foreignResource.polymorphicOn] === pr.whenValue).map((item) => item[col.name]))];
if (pksUnique.length !== 0) {
pksUniques[pr.whenValue] = pksUnique;
}
if (Object.keys(pksUniques).length === 0) {
return;
}
});
if (this.checkAbortSignal(abortSignal)) { return { error: 'Request aborted' }; }
const targetData = (await Promise.all(Object.keys(pksUniques).map((polymorphicOnValue) =>
targetConnectors[polymorphicOnValue].getData({
resource: targetResources[polymorphicOnValue],
limit: limit,
offset: 0,
filters: { operator: AdminForthFilterOperators.AND, subFilters: [
{
field: targetResourcePkFields[polymorphicOnValue],
operator: AdminForthFilterOperators.IN,
value: pksUniques[polymorphicOnValue],
}
]},
sort: [],
})
))).reduce((acc: any, td: any, tdi) => ({
...acc,
[Object.keys(pksUniques)[tdi]]: td,
}), {});
targetDataMap = Object.keys(targetData).reduce((tdAcc, polymorphicOnValue) => ({
...tdAcc,
...targetData[polymorphicOnValue].data.reduce((dAcc, item) => {
dAcc[item[targetResourcePkFields[polymorphicOnValue]]] = {
label: targetResources[polymorphicOnValue].recordLabel(item),
pk: item[targetResourcePkFields[polymorphicOnValue]],
}
return dAcc;
}, {}),
}), {});
}
data.data.forEach((item) => {
// item[col.name] = targetDataMap[item[col.name]];, commented by @Vitalii
if (col.isArray?.enabled) {
if (item[col.name]?.length) {
item[col.name] = item[col.name].map((i) => targetDataMap[i]);
}
} else {
item[col.name] = targetDataMap[item[col.name]];
}
});
})
);
const pkField = resource.columns.find((col) => col.primaryKey)?.name;
// remove all columns which are not defined in resources, or defined but backendOnly
{
const ctx = {
adminUser,
resource,
meta,
source: {
show: ActionCheckSource.ShowRequest,
list: ActionCheckSource.ListRequest,
edit: ActionCheckSource.EditLoadRequest,
}[source],
adminforth: this.adminforth,
};
for (const item of data.data) {
for (const key of Object.keys(item)) {
const col = resource.columns.find((c) => c.name === key);
const bo = col ? await isBackendOnly(col, ctx) : true;
if (!col || bo) {
delete item[key];
}
}
item._label = resource.recordLabel(item);
}
}
if (source === 'list' && resource.options.listTableClickUrl) {
await Promise.all(
data.data.map(async (item) => {
item._clickUrl = await resource.options.listTableClickUrl(item, adminUser, resource);
})
);
}
// only after adminforth made all post processing, give user ability to edit it
for (const hook of listify(resource.hooks?.[hookSource]?.afterDatasourceResponse)) {
if (this.checkAbortSignal(abortSignal)) { return { error: 'Request aborted' }; }
const resp = await hook({
resource,
query: body,
response: data.data,
adminUser,
extra: {
body, query, headers, cookies, requestUrl
},
adminforth: this.adminforth,
});
const hookRespError = hookResponseError(resp);
if (hookRespError) {
return hookRespError;
}
}
return {
...data,
options: resource?.options,
};
},
});
server.endpoint({
method: 'POST',
path: '/get_resource_foreign_data',
handler: async ({ body, adminUser, headers, query, cookies, requestUrl }) => {
const { resourceId, column, search } = body;
if (!this.adminforth.statuses.dbDiscover) {
return { error: 'Database discovery not started' };
}
if (this.adminforth.statuses.dbDiscover !== 'done') {
return { error : 'Database discovery is still in progress, please try later' };
}
const resource = this.adminforth.config.resources.find((res) => res.resourceId == resourceId);
if (!resource) {
return { error: `Resource '${resourceId}' not found` };
}
const columnConfig = resource.columns.find((col) => col.name == column);
if (!columnConfig) {