adminforth 4.19.1 → 4.20.0

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.
Files changed (50) hide show
  1. package/dist/dataConnectors/baseConnector.js +1 -1
  2. package/dist/dataConnectors/baseConnector.js.map +1 -1
  3. package/dist/index.d.ts +24 -8
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +64 -44
  6. package/dist/index.js.map +1 -1
  7. package/dist/modules/columnAccess.d.ts +63 -0
  8. package/dist/modules/columnAccess.d.ts.map +1 -0
  9. package/dist/modules/columnAccess.js +162 -0
  10. package/dist/modules/columnAccess.js.map +1 -0
  11. package/dist/modules/configValidator.d.ts.map +1 -1
  12. package/dist/modules/configValidator.js +15 -34
  13. package/dist/modules/configValidator.js.map +1 -1
  14. package/dist/modules/filterSecurity.d.ts +5 -0
  15. package/dist/modules/filterSecurity.d.ts.map +1 -0
  16. package/dist/modules/filterSecurity.js +20 -0
  17. package/dist/modules/filterSecurity.js.map +1 -0
  18. package/dist/modules/operationalResource.d.ts +19 -4
  19. package/dist/modules/operationalResource.d.ts.map +1 -1
  20. package/dist/modules/operationalResource.js +16 -14
  21. package/dist/modules/operationalResource.js.map +1 -1
  22. package/dist/modules/polymorphicReferences.d.ts +4 -0
  23. package/dist/modules/polymorphicReferences.d.ts.map +1 -0
  24. package/dist/modules/polymorphicReferences.js +45 -0
  25. package/dist/modules/polymorphicReferences.js.map +1 -0
  26. package/dist/modules/recordValidator.d.ts +9 -0
  27. package/dist/modules/recordValidator.d.ts.map +1 -0
  28. package/dist/modules/recordValidator.js +40 -0
  29. package/dist/modules/recordValidator.js.map +1 -0
  30. package/dist/modules/resourceAccess.d.ts +16 -0
  31. package/dist/modules/resourceAccess.d.ts.map +1 -0
  32. package/dist/modules/resourceAccess.js +57 -0
  33. package/dist/modules/resourceAccess.js.map +1 -0
  34. package/dist/modules/restApi.d.ts +3 -8
  35. package/dist/modules/restApi.d.ts.map +1 -1
  36. package/dist/modules/restApi.js +223 -554
  37. package/dist/modules/restApi.js.map +1 -1
  38. package/dist/modules/userScopedResource.d.ts +57 -0
  39. package/dist/modules/userScopedResource.d.ts.map +1 -0
  40. package/dist/modules/userScopedResource.js +309 -0
  41. package/dist/modules/userScopedResource.js.map +1 -0
  42. package/dist/modules/utils.d.ts +17 -2
  43. package/dist/modules/utils.d.ts.map +1 -1
  44. package/dist/modules/utils.js +25 -9
  45. package/dist/modules/utils.js.map +1 -1
  46. package/dist/spa/src/types/Back.ts +84 -2
  47. package/dist/types/Back.d.ts +70 -4
  48. package/dist/types/Back.d.ts.map +1 -1
  49. package/dist/types/Back.js.map +1 -1
  50. package/package.json +1 -1
@@ -10,7 +10,6 @@ var __rest = (this && this.__rest) || function (s, e) {
10
10
  return t;
11
11
  };
12
12
  import { Filters, } from "../types/Back.js";
13
- import { cascadeChildrenDelete } from './utils.js';
14
13
  import { encodeRecordId, isCompositePrimaryKey, primaryKeyColumnNames } from './recordId.js';
15
14
  import { afLogger } from "./logger.js";
16
15
  import { ADMINFORTH_VERSION, listify, getLoginPromptHTML, hookResponseError, parseLooseJson, RateLimiter, checkShowIf } from './utils.js';
@@ -19,27 +18,10 @@ import { ActionCheckSource, AdminForthDataTypes, AdminForthFilterOperators, Admi
19
18
  import { filtersTools } from "../modules/filtersTools.js";
20
19
  import { normalizeColumnValue } from './columnValueNormalizer.js';
21
20
  import { isEmptyColumnValue, runColumnValidators } from './columnValueValidator.js';
22
- async function resolveBoolOrFn(val, ctx) {
23
- if (typeof val === 'function') {
24
- return !!(await (val)(ctx));
25
- }
26
- return !!val;
27
- }
28
- async function isBackendOnly(col, ctx) {
29
- return await resolveBoolOrFn(col.backendOnly, ctx);
30
- }
31
- async function isShown(col, page, ctx) {
32
- const s = col.showIn || {};
33
- if (s[page] !== undefined)
34
- return await resolveBoolOrFn(s[page], ctx);
35
- if (s.all !== undefined)
36
- return await resolveBoolOrFn(s.all, ctx);
37
- return true;
38
- }
39
- async function isFilledOnCreate(col) {
40
- const fillOnCreate = !!col.fillOnCreate;
41
- return fillOnCreate;
42
- }
21
+ import { rejectApiRawFilters } from './filterSecurity.js';
22
+ export { rejectApiRawFilters } from './filterSecurity.js';
23
+ import { filterColumnsReadableError, isShown, sortColumnsReadableError, stripReadForbiddenColumns, } from './columnAccess.js';
24
+ import { authorizeResourceOperation, interpretResource, RESOURCE_ACCESS_GRANT } from './resourceAccess.js';
43
25
  function stripResourceColumnFrontendMeta(column) {
44
26
  const { default: _default, _baseTypeDebug } = column, sanitizedColumn = __rest(column, ["default", "_baseTypeDebug"]);
45
27
  return sanitizedColumn;
@@ -176,55 +158,6 @@ const commonFiltersSchema = {
176
158
  { $ref: '#/$defs/filterNode' },
177
159
  ],
178
160
  };
179
- function hasApiRawFilter(filters) {
180
- if (!filters || typeof filters !== 'object') {
181
- return false;
182
- }
183
- if (Array.isArray(filters)) {
184
- return filters.some(hasApiRawFilter);
185
- }
186
- if (Object.prototype.hasOwnProperty.call(filters, 'insecureRawSQL') ||
187
- Object.prototype.hasOwnProperty.call(filters, 'insecureRawNoSQL')) {
188
- return true;
189
- }
190
- return Array.isArray(filters.subFilters) && filters.subFilters.some(hasApiRawFilter);
191
- }
192
- export function rejectApiRawFilters(filters) {
193
- if (hasApiRawFilter(filters)) {
194
- return { error: 'insecureRawSQL and insecureRawNoSQL filters are not allowed in API requests' };
195
- }
196
- }
197
- /**
198
- * Collects every column name referenced anywhere in a (possibly nested) filter tree,
199
- * so the caller can check those columns against the visibility rules.
200
- */
201
- function collectFilterFields(filters, fields = new Set()) {
202
- if (!filters || typeof filters !== 'object') {
203
- return fields;
204
- }
205
- if (Array.isArray(filters)) {
206
- filters.forEach((filter) => collectFilterFields(filter, fields));
207
- return fields;
208
- }
209
- if (typeof filters.field === 'string') {
210
- fields.add(filters.field);
211
- }
212
- if (typeof filters.rightField === 'string') {
213
- fields.add(filters.rightField);
214
- }
215
- if (Array.isArray(filters.subFilters)) {
216
- filters.subFilters.forEach((filter) => collectFilterFields(filter, fields));
217
- }
218
- return fields;
219
- }
220
- async function rejectBackendOnlyFilters(filters, ctx) {
221
- for (const fieldName of collectFilterFields(filters)) {
222
- const column = ctx.resource.columns.find((col) => col.name === fieldName);
223
- if (column && await isBackendOnly(column, ctx)) {
224
- return { error: `Filter: column "${fieldName}" cannot be used (backendOnly is true).` };
225
- }
226
- }
227
- }
228
161
  function createErrorOrSuccessSchema(successSchema) {
229
162
  return {
230
163
  anyOf: [
@@ -548,42 +481,6 @@ const validateColumnsResponseSchema = createErrorOrSuccessSchema({
548
481
  },
549
482
  additionalProperties: true,
550
483
  });
551
- export async function interpretResource(adminUser, resource, meta, source, adminforth) {
552
- afLogger.trace(`🪲Interpreting resource, ${resource.resourceId}, ${source}, 'adminUser', ${adminUser}`);
553
- const allowedActions = {};
554
- // we need to compute only allowed actions for this source:
555
- // 'show' needed for ActionCheckSource.showRequest and ActionCheckSource.editLoadRequest and ActionCheckSource.displayButtons
556
- // 'edit' needed for ActionCheckSource.editRequest and ActionCheckSource.displayButtons
557
- // 'delete' needed for ActionCheckSource.deleteRequest and ActionCheckSource.displayButtons and ActionCheckSource.bulkActionRequest
558
- // 'list' needed for ActionCheckSource.listRequest
559
- // 'create' needed for ActionCheckSource.createRequest and ActionCheckSource.displayButtons
560
- // for bulk actions we need to check all actions because bulk action can use any of them e.g sync allowed with edit
561
- const neededActions = {
562
- [ActionCheckSource.ShowRequest]: ['show'],
563
- [ActionCheckSource.EditRequest]: ['edit'],
564
- [ActionCheckSource.EditLoadRequest]: ['show'],
565
- [ActionCheckSource.DeleteRequest]: ['delete'],
566
- [ActionCheckSource.ListRequest]: ['list'],
567
- [ActionCheckSource.CreateRequest]: ['create'],
568
- [ActionCheckSource.DisplayButtons]: ['show', 'edit', 'delete', 'create', 'filter'],
569
- [ActionCheckSource.BulkActionRequest]: ['show', 'edit', 'delete', 'create', 'filter'],
570
- [ActionCheckSource.CustomActionRequest]: ['show', 'edit', 'delete', 'create', 'filter'],
571
- }[source];
572
- await Promise.all(Object.entries(resource.options.allowedActions).map(async ([key, value]) => {
573
- if (!neededActions.includes(key)) {
574
- allowedActions[key] = false;
575
- return;
576
- }
577
- // if callable then call
578
- if (typeof value === 'function') {
579
- allowedActions[key] = await value({ adminUser, resource, meta, source, adminforth });
580
- }
581
- else {
582
- allowedActions[key] = value;
583
- }
584
- }));
585
- return { allowedActions };
586
- }
587
484
  export default class AdminForthRestAPI {
588
485
  constructor(adminforth) {
589
486
  this.loginRateLimiters = [];
@@ -898,7 +795,9 @@ export default class AdminForthRestAPI {
898
795
  }
899
796
  }
900
797
  const usersResource = this.adminforth.config.resources.find((res) => res.resourceId === this.adminforth.config.auth.usersResourceId);
901
- const defaultUserExists = await this.adminforth.resource(usersResource.resourceId).get(Filters.EQ(usernameField, 'adminforth')) ? true : false;
798
+ const defaultUserExists = await this.adminforth
799
+ .resource(usersResource.resourceId)
800
+ .get(Filters.EQ(usernameField, 'adminforth')) ? true : false;
902
801
  const loggedInPart = {
903
802
  showBrandNameInSidebar: this.adminforth.config.customization.showBrandNameInSidebar,
904
803
  showBrandLogoInSidebar: this.adminforth.config.customization.showBrandLogoInSidebar,
@@ -957,13 +856,7 @@ export default class AdminForthRestAPI {
957
856
  source: ActionCheckSource.ShowRequest,
958
857
  adminforth: this.adminforth,
959
858
  };
960
- for (const key of Object.keys(adminUser.dbUser)) {
961
- const col = userResource.columns.find((c) => c.name === key);
962
- const bo = col ? await isBackendOnly(col, ctx) : true;
963
- if (!col || bo) {
964
- delete adminUser.dbUser[key];
965
- }
966
- }
859
+ await stripReadForbiddenColumns(ctx, adminUser.dbUser);
967
860
  return {
968
861
  loggedIn: true,
969
862
  config: Object.assign(Object.assign({}, public_config), loggedInPart),
@@ -1246,9 +1139,9 @@ export default class AdminForthRestAPI {
1246
1139
  if (!allowed) {
1247
1140
  return { error };
1248
1141
  }
1249
- const backendOnlyFilterError = await rejectBackendOnlyFilters(body.filters, columnCtx);
1250
- if (backendOnlyFilterError) {
1251
- return backendOnlyFilterError;
1142
+ const filterError = await filterColumnsReadableError(columnCtx, body.filters);
1143
+ if (filterError) {
1144
+ return { error: filterError };
1252
1145
  }
1253
1146
  if (this.checkAbortSignal(abortSignal)) {
1254
1147
  return { error: 'Request aborted' };
@@ -1320,6 +1213,10 @@ export default class AdminForthRestAPI {
1320
1213
  const col = resource.columns.find((col) => col.name === sortItem.field);
1321
1214
  return col && !col.virtual;
1322
1215
  });
1216
+ const sortError = await sortColumnsReadableError(columnCtx, sortFiltered);
1217
+ if (sortError) {
1218
+ return { error: sortError };
1219
+ }
1323
1220
  // after beforeDatasourceRequest hook, filter can be anything
1324
1221
  // so, we need to turn it into AndOr filter
1325
1222
  // (validation and normalization of individual filters will be done inside getData)
@@ -1479,15 +1376,14 @@ export default class AdminForthRestAPI {
1479
1376
  // remove all columns which are not defined in resources, or defined but backendOnly
1480
1377
  {
1481
1378
  for (const [i, item] of data.data.entries()) {
1379
+ const encodedId = item._primaryKeyValue;
1380
+ await stripReadForbiddenColumns(columnCtx, item);
1381
+ if (encodedId !== undefined) {
1382
+ item._primaryKeyValue = encodedId;
1383
+ }
1482
1384
  const rawItem = rawItems[i];
1483
- for (const key of Object.keys(item)) {
1484
- if (key === '_primaryKeyValue') {
1485
- continue;
1486
- }
1487
- const col = resource.columns.find((c) => c.name === key);
1488
- const bo = col ? await isBackendOnly(col, columnCtx) : true;
1489
- if (!col || bo) {
1490
- delete item[key];
1385
+ for (const key of Object.keys(rawItem)) {
1386
+ if (!(key in item)) {
1491
1387
  delete rawItem[key];
1492
1388
  }
1493
1389
  }
@@ -1617,8 +1513,7 @@ export default class AdminForthRestAPI {
1617
1513
  },
1618
1514
  request_schema: aggregateRequestSchema,
1619
1515
  response_schema: aggregateResponseSchema,
1620
- handler: async ({ body, adminUser, headers, query, cookies, requestUrl }) => {
1621
- var _a, _b, _c, _d;
1516
+ handler: async ({ body, adminUser, headers, query, cookies, requestUrl, response }) => {
1622
1517
  const { resourceId } = body;
1623
1518
  if (!this.adminforth.statuses.dbDiscover) {
1624
1519
  return { error: 'Database discovery not started' };
@@ -1630,147 +1525,26 @@ export default class AdminForthRestAPI {
1630
1525
  if (!resource) {
1631
1526
  return { error: `Resource ${resourceId} not found` };
1632
1527
  }
1633
- const rawFilterError = rejectApiRawFilters(body.filters);
1634
- if (rawFilterError) {
1635
- return rawFilterError;
1636
- }
1637
- const meta = { requestBody: body, pk: undefined };
1638
- const { allowedActions: listActions } = await interpretResource(adminUser, resource, meta, ActionCheckSource.ListRequest, this.adminforth);
1639
- // aggregation reads a whole set of records at once, so it needs list access
1640
- const { allowed, error } = checkAccess(AllowedActionsEnum.list, listActions);
1641
- if (!allowed) {
1642
- return { error };
1643
- }
1644
- // ...and min/max/groupBy return raw per-field values, which is what the show view does,
1645
- // so a resource with no reachable show view must not be aggregatable either.
1646
- // ListRequest resolves only 'list', so 'show' is resolved with its own source
1647
- const { allowedActions: showActions } = await interpretResource(adminUser, resource, meta, ActionCheckSource.ShowRequest, this.adminforth);
1648
- const { allowed: showAllowed, error: showError } = checkAccess(AllowedActionsEnum.show, showActions);
1649
- if (!showAllowed) {
1650
- return { error: showError };
1651
- }
1652
- const columnCtx = {
1653
- adminUser,
1654
- resource,
1655
- meta,
1656
- source: ActionCheckSource.ShowRequest,
1657
- adminforth: this.adminforth,
1658
- };
1659
- // a column may only take part in an aggregation if the user could have read the
1660
- // very same value from the show view
1661
- const columnExposureError = async (fieldName, context) => {
1662
- const column = resource.columns.find((col) => col.name === fieldName);
1663
- if (!column) {
1664
- return `${context}: unknown column "${fieldName}"`;
1665
- }
1666
- if (await isBackendOnly(column, columnCtx)) {
1667
- return `${context}: column "${fieldName}" cannot be aggregated (backendOnly is true).`;
1668
- }
1669
- if (!await isShown(column, 'show', columnCtx)) {
1670
- return `${context}: column "${fieldName}" cannot be aggregated (showIn.show is false).`;
1671
- }
1672
- return null;
1673
- };
1674
- for (const [alias, rule] of Object.entries((body.aggregations || {}))) {
1675
- // plain count does not reference any column
1676
- if (!(rule === null || rule === void 0 ? void 0 : rule.field)) {
1677
- continue;
1678
- }
1679
- const fieldError = await columnExposureError(rule.field, `Aggregation "${alias}"`);
1680
- if (fieldError) {
1681
- return { error: fieldError };
1682
- }
1683
- }
1684
- const groupByRules = Array.isArray(body.groupBy) ? body.groupBy : (body.groupBy ? [body.groupBy] : []);
1685
- for (const groupByRule of groupByRules) {
1686
- if (!(groupByRule === null || groupByRule === void 0 ? void 0 : groupByRule.field)) {
1687
- continue;
1688
- }
1689
- const fieldError = await columnExposureError(groupByRule.field, 'GroupBy');
1690
- if (fieldError) {
1691
- return { error: fieldError };
1692
- }
1693
- }
1694
- const backendOnlyFilterError = await rejectBackendOnlyFilters(body.filters, columnCtx);
1695
- if (backendOnlyFilterError) {
1696
- return backendOnlyFilterError;
1697
- }
1698
- // aggregation reads the same set of records as the list, so the list hooks scope it
1699
- for (const hook of listify((_b = (_a = resource.hooks) === null || _a === void 0 ? void 0 : _a.list) === null || _b === void 0 ? void 0 : _b.beforeDatasourceRequest)) {
1700
- const filterTools = filtersTools.get(body);
1701
- body.filtersTools = filterTools;
1702
- const resp = await hook({
1703
- resource,
1704
- query: body,
1705
- adminUser,
1706
- filtersTools: filterTools,
1707
- extra: {
1708
- body, query, headers, cookies, requestUrl
1709
- },
1710
- adminforth: this.adminforth,
1711
- });
1712
- const hookRespError = hookResponseError(resp);
1713
- if (hookRespError) {
1714
- return hookRespError;
1715
- }
1716
- }
1717
1528
  const { aggregations, filters, groupBy } = body;
1718
- // normalize filters same way as get_resource_data
1719
- const normalizedFilters = { operator: AdminForthFilterOperators.AND, subFilters: [] };
1720
- if (filters) {
1721
- if (typeof filters !== 'object') {
1722
- return { error: 'Filter should be an array or an object' };
1723
- }
1724
- if (Array.isArray(filters)) {
1725
- normalizedFilters.subFilters = filters;
1726
- }
1727
- else if (filters.field) {
1728
- normalizedFilters.subFilters = [filters];
1729
- }
1730
- else if (filters.subFilters) {
1731
- normalizedFilters.operator = filters.operator;
1732
- normalizedFilters.subFilters = filters.subFilters;
1733
- }
1734
- else {
1735
- return { error: `Wrong filter object value: ${JSON.stringify(filters)}` };
1736
- }
1737
- }
1738
1529
  const userTimeZone = headers['X-TimeZone'];
1739
1530
  const applyUserTimeZone = (groupByRule) => (groupByRule === null || groupByRule === void 0 ? void 0 : groupByRule.type) === 'date_trunc' && userTimeZone
1740
1531
  ? Object.assign(Object.assign({}, groupByRule), { timezone: userTimeZone }) : groupByRule;
1741
1532
  const aggregateGroupBy = Array.isArray(groupBy)
1742
1533
  ? groupBy.map(applyUserTimeZone)
1743
1534
  : applyUserTimeZone(groupBy);
1744
- let data;
1745
1535
  try {
1746
- data = await this.adminforth.connectors[resource.dataSource].aggregate({
1747
- resource,
1748
- filters: normalizedFilters,
1749
- aggregations,
1750
- groupBy: aggregateGroupBy,
1751
- });
1536
+ const data = await this.adminforth
1537
+ .resource(resource.resourceId)
1538
+ .asUser(adminUser, {
1539
+ meta: { requestBody: body, pk: undefined },
1540
+ extra: { body, query, headers, cookies, requestUrl, response },
1541
+ })
1542
+ .aggregate(filters, aggregations, aggregateGroupBy);
1543
+ return { data };
1752
1544
  }
1753
1545
  catch (e) {
1754
1546
  return { error: e.message };
1755
1547
  }
1756
- // hooks get the aggregation rows as response, they can tell this call by query.aggregations
1757
- for (const hook of listify((_d = (_c = resource.hooks) === null || _c === void 0 ? void 0 : _c.list) === null || _d === void 0 ? void 0 : _d.afterDatasourceResponse)) {
1758
- const resp = await hook({
1759
- resource,
1760
- query: body,
1761
- response: data,
1762
- adminUser,
1763
- extra: {
1764
- body, query, headers, cookies, requestUrl
1765
- },
1766
- adminforth: this.adminforth,
1767
- });
1768
- const hookRespError = hookResponseError(resp);
1769
- if (hookRespError) {
1770
- return hookRespError;
1771
- }
1772
- }
1773
- return { data };
1774
1548
  },
1775
1549
  });
1776
1550
  server.endpoint({
@@ -1815,157 +1589,156 @@ export default class AdminForthRestAPI {
1815
1589
  const targetResources = targetResourceIds.map((trId) => this.adminforth.config.resources.find((res) => res.resourceId == trId));
1816
1590
  // request filters are applied to the target resources, so their columns are what has to be readable
1817
1591
  for (const targetResource of targetResources) {
1818
- const backendOnlyFilterError = await rejectBackendOnlyFilters(body.filters, {
1592
+ const filterError = await filterColumnsReadableError({
1819
1593
  adminUser,
1820
1594
  resource: targetResource,
1821
1595
  meta,
1822
1596
  source: ActionCheckSource.ListRequest,
1823
1597
  adminforth: this.adminforth,
1824
- });
1825
- if (backendOnlyFilterError) {
1826
- return backendOnlyFilterError;
1598
+ }, body.filters);
1599
+ if (filterError) {
1600
+ return { error: filterError };
1601
+ }
1602
+ }
1603
+ const responses = await Promise.all(targetResources.map(async (targetResource) => {
1604
+ var _a, _b, _c, _d;
1605
+ for (const hook of listify((_b = (_a = columnConfig.foreignResource.hooks) === null || _a === void 0 ? void 0 : _a.dropdownList) === null || _b === void 0 ? void 0 : _b.beforeDatasourceRequest)) {
1606
+ const filterTools = filtersTools.get(body);
1607
+ body.filtersTools = filterTools;
1608
+ const resp = await hook({
1609
+ query: body,
1610
+ adminUser,
1611
+ filtersTools: filterTools,
1612
+ resource: targetResource,
1613
+ extra: {
1614
+ body, query, headers, cookies, requestUrl
1615
+ },
1616
+ adminforth: this.adminforth,
1617
+ });
1618
+ if (!resp || (!resp.ok && !resp.error)) {
1619
+ throw new Error(`Hook must return object with {ok: true} or { error: 'Error' } `);
1620
+ }
1621
+ if (resp.error) {
1622
+ return { error: resp.error };
1623
+ }
1827
1624
  }
1828
- }
1829
- const responses = (await Promise.all(targetResources.map(async (targetResource) => {
1830
- return new Promise(async (resolve) => {
1831
- var _a, _b, _c, _d;
1832
- for (const hook of listify((_b = (_a = columnConfig.foreignResource.hooks) === null || _a === void 0 ? void 0 : _a.dropdownList) === null || _b === void 0 ? void 0 : _b.beforeDatasourceRequest)) {
1833
- const filterTools = filtersTools.get(body);
1834
- body.filtersTools = filterTools;
1835
- const resp = await hook({
1836
- query: body,
1837
- adminUser,
1838
- filtersTools: filterTools,
1839
- resource: targetResource,
1840
- extra: {
1841
- body, query, headers, cookies, requestUrl
1842
- },
1843
- adminforth: this.adminforth,
1844
- });
1845
- if (!resp || (!resp.ok && !resp.error)) {
1846
- throw new Error(`Hook must return object with {ok: true} or { error: 'Error' } `);
1847
- }
1848
- if (resp.error) {
1849
- return { error: resp.error };
1850
- }
1625
+ const { limit, offset, filters, sort } = body;
1626
+ // after beforeDatasourceRequest hook, filter can be anything
1627
+ // so, we need to turn it into AndOr filter
1628
+ // (validation and normalization of individual filters will be done inside getData)
1629
+ const normalizedFilters = { operator: AdminForthFilterOperators.AND, subFilters: [] };
1630
+ if (filters) {
1631
+ if (typeof filters !== 'object') {
1632
+ throw new Error(`Filter should be an array or an object`);
1851
1633
  }
1852
- const { limit, offset, filters, sort } = body;
1853
- // after beforeDatasourceRequest hook, filter can be anything
1854
- // so, we need to turn it into AndOr filter
1855
- // (validation and normalization of individual filters will be done inside getData)
1856
- const normalizedFilters = { operator: AdminForthFilterOperators.AND, subFilters: [] };
1857
- if (filters) {
1858
- if (typeof filters !== 'object') {
1859
- throw new Error(`Filter should be an array or an object`);
1860
- }
1861
- if (Array.isArray(filters)) {
1862
- // if filters are an array, they will be connected with "AND" operator by default
1863
- normalizedFilters.subFilters = filters;
1864
- }
1865
- else if (filters.field) {
1866
- // assume filter is a SingleFilter
1867
- normalizedFilters.subFilters = [filters];
1868
- }
1869
- else if (filters.subFilters) {
1870
- // assume filter is a AndOr filter
1871
- normalizedFilters.operator = filters.operator;
1872
- normalizedFilters.subFilters = filters.subFilters;
1873
- }
1874
- else {
1875
- // wrong filter
1876
- throw new Error(`Wrong filter object value: ${JSON.stringify(filters)}`);
1877
- }
1634
+ if (Array.isArray(filters)) {
1635
+ // if filters are an array, they will be connected with "AND" operator by default
1636
+ normalizedFilters.subFilters = filters;
1878
1637
  }
1879
- if (search && search.trim() && columnConfig.foreignResource.searchableFields) {
1880
- const searchableFields = Array.isArray(columnConfig.foreignResource.searchableFields)
1881
- ? columnConfig.foreignResource.searchableFields
1882
- : [columnConfig.foreignResource.searchableFields];
1883
- const searchOperator = columnConfig.foreignResource.searchIsCaseSensitive
1884
- ? AdminForthFilterOperators.LIKE
1885
- : AdminForthFilterOperators.ILIKE;
1886
- const availableSearchFields = searchableFields.filter((fieldName) => {
1887
- const fieldExists = targetResource.columns.some(col => col.name === fieldName);
1888
- if (!fieldExists) {
1889
- afLogger.trace(`⚠️ Field '${fieldName}' not found in polymorphic target resource '${targetResource.resourceId}', skipping in search filter.`);
1890
- }
1891
- return fieldExists;
1892
- });
1893
- if (availableSearchFields.length === 0) {
1894
- afLogger.trace(`⚠️ No searchable fields available in polymorphic target resource '${targetResource.resourceId}', skipping resource.`);
1895
- resolve({ items: [] });
1896
- return;
1897
- }
1898
- const searchFilters = availableSearchFields.map((fieldName) => {
1899
- const filter = {
1900
- field: fieldName,
1901
- operator: searchOperator,
1902
- value: search.trim(),
1903
- };
1904
- return filter;
1905
- });
1906
- if (searchFilters.length > 1) {
1907
- normalizedFilters.subFilters.push({
1908
- operator: AdminForthFilterOperators.OR,
1909
- subFilters: searchFilters,
1910
- });
1911
- }
1912
- else if (searchFilters.length === 1) {
1913
- normalizedFilters.subFilters.push(searchFilters[0]);
1914
- }
1638
+ else if (filters.field) {
1639
+ // assume filter is a SingleFilter
1640
+ normalizedFilters.subFilters = [filters];
1915
1641
  }
1916
- if (currentValue !== undefined && currentValue !== null && currentValue !== '') {
1917
- const pkField = targetResource.columns.find((col) => col.primaryKey);
1918
- if (pkField) {
1919
- normalizedFilters.subFilters.push({ field: pkField.name, operator: AdminForthFilterOperators.EQ, value: currentValue });
1920
- }
1642
+ else if (filters.subFilters) {
1643
+ // assume filter is a AndOr filter
1644
+ normalizedFilters.operator = filters.operator;
1645
+ normalizedFilters.subFilters = filters.subFilters;
1921
1646
  }
1922
- const dbDataItems = await this.adminforth.connectors[targetResource.dataSource].getData({
1923
- resource: targetResource,
1924
- limit,
1925
- offset,
1926
- filters: normalizedFilters,
1927
- sort: sort || [],
1647
+ else {
1648
+ // wrong filter
1649
+ throw new Error(`Wrong filter object value: ${JSON.stringify(filters)}`);
1650
+ }
1651
+ }
1652
+ if (search && search.trim() && columnConfig.foreignResource.searchableFields) {
1653
+ const searchableFields = Array.isArray(columnConfig.foreignResource.searchableFields)
1654
+ ? columnConfig.foreignResource.searchableFields
1655
+ : [columnConfig.foreignResource.searchableFields];
1656
+ const searchOperator = columnConfig.foreignResource.searchIsCaseSensitive
1657
+ ? AdminForthFilterOperators.LIKE
1658
+ : AdminForthFilterOperators.ILIKE;
1659
+ const availableSearchFields = searchableFields.filter((fieldName) => {
1660
+ const fieldExists = targetResource.columns.some(col => col.name === fieldName);
1661
+ if (!fieldExists) {
1662
+ afLogger.trace(`⚠️ Field '${fieldName}' not found in polymorphic target resource '${targetResource.resourceId}', skipping in search filter.`);
1663
+ }
1664
+ return fieldExists;
1928
1665
  });
1929
- const items = dbDataItems.data.map((item) => {
1930
- const pk = item[targetResource.columns.find((col) => col.primaryKey).name];
1931
- const labler = targetResource.recordLabel;
1932
- return {
1933
- value: pk,
1934
- label: labler(item),
1935
- _item: item, // user might need it in hook to form new label
1666
+ if (availableSearchFields.length === 0) {
1667
+ afLogger.trace(`⚠️ No searchable fields available in polymorphic target resource '${targetResource.resourceId}', skipping resource.`);
1668
+ return { items: [] };
1669
+ }
1670
+ const searchFilters = availableSearchFields.map((fieldName) => {
1671
+ const filter = {
1672
+ field: fieldName,
1673
+ operator: searchOperator,
1674
+ value: search.trim(),
1936
1675
  };
1676
+ return filter;
1937
1677
  });
1938
- const response = {
1939
- items
1940
- };
1941
- for (const hook of listify((_d = (_c = columnConfig.foreignResource.hooks) === null || _c === void 0 ? void 0 : _c.dropdownList) === null || _d === void 0 ? void 0 : _d.afterDatasourceResponse)) {
1942
- const resp = await hook({
1943
- response,
1944
- adminUser,
1945
- query: body,
1946
- resource: targetResource,
1947
- extra: {
1948
- body, query, headers, cookies, requestUrl
1949
- },
1950
- adminforth: this.adminforth,
1678
+ if (searchFilters.length > 1) {
1679
+ normalizedFilters.subFilters.push({
1680
+ operator: AdminForthFilterOperators.OR,
1681
+ subFilters: searchFilters,
1951
1682
  });
1952
- if (!resp || (!resp.ok && !resp.error)) {
1953
- throw new Error(`Hook must return object with {ok: true} or { error: 'Error' } `);
1954
- }
1955
- if (resp.error) {
1956
- return { error: resp.error };
1957
- }
1958
1683
  }
1959
- // remove _item from response (might expose sensitive data like backendOnly fields)
1960
- response.items.forEach((item) => {
1961
- delete item._item;
1684
+ else if (searchFilters.length === 1) {
1685
+ normalizedFilters.subFilters.push(searchFilters[0]);
1686
+ }
1687
+ }
1688
+ if (currentValue !== undefined && currentValue !== null && currentValue !== '') {
1689
+ const pkField = targetResource.columns.find((col) => col.primaryKey);
1690
+ if (pkField) {
1691
+ normalizedFilters.subFilters.push({ field: pkField.name, operator: AdminForthFilterOperators.EQ, value: currentValue });
1692
+ }
1693
+ }
1694
+ const dbDataItems = await this.adminforth.connectors[targetResource.dataSource].getData({
1695
+ resource: targetResource,
1696
+ limit,
1697
+ offset,
1698
+ filters: normalizedFilters,
1699
+ sort: sort || [],
1700
+ });
1701
+ const items = dbDataItems.data.map((item) => {
1702
+ const pk = item[targetResource.columns.find((col) => col.primaryKey).name];
1703
+ const labler = targetResource.recordLabel;
1704
+ return {
1705
+ value: pk,
1706
+ label: labler(item),
1707
+ _item: item, // user might need it in hook to form new label
1708
+ };
1709
+ });
1710
+ const response = {
1711
+ items
1712
+ };
1713
+ for (const hook of listify((_d = (_c = columnConfig.foreignResource.hooks) === null || _c === void 0 ? void 0 : _c.dropdownList) === null || _d === void 0 ? void 0 : _d.afterDatasourceResponse)) {
1714
+ const resp = await hook({
1715
+ response,
1716
+ adminUser,
1717
+ query: body,
1718
+ resource: targetResource,
1719
+ extra: {
1720
+ body, query, headers, cookies, requestUrl
1721
+ },
1722
+ adminforth: this.adminforth,
1962
1723
  });
1963
- resolve(response);
1724
+ if (!resp || (!resp.ok && !resp.error)) {
1725
+ throw new Error(`Hook must return object with {ok: true} or { error: 'Error' } `);
1726
+ }
1727
+ if (resp.error) {
1728
+ return { error: resp.error };
1729
+ }
1730
+ }
1731
+ // remove _item from response (might expose sensitive data like backendOnly fields)
1732
+ response.items.forEach((item) => {
1733
+ delete item._item;
1964
1734
  });
1965
- }))).reduce((acc, response) => {
1966
- return [...acc, ...response.items];
1967
- }, []);
1968
- return { items: responses };
1735
+ return response;
1736
+ }));
1737
+ const errorResponse = responses.find((response) => response.error);
1738
+ if (errorResponse) {
1739
+ return errorResponse;
1740
+ }
1741
+ return { items: responses.flatMap((response) => response.items) };
1969
1742
  },
1970
1743
  });
1971
1744
  server.endpoint({
@@ -2013,15 +1786,15 @@ export default class AdminForthRestAPI {
2013
1786
  request_schema: createRecordRequestSchema,
2014
1787
  response_schema: createRecordResponseSchema,
2015
1788
  handler: async ({ body, adminUser, query, headers, cookies, requestUrl, response }) => {
2016
- var _a, _b;
2017
1789
  const resource = this.adminforth.config.resources.find((res) => res.resourceId == body['resourceId']);
2018
1790
  if (!resource) {
2019
1791
  return { error: `Resource '${body['resourceId']}' not found` };
2020
1792
  }
2021
- const { allowedActions } = await interpretResource(adminUser, resource, { requestBody: body }, ActionCheckSource.CreateRequest, this.adminforth);
2022
- const { allowed, error } = checkAccess(AllowedActionsEnum.create, allowedActions);
2023
- if (!allowed) {
2024
- return { error };
1793
+ // Check before revealing existing records or required columns. The scoped write
1794
+ // consumes this one-use grant, so the ACL callback is not invoked twice.
1795
+ const createAccess = await authorizeResourceOperation(adminUser, resource, { requestBody: body }, ActionCheckSource.CreateRequest, AllowedActionsEnum.create, this.adminforth, body.record);
1796
+ if (createAccess.error) {
1797
+ return { error: createAccess.error };
2025
1798
  }
2026
1799
  const { record } = body;
2027
1800
  const ctxCreate = {
@@ -2054,78 +1827,26 @@ export default class AdminForthRestAPI {
2054
1827
  else {
2055
1828
  const primaryKeyColumn = resource.columns.find((col) => col.primaryKey);
2056
1829
  if (record[primaryKeyColumn.name] !== undefined) {
2057
- const existingRecord = await this.adminforth.resource(resource.resourceId).get([Filters.EQ(primaryKeyColumn.name, record[primaryKeyColumn.name])]);
1830
+ const existingRecord = await this.adminforth.resource(resource.resourceId)
1831
+ .get([Filters.EQ(primaryKeyColumn.name, record[primaryKeyColumn.name])]);
2058
1832
  if (existingRecord) {
2059
1833
  return { error: `Record with ${primaryKeyColumn.name} '${record[primaryKeyColumn.name]}' already exists`, ok: false };
2060
1834
  }
2061
1835
  }
2062
1836
  }
2063
- for (const column of resource.columns) {
2064
- const fieldName = column.name;
2065
- if (fieldName in record) {
2066
- const shown = await isShown(column, 'create', ctxCreate); //
2067
- const bo = await isBackendOnly(column, ctxCreate);
2068
- const filledOnCreate = await isFilledOnCreate(column);
2069
- if (bo) {
2070
- return {
2071
- error: `Field "${fieldName}" cannot be modified as it is restricted from creation (backendOnly is true).`,
2072
- ok: false,
2073
- };
2074
- }
2075
- if (!shown && !filledOnCreate && !column.allowModifyWhenNotShowInCreate) {
2076
- return {
2077
- error: `Field "${fieldName}" cannot be modified as it is restricted from creation (showIn.create is false). If you need to set this hidden field during creation, either configure column.fillOnCreate or set column.allowModifyWhenNotShowInCreate = true.`,
2078
- ok: false,
2079
- };
2080
- }
2081
- }
2082
- }
2083
- // for polymorphic foreign resources, we need to find out the value for polymorphicOn column
2084
- for (const column of resource.columns) {
2085
- if (((_a = column.foreignResource) === null || _a === void 0 ? void 0 : _a.polymorphicOn) && record[column.name] === null) {
2086
- const systemResource = column.foreignResource.polymorphicResources.find(pr => pr.resourceId === null);
2087
- record[column.foreignResource.polymorphicOn] = systemResource.whenValue;
2088
- }
2089
- else if (((_b = column.foreignResource) === null || _b === void 0 ? void 0 : _b.polymorphicOn) && record[column.name]) {
2090
- const targetResources = {};
2091
- const targetConnectors = {};
2092
- const targetResourcePkFields = {};
2093
- column.foreignResource.polymorphicResources.forEach((pr) => {
2094
- if (pr.resourceId === null) {
2095
- return;
2096
- }
2097
- const targetResource = this.adminforth.config.resources.find((res) => res.resourceId == pr.resourceId);
2098
- if (!targetResource) {
2099
- return;
2100
- }
2101
- targetResources[pr.whenValue] = targetResource;
2102
- targetConnectors[pr.whenValue] = this.adminforth.connectors[targetResources[pr.whenValue].dataSource];
2103
- targetResourcePkFields[pr.whenValue] = targetResources[pr.whenValue].columns.find((col) => col.primaryKey).name;
2104
- });
2105
- const targetData = (await Promise.all(Object.keys(targetResources).map((polymorphicOnValue) => targetConnectors[polymorphicOnValue].getData({
2106
- resource: targetResources[polymorphicOnValue],
2107
- limit: 1,
2108
- offset: 0,
2109
- filters: { operator: AdminForthFilterOperators.AND, subFilters: [
2110
- {
2111
- field: targetResourcePkFields[polymorphicOnValue],
2112
- operator: AdminForthFilterOperators.EQ,
2113
- value: record[column.name],
2114
- }
2115
- ] },
2116
- sort: [],
2117
- })))).reduce((acc, td, tdi) => (Object.assign(Object.assign({}, acc), { [Object.keys(targetResources)[tdi]]: td.data })), {});
2118
- record[column.foreignResource.polymorphicOn] = Object.keys(targetData).find((tdk) => targetData[tdk].length);
2119
- }
2120
- }
2121
1837
  const jsonError = this.normalizeJsonColumns(resource, record);
2122
1838
  if (jsonError) {
2123
1839
  return { error: jsonError, ok: false };
2124
1840
  }
2125
- const createRecordResponse = await this.adminforth.createResourceRecord({
2126
- resource, record, adminUser,
2127
- extra: { body, query, headers, cookies, requestUrl, response }
2128
- });
1841
+ const scopedCreateOptions = {
1842
+ meta: ctxCreate.meta,
1843
+ extra: { body, query, headers, cookies, requestUrl, response },
1844
+ [RESOURCE_ACCESS_GRANT]: createAccess.grant,
1845
+ };
1846
+ const createRecordResponse = await this.adminforth
1847
+ .resource(resource.resourceId)
1848
+ .asUser(adminUser, scopedCreateOptions)
1849
+ .create(record);
2129
1850
  if (createRecordResponse.error) {
2130
1851
  return {
2131
1852
  error: createRecordResponse.error,
@@ -2155,7 +1876,6 @@ export default class AdminForthRestAPI {
2155
1876
  request_schema: updateRecordRequestSchema,
2156
1877
  response_schema: updateRecordResponseSchema,
2157
1878
  handler: async ({ body, adminUser, query, headers, cookies, requestUrl, response }) => {
2158
- var _a, _b;
2159
1879
  const resource = this.adminforth.config.resources.find((res) => res.resourceId == body['resourceId']);
2160
1880
  if (!resource) {
2161
1881
  return { error: `Resource '${body['resourceId']}' not found` };
@@ -2163,15 +1883,16 @@ export default class AdminForthRestAPI {
2163
1883
  const recordId = body['recordId'];
2164
1884
  const connector = this.adminforth.connectors[resource.dataSource];
2165
1885
  const oldRecord = await connector.getRecordByPrimaryKey(resource, recordId);
1886
+ // edit permission callbacks read meta.oldRecord, so they only ever see an existing record
2166
1887
  if (!oldRecord) {
2167
1888
  const primaryKeyColumn = resource.columns.find((col) => col.primaryKey);
2168
1889
  return { error: `Record with ${isCompositePrimaryKey(resource) ? primaryKeyColumnNames(resource).join(', ') : primaryKeyColumn.name} ${recordId} not found` };
2169
1890
  }
2170
1891
  const record = body['record'];
2171
- const { allowedActions } = await interpretResource(adminUser, resource, { requestBody: body, newRecord: record, oldRecord, pk: recordId }, ActionCheckSource.EditRequest, this.adminforth);
2172
- const { allowed, error: allowedError } = checkAccess(AllowedActionsEnum.edit, allowedActions);
2173
- if (!allowed) {
2174
- return { error: allowedError };
1892
+ // Check before revealing whether another record has the requested key.
1893
+ const editAccess = await authorizeResourceOperation(adminUser, resource, { requestBody: body, newRecord: record, oldRecord, pk: recordId }, ActionCheckSource.EditRequest, AllowedActionsEnum.edit, this.adminforth, record, recordId);
1894
+ if (editAccess.error) {
1895
+ return { error: editAccess.error };
2175
1896
  }
2176
1897
  if (isCompositePrimaryKey(resource)) {
2177
1898
  const pkColumnNames = primaryKeyColumnNames(resource);
@@ -2193,7 +1914,8 @@ export default class AdminForthRestAPI {
2193
1914
  else {
2194
1915
  const primaryKeyColumn = resource.columns.find((col) => col.primaryKey);
2195
1916
  if (record[primaryKeyColumn.name] !== undefined) {
2196
- const existingRecord = await this.adminforth.resource(resource.resourceId).get([Filters.EQ(primaryKeyColumn.name, record[primaryKeyColumn.name])]);
1917
+ const existingRecord = await this.adminforth.resource(resource.resourceId)
1918
+ .get([Filters.EQ(primaryKeyColumn.name, record[primaryKeyColumn.name])]);
2197
1919
  if (existingRecord) {
2198
1920
  return { error: `Record with ${primaryKeyColumn.name} '${record[primaryKeyColumn.name]}' already exists`, ok: false };
2199
1921
  }
@@ -2207,88 +1929,28 @@ export default class AdminForthRestAPI {
2207
1929
  adminforth: this.adminforth,
2208
1930
  };
2209
1931
  for (const column of resource.columns) {
2210
- const fieldName = column.name;
2211
- if (fieldName in record) {
2212
- const shown = await isShown(column, 'edit', ctxEdit);
2213
- const bo = await isBackendOnly(column, ctxEdit);
2214
- if (bo) {
2215
- return {
2216
- error: `Field "${fieldName}" cannot be modified as it is restricted from editing (backendOnly is true).`,
2217
- ok: false,
2218
- };
2219
- }
2220
- if (column.editReadonly) {
2221
- return {
2222
- error: `Field "${fieldName}" cannot be modified as it is restricted from editing (editReadonly is true).`,
2223
- ok: false,
2224
- };
2225
- }
2226
- if (!shown && !column.allowModifyWhenNotShowInEdit) {
2227
- return {
2228
- error: `Field "${fieldName}" cannot be modified as it is restricted from editing (showIn.edit is false). If you need to allow updating this hidden field during editing, set column.allowModifyWhenNotShowInEdit = true.`,
2229
- ok: false,
2230
- };
2231
- }
2232
- if (column.required.edit &&
2233
- shown &&
2234
- isEmptyColumnValue(column, record[fieldName]) &&
2235
- checkShowIf(column, Object.assign(Object.assign({}, oldRecord), record), resource.columns)) {
2236
- return { error: `Column '${fieldName}' is required`, ok: false };
2237
- }
2238
- }
2239
- }
2240
- // for polymorphic foreign resources, we need to find out the value for polymorphicOn column
2241
- for (const column of resource.columns) {
2242
- if (((_a = column.foreignResource) === null || _a === void 0 ? void 0 : _a.polymorphicOn) && record[column.name] === null) {
2243
- const systemResource = column.foreignResource.polymorphicResources.find(pr => pr.resourceId === null);
2244
- record[column.foreignResource.polymorphicOn] = systemResource.whenValue;
2245
- }
2246
- else if (((_b = column.foreignResource) === null || _b === void 0 ? void 0 : _b.polymorphicOn) && record[column.name]) {
2247
- let newPolymorphicOnValue = null;
2248
- if (record[column.name]) {
2249
- const targetResources = {};
2250
- const targetConnectors = {};
2251
- const targetResourcePkFields = {};
2252
- column.foreignResource.polymorphicResources.forEach((pr) => {
2253
- if (pr.resourceId === null) {
2254
- return;
2255
- }
2256
- const targetResource = this.adminforth.config.resources.find((res) => res.resourceId == pr.resourceId);
2257
- if (!targetResource) {
2258
- return;
2259
- }
2260
- targetResources[pr.whenValue] = targetResource;
2261
- targetConnectors[pr.whenValue] = this.adminforth.connectors[targetResources[pr.whenValue].dataSource];
2262
- targetResourcePkFields[pr.whenValue] = targetResources[pr.whenValue].columns.find((col) => col.primaryKey).name;
2263
- });
2264
- const targetData = (await Promise.all(Object.keys(targetResources).map((polymorphicOnValue) => targetConnectors[polymorphicOnValue].getData({
2265
- resource: targetResources[polymorphicOnValue],
2266
- limit: 1,
2267
- offset: 0,
2268
- filters: { operator: AdminForthFilterOperators.AND, subFilters: [
2269
- {
2270
- field: targetResourcePkFields[polymorphicOnValue],
2271
- operator: AdminForthFilterOperators.EQ,
2272
- value: record[column.name],
2273
- }
2274
- ] },
2275
- sort: [],
2276
- })))).reduce((acc, td, tdi) => (Object.assign(Object.assign({}, acc), { [Object.keys(targetResources)[tdi]]: td.data })), {});
2277
- newPolymorphicOnValue = Object.keys(targetData).find((tdk) => targetData[tdk].length);
2278
- }
2279
- if (oldRecord[column.foreignResource.polymorphicOn] !== newPolymorphicOnValue) {
2280
- record[column.foreignResource.polymorphicOn] = newPolymorphicOnValue;
2281
- }
1932
+ if (column.name in record &&
1933
+ column.required.edit &&
1934
+ isEmptyColumnValue(column, record[column.name]) &&
1935
+ await isShown(column, 'edit', ctxEdit) &&
1936
+ checkShowIf(column, Object.assign(Object.assign({}, oldRecord), record), resource.columns)) {
1937
+ return { error: `Column '${column.name}' is required`, ok: false };
2282
1938
  }
2283
1939
  }
2284
1940
  const jsonError = this.normalizeJsonColumns(resource, record);
2285
1941
  if (jsonError) {
2286
1942
  return { error: jsonError, ok: false };
2287
1943
  }
2288
- const { error } = await this.adminforth.updateResourceRecord({
2289
- resource, updates: record, adminUser, oldRecord, recordId,
2290
- extra: { body, query, headers, cookies, requestUrl, response }
2291
- });
1944
+ const scopedEditOptions = {
1945
+ meta: ctxEdit.meta,
1946
+ oldRecord,
1947
+ extra: { body, query, headers, cookies, requestUrl, response },
1948
+ [RESOURCE_ACCESS_GRANT]: editAccess.grant,
1949
+ };
1950
+ const { error } = await this.adminforth
1951
+ .resource(resource.resourceId)
1952
+ .asUser(adminUser, scopedEditOptions)
1953
+ .update(recordId, record);
2292
1954
  if (error) {
2293
1955
  return { error };
2294
1956
  }
@@ -2315,24 +1977,31 @@ export default class AdminForthRestAPI {
2315
1977
  return { error: `Resource '${body['resourceId']}' not found` };
2316
1978
  }
2317
1979
  const record = await this.adminforth.connectors[resource.dataSource].getRecordByPrimaryKey(resource, body['primaryKey']);
1980
+ // delete permission callbacks read meta.record, so they only ever see an existing record
2318
1981
  if (!record) {
2319
1982
  return { error: `Record with ${body['primaryKey']} not found` };
2320
1983
  }
2321
- const { allowedActions } = await interpretResource(adminUser, resource, { requestBody: body, record: record }, ActionCheckSource.DeleteRequest, this.adminforth);
2322
- const { allowed, error } = checkAccess(AllowedActionsEnum.delete, allowedActions);
2323
- if (!allowed) {
2324
- return { error };
1984
+ const deleteAccess = await authorizeResourceOperation(adminUser, resource, { requestBody: body, record }, ActionCheckSource.DeleteRequest, AllowedActionsEnum.delete, this.adminforth, record, body.primaryKey);
1985
+ if (deleteAccess.error) {
1986
+ return { error: deleteAccess.error };
2325
1987
  }
2326
- const extra = { body, query, headers, cookies, requestUrl, response };
2327
- const { error: cascadeError } = await cascadeChildrenDelete(resource, body.primaryKey, { adminUser, extra }, this.adminforth);
2328
- if (cascadeError) {
2329
- return { error: cascadeError };
1988
+ try {
1989
+ const scopedDeleteOptions = {
1990
+ meta: { requestBody: body, record },
1991
+ record,
1992
+ extra: { body, query, headers, cookies, requestUrl, response },
1993
+ [RESOURCE_ACCESS_GRANT]: deleteAccess.grant,
1994
+ };
1995
+ const deleted = await this.adminforth
1996
+ .resource(resource.resourceId)
1997
+ .asUser(adminUser, scopedDeleteOptions)
1998
+ .delete(body.primaryKey);
1999
+ if (!deleted) {
2000
+ return { error: `Record with ${body.primaryKey} not found` };
2001
+ }
2330
2002
  }
2331
- const { error: deleteError } = await this.adminforth.deleteResourceRecord({
2332
- resource, record, adminUser, recordId: body['primaryKey'], extra,
2333
- });
2334
- if (deleteError) {
2335
- return { error: deleteError };
2003
+ catch (error) {
2004
+ return { error: error.message };
2336
2005
  }
2337
2006
  return {
2338
2007
  ok: true,