adminforth 4.19.2 → 4.21.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 (58) 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 +69 -45
  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 +94 -424
  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/package-lock.json +11 -0
  47. package/dist/spa/package.json +1 -0
  48. package/dist/spa/pnpm-lock.yaml +8 -0
  49. package/dist/spa/src/afcl/ZoomableImage.vue +56 -0
  50. package/dist/spa/src/afcl/index.ts +1 -0
  51. package/dist/spa/src/types/Back.ts +86 -3
  52. package/dist/types/Back.d.ts +72 -5
  53. package/dist/types/Back.d.ts.map +1 -1
  54. package/dist/types/Back.js.map +1 -1
  55. package/package.json +1 -1
  56. package/dist/spa/src/assets/agents/claude-code.svg +0 -1
  57. package/dist/spa/src/assets/agents/codex.svg +0 -1
  58. package/dist/spa/src/assets/agents/gemini.svg +0 -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,15 +1589,15 @@ 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 };
1827
1601
  }
1828
1602
  }
1829
1603
  const responses = await Promise.all(targetResources.map(async (targetResource) => {
@@ -2012,15 +1786,15 @@ export default class AdminForthRestAPI {
2012
1786
  request_schema: createRecordRequestSchema,
2013
1787
  response_schema: createRecordResponseSchema,
2014
1788
  handler: async ({ body, adminUser, query, headers, cookies, requestUrl, response }) => {
2015
- var _a, _b;
2016
1789
  const resource = this.adminforth.config.resources.find((res) => res.resourceId == body['resourceId']);
2017
1790
  if (!resource) {
2018
1791
  return { error: `Resource '${body['resourceId']}' not found` };
2019
1792
  }
2020
- const { allowedActions } = await interpretResource(adminUser, resource, { requestBody: body }, ActionCheckSource.CreateRequest, this.adminforth);
2021
- const { allowed, error } = checkAccess(AllowedActionsEnum.create, allowedActions);
2022
- if (!allowed) {
2023
- 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 };
2024
1798
  }
2025
1799
  const { record } = body;
2026
1800
  const ctxCreate = {
@@ -2053,78 +1827,26 @@ export default class AdminForthRestAPI {
2053
1827
  else {
2054
1828
  const primaryKeyColumn = resource.columns.find((col) => col.primaryKey);
2055
1829
  if (record[primaryKeyColumn.name] !== undefined) {
2056
- 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])]);
2057
1832
  if (existingRecord) {
2058
1833
  return { error: `Record with ${primaryKeyColumn.name} '${record[primaryKeyColumn.name]}' already exists`, ok: false };
2059
1834
  }
2060
1835
  }
2061
1836
  }
2062
- for (const column of resource.columns) {
2063
- const fieldName = column.name;
2064
- if (fieldName in record) {
2065
- const shown = await isShown(column, 'create', ctxCreate); //
2066
- const bo = await isBackendOnly(column, ctxCreate);
2067
- const filledOnCreate = await isFilledOnCreate(column);
2068
- if (bo) {
2069
- return {
2070
- error: `Field "${fieldName}" cannot be modified as it is restricted from creation (backendOnly is true).`,
2071
- ok: false,
2072
- };
2073
- }
2074
- if (!shown && !filledOnCreate && !column.allowModifyWhenNotShowInCreate) {
2075
- return {
2076
- 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.`,
2077
- ok: false,
2078
- };
2079
- }
2080
- }
2081
- }
2082
- // for polymorphic foreign resources, we need to find out the value for polymorphicOn column
2083
- for (const column of resource.columns) {
2084
- if (((_a = column.foreignResource) === null || _a === void 0 ? void 0 : _a.polymorphicOn) && record[column.name] === null) {
2085
- const systemResource = column.foreignResource.polymorphicResources.find(pr => pr.resourceId === null);
2086
- record[column.foreignResource.polymorphicOn] = systemResource.whenValue;
2087
- }
2088
- else if (((_b = column.foreignResource) === null || _b === void 0 ? void 0 : _b.polymorphicOn) && record[column.name]) {
2089
- const targetResources = {};
2090
- const targetConnectors = {};
2091
- const targetResourcePkFields = {};
2092
- column.foreignResource.polymorphicResources.forEach((pr) => {
2093
- if (pr.resourceId === null) {
2094
- return;
2095
- }
2096
- const targetResource = this.adminforth.config.resources.find((res) => res.resourceId == pr.resourceId);
2097
- if (!targetResource) {
2098
- return;
2099
- }
2100
- targetResources[pr.whenValue] = targetResource;
2101
- targetConnectors[pr.whenValue] = this.adminforth.connectors[targetResources[pr.whenValue].dataSource];
2102
- targetResourcePkFields[pr.whenValue] = targetResources[pr.whenValue].columns.find((col) => col.primaryKey).name;
2103
- });
2104
- const targetData = (await Promise.all(Object.keys(targetResources).map((polymorphicOnValue) => targetConnectors[polymorphicOnValue].getData({
2105
- resource: targetResources[polymorphicOnValue],
2106
- limit: 1,
2107
- offset: 0,
2108
- filters: { operator: AdminForthFilterOperators.AND, subFilters: [
2109
- {
2110
- field: targetResourcePkFields[polymorphicOnValue],
2111
- operator: AdminForthFilterOperators.EQ,
2112
- value: record[column.name],
2113
- }
2114
- ] },
2115
- sort: [],
2116
- })))).reduce((acc, td, tdi) => (Object.assign(Object.assign({}, acc), { [Object.keys(targetResources)[tdi]]: td.data })), {});
2117
- record[column.foreignResource.polymorphicOn] = Object.keys(targetData).find((tdk) => targetData[tdk].length);
2118
- }
2119
- }
2120
1837
  const jsonError = this.normalizeJsonColumns(resource, record);
2121
1838
  if (jsonError) {
2122
1839
  return { error: jsonError, ok: false };
2123
1840
  }
2124
- const createRecordResponse = await this.adminforth.createResourceRecord({
2125
- resource, record, adminUser,
2126
- extra: { body, query, headers, cookies, requestUrl, response }
2127
- });
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);
2128
1850
  if (createRecordResponse.error) {
2129
1851
  return {
2130
1852
  error: createRecordResponse.error,
@@ -2154,7 +1876,6 @@ export default class AdminForthRestAPI {
2154
1876
  request_schema: updateRecordRequestSchema,
2155
1877
  response_schema: updateRecordResponseSchema,
2156
1878
  handler: async ({ body, adminUser, query, headers, cookies, requestUrl, response }) => {
2157
- var _a, _b;
2158
1879
  const resource = this.adminforth.config.resources.find((res) => res.resourceId == body['resourceId']);
2159
1880
  if (!resource) {
2160
1881
  return { error: `Resource '${body['resourceId']}' not found` };
@@ -2162,15 +1883,16 @@ export default class AdminForthRestAPI {
2162
1883
  const recordId = body['recordId'];
2163
1884
  const connector = this.adminforth.connectors[resource.dataSource];
2164
1885
  const oldRecord = await connector.getRecordByPrimaryKey(resource, recordId);
1886
+ // edit permission callbacks read meta.oldRecord, so they only ever see an existing record
2165
1887
  if (!oldRecord) {
2166
1888
  const primaryKeyColumn = resource.columns.find((col) => col.primaryKey);
2167
1889
  return { error: `Record with ${isCompositePrimaryKey(resource) ? primaryKeyColumnNames(resource).join(', ') : primaryKeyColumn.name} ${recordId} not found` };
2168
1890
  }
2169
1891
  const record = body['record'];
2170
- const { allowedActions } = await interpretResource(adminUser, resource, { requestBody: body, newRecord: record, oldRecord, pk: recordId }, ActionCheckSource.EditRequest, this.adminforth);
2171
- const { allowed, error: allowedError } = checkAccess(AllowedActionsEnum.edit, allowedActions);
2172
- if (!allowed) {
2173
- 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 };
2174
1896
  }
2175
1897
  if (isCompositePrimaryKey(resource)) {
2176
1898
  const pkColumnNames = primaryKeyColumnNames(resource);
@@ -2192,7 +1914,8 @@ export default class AdminForthRestAPI {
2192
1914
  else {
2193
1915
  const primaryKeyColumn = resource.columns.find((col) => col.primaryKey);
2194
1916
  if (record[primaryKeyColumn.name] !== undefined) {
2195
- 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])]);
2196
1919
  if (existingRecord) {
2197
1920
  return { error: `Record with ${primaryKeyColumn.name} '${record[primaryKeyColumn.name]}' already exists`, ok: false };
2198
1921
  }
@@ -2206,88 +1929,28 @@ export default class AdminForthRestAPI {
2206
1929
  adminforth: this.adminforth,
2207
1930
  };
2208
1931
  for (const column of resource.columns) {
2209
- const fieldName = column.name;
2210
- if (fieldName in record) {
2211
- const shown = await isShown(column, 'edit', ctxEdit);
2212
- const bo = await isBackendOnly(column, ctxEdit);
2213
- if (bo) {
2214
- return {
2215
- error: `Field "${fieldName}" cannot be modified as it is restricted from editing (backendOnly is true).`,
2216
- ok: false,
2217
- };
2218
- }
2219
- if (column.editReadonly) {
2220
- return {
2221
- error: `Field "${fieldName}" cannot be modified as it is restricted from editing (editReadonly is true).`,
2222
- ok: false,
2223
- };
2224
- }
2225
- if (!shown && !column.allowModifyWhenNotShowInEdit) {
2226
- return {
2227
- 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.`,
2228
- ok: false,
2229
- };
2230
- }
2231
- if (column.required.edit &&
2232
- shown &&
2233
- isEmptyColumnValue(column, record[fieldName]) &&
2234
- checkShowIf(column, Object.assign(Object.assign({}, oldRecord), record), resource.columns)) {
2235
- return { error: `Column '${fieldName}' is required`, ok: false };
2236
- }
2237
- }
2238
- }
2239
- // for polymorphic foreign resources, we need to find out the value for polymorphicOn column
2240
- for (const column of resource.columns) {
2241
- if (((_a = column.foreignResource) === null || _a === void 0 ? void 0 : _a.polymorphicOn) && record[column.name] === null) {
2242
- const systemResource = column.foreignResource.polymorphicResources.find(pr => pr.resourceId === null);
2243
- record[column.foreignResource.polymorphicOn] = systemResource.whenValue;
2244
- }
2245
- else if (((_b = column.foreignResource) === null || _b === void 0 ? void 0 : _b.polymorphicOn) && record[column.name]) {
2246
- let newPolymorphicOnValue = null;
2247
- if (record[column.name]) {
2248
- const targetResources = {};
2249
- const targetConnectors = {};
2250
- const targetResourcePkFields = {};
2251
- column.foreignResource.polymorphicResources.forEach((pr) => {
2252
- if (pr.resourceId === null) {
2253
- return;
2254
- }
2255
- const targetResource = this.adminforth.config.resources.find((res) => res.resourceId == pr.resourceId);
2256
- if (!targetResource) {
2257
- return;
2258
- }
2259
- targetResources[pr.whenValue] = targetResource;
2260
- targetConnectors[pr.whenValue] = this.adminforth.connectors[targetResources[pr.whenValue].dataSource];
2261
- targetResourcePkFields[pr.whenValue] = targetResources[pr.whenValue].columns.find((col) => col.primaryKey).name;
2262
- });
2263
- const targetData = (await Promise.all(Object.keys(targetResources).map((polymorphicOnValue) => targetConnectors[polymorphicOnValue].getData({
2264
- resource: targetResources[polymorphicOnValue],
2265
- limit: 1,
2266
- offset: 0,
2267
- filters: { operator: AdminForthFilterOperators.AND, subFilters: [
2268
- {
2269
- field: targetResourcePkFields[polymorphicOnValue],
2270
- operator: AdminForthFilterOperators.EQ,
2271
- value: record[column.name],
2272
- }
2273
- ] },
2274
- sort: [],
2275
- })))).reduce((acc, td, tdi) => (Object.assign(Object.assign({}, acc), { [Object.keys(targetResources)[tdi]]: td.data })), {});
2276
- newPolymorphicOnValue = Object.keys(targetData).find((tdk) => targetData[tdk].length);
2277
- }
2278
- if (oldRecord[column.foreignResource.polymorphicOn] !== newPolymorphicOnValue) {
2279
- record[column.foreignResource.polymorphicOn] = newPolymorphicOnValue;
2280
- }
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 };
2281
1938
  }
2282
1939
  }
2283
1940
  const jsonError = this.normalizeJsonColumns(resource, record);
2284
1941
  if (jsonError) {
2285
1942
  return { error: jsonError, ok: false };
2286
1943
  }
2287
- const { error } = await this.adminforth.updateResourceRecord({
2288
- resource, updates: record, adminUser, oldRecord, recordId,
2289
- extra: { body, query, headers, cookies, requestUrl, response }
2290
- });
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);
2291
1954
  if (error) {
2292
1955
  return { error };
2293
1956
  }
@@ -2314,24 +1977,31 @@ export default class AdminForthRestAPI {
2314
1977
  return { error: `Resource '${body['resourceId']}' not found` };
2315
1978
  }
2316
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
2317
1981
  if (!record) {
2318
1982
  return { error: `Record with ${body['primaryKey']} not found` };
2319
1983
  }
2320
- const { allowedActions } = await interpretResource(adminUser, resource, { requestBody: body, record: record }, ActionCheckSource.DeleteRequest, this.adminforth);
2321
- const { allowed, error } = checkAccess(AllowedActionsEnum.delete, allowedActions);
2322
- if (!allowed) {
2323
- 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 };
2324
1987
  }
2325
- const extra = { body, query, headers, cookies, requestUrl, response };
2326
- const { error: cascadeError } = await cascadeChildrenDelete(resource, body.primaryKey, { adminUser, extra }, this.adminforth);
2327
- if (cascadeError) {
2328
- 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
+ }
2329
2002
  }
2330
- const { error: deleteError } = await this.adminforth.deleteResourceRecord({
2331
- resource, record, adminUser, recordId: body['primaryKey'], extra,
2332
- });
2333
- if (deleteError) {
2334
- return { error: deleteError };
2003
+ catch (error) {
2004
+ return { error: error.message };
2335
2005
  }
2336
2006
  return {
2337
2007
  ok: true,