@directus/api 21.0.0 → 22.0.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.
- package/dist/app.js +4 -4
- package/dist/auth/drivers/ldap.js +4 -4
- package/dist/auth/drivers/local.js +4 -4
- package/dist/auth/drivers/oauth2.js +4 -4
- package/dist/auth/drivers/openid.js +2 -4
- package/dist/cache.js +3 -0
- package/dist/cli/commands/bootstrap/index.js +8 -2
- package/dist/cli/commands/init/index.js +9 -10
- package/dist/cli/utils/defaults.d.ts +4 -11
- package/dist/cli/utils/defaults.js +7 -1
- package/dist/constants.d.ts +1 -1
- package/dist/controllers/access.d.ts +2 -0
- package/dist/controllers/access.js +148 -0
- package/dist/controllers/auth.js +5 -16
- package/dist/controllers/permissions.js +14 -2
- package/dist/controllers/policies.d.ts +2 -0
- package/dist/controllers/policies.js +169 -0
- package/dist/controllers/roles.js +22 -1
- package/dist/controllers/tus.js +14 -26
- package/dist/controllers/users.js +0 -55
- package/dist/database/get-ast-from-query/get-ast-from-query.d.ts +16 -0
- package/dist/database/get-ast-from-query/get-ast-from-query.js +82 -0
- package/dist/database/get-ast-from-query/lib/convert-wildcards.d.ts +13 -0
- package/dist/database/get-ast-from-query/lib/convert-wildcards.js +69 -0
- package/dist/database/get-ast-from-query/lib/parse-fields.d.ts +15 -0
- package/dist/database/get-ast-from-query/lib/parse-fields.js +200 -0
- package/dist/database/get-ast-from-query/utils/get-deep-query.d.ts +14 -0
- package/dist/database/get-ast-from-query/utils/get-deep-query.js +17 -0
- package/dist/database/get-ast-from-query/utils/get-related-collection.d.ts +2 -0
- package/dist/database/get-ast-from-query/utils/get-related-collection.js +13 -0
- package/dist/database/get-ast-from-query/utils/get-relation.d.ts +2 -0
- package/dist/database/get-ast-from-query/utils/get-relation.js +7 -0
- package/dist/database/helpers/fn/types.d.ts +2 -1
- package/dist/database/helpers/fn/types.js +1 -1
- package/dist/database/helpers/geometry/dialects/mssql.d.ts +1 -1
- package/dist/database/helpers/geometry/dialects/mssql.js +4 -2
- package/dist/database/helpers/geometry/dialects/mysql.js +1 -1
- package/dist/database/helpers/geometry/dialects/oracle.d.ts +1 -1
- package/dist/database/helpers/geometry/dialects/oracle.js +5 -3
- package/dist/database/helpers/geometry/types.d.ts +1 -1
- package/dist/database/helpers/geometry/types.js +4 -2
- package/dist/database/helpers/schema/dialects/cockroachdb.d.ts +2 -1
- package/dist/database/helpers/schema/dialects/cockroachdb.js +4 -0
- package/dist/database/helpers/schema/dialects/mssql.d.ts +2 -1
- package/dist/database/helpers/schema/dialects/mssql.js +4 -0
- package/dist/database/helpers/schema/dialects/oracle.d.ts +2 -1
- package/dist/database/helpers/schema/dialects/oracle.js +4 -0
- package/dist/database/helpers/schema/dialects/postgres.d.ts +2 -1
- package/dist/database/helpers/schema/dialects/postgres.js +4 -0
- package/dist/database/helpers/schema/types.d.ts +5 -0
- package/dist/database/helpers/schema/types.js +3 -0
- package/dist/database/helpers/schema/utils/preprocess-bindings.d.ts +8 -0
- package/dist/database/helpers/schema/utils/preprocess-bindings.js +30 -0
- package/dist/database/index.js +6 -1
- package/dist/{utils/merge-permissions.d.ts → database/migrations/20240806A-permissions-policies.d.ts} +4 -1
- package/dist/database/migrations/20240806A-permissions-policies.js +338 -0
- package/dist/database/run-ast/lib/get-db-query.d.ts +4 -0
- package/dist/database/run-ast/lib/get-db-query.js +218 -0
- package/dist/database/run-ast/lib/parse-current-level.d.ts +7 -0
- package/dist/database/run-ast/lib/parse-current-level.js +41 -0
- package/dist/database/run-ast/run-ast.d.ts +7 -0
- package/dist/database/run-ast/run-ast.js +107 -0
- package/dist/database/{run-ast.d.ts → run-ast/types.d.ts} +3 -9
- package/dist/database/run-ast/types.js +1 -0
- package/dist/database/run-ast/utils/apply-case-when.d.ts +16 -0
- package/dist/database/run-ast/utils/apply-case-when.js +27 -0
- package/dist/database/run-ast/utils/apply-parent-filters.d.ts +3 -0
- package/dist/database/run-ast/utils/apply-parent-filters.js +55 -0
- package/dist/database/run-ast/utils/get-column-pre-processor.d.ts +10 -0
- package/dist/database/run-ast/utils/get-column-pre-processor.js +57 -0
- package/dist/database/run-ast/utils/get-field-alias.d.ts +2 -0
- package/dist/database/run-ast/utils/get-field-alias.js +4 -0
- package/dist/database/run-ast/utils/get-inner-query-column-pre-processor.d.ts +5 -0
- package/dist/database/run-ast/utils/get-inner-query-column-pre-processor.js +23 -0
- package/dist/database/run-ast/utils/merge-with-parent-items.d.ts +3 -0
- package/dist/database/run-ast/utils/merge-with-parent-items.js +87 -0
- package/dist/database/run-ast/utils/remove-temporary-fields.d.ts +3 -0
- package/dist/database/run-ast/utils/remove-temporary-fields.js +73 -0
- package/dist/database/run-ast/utils/with-preprocess-bindings.d.ts +2 -0
- package/dist/database/run-ast/utils/with-preprocess-bindings.js +14 -0
- package/dist/flows.js +3 -4
- package/dist/middleware/authenticate.js +2 -7
- package/dist/middleware/cache.js +1 -1
- package/dist/middleware/respond.js +1 -1
- package/dist/permissions/cache.d.ts +2 -0
- package/dist/permissions/cache.js +23 -0
- package/dist/permissions/lib/fetch-permissions.d.ts +11 -0
- package/dist/permissions/lib/fetch-permissions.js +56 -0
- package/dist/permissions/lib/fetch-policies.d.ts +14 -0
- package/dist/permissions/lib/fetch-policies.js +43 -0
- package/dist/permissions/lib/fetch-roles-tree.d.ts +3 -0
- package/dist/permissions/lib/fetch-roles-tree.js +28 -0
- package/dist/{services/permissions → permissions}/lib/with-app-minimal-permissions.d.ts +1 -1
- package/dist/permissions/lib/with-app-minimal-permissions.js +10 -0
- package/dist/permissions/modules/fetch-accountability-collection-access/fetch-accountability-collection-access.d.ts +7 -0
- package/dist/permissions/modules/fetch-accountability-collection-access/fetch-accountability-collection-access.js +56 -0
- package/dist/permissions/modules/fetch-accountability-policy-globals/fetch-accountability-policy-globals.d.ts +3 -0
- package/dist/permissions/modules/fetch-accountability-policy-globals/fetch-accountability-policy-globals.js +16 -0
- package/dist/permissions/modules/fetch-allowed-collections/fetch-allowed-collections.d.ts +8 -0
- package/dist/permissions/modules/fetch-allowed-collections/fetch-allowed-collections.js +24 -0
- package/dist/permissions/modules/fetch-allowed-field-map/fetch-allowed-field-map.d.ts +9 -0
- package/dist/permissions/modules/fetch-allowed-field-map/fetch-allowed-field-map.js +31 -0
- package/dist/permissions/modules/fetch-allowed-fields/fetch-allowed-fields.d.ts +16 -0
- package/dist/permissions/modules/fetch-allowed-fields/fetch-allowed-fields.js +27 -0
- package/dist/permissions/modules/fetch-global-access/fetch-global-access.d.ts +10 -0
- package/dist/permissions/modules/fetch-global-access/fetch-global-access.js +23 -0
- package/dist/permissions/modules/fetch-global-access/lib/fetch-global-access-for-roles.d.ts +5 -0
- package/dist/permissions/modules/fetch-global-access/lib/fetch-global-access-for-roles.js +7 -0
- package/dist/permissions/modules/fetch-global-access/lib/fetch-global-access-for-user.d.ts +5 -0
- package/dist/permissions/modules/fetch-global-access/lib/fetch-global-access-for-user.js +10 -0
- package/dist/permissions/modules/fetch-global-access/types.d.ts +4 -0
- package/dist/permissions/modules/fetch-global-access/types.js +1 -0
- package/dist/permissions/modules/fetch-global-access/utils/fetch-global-access-for-query.d.ts +4 -0
- package/dist/permissions/modules/fetch-global-access/utils/fetch-global-access-for-query.js +27 -0
- package/dist/permissions/modules/fetch-inconsistent-field-map/fetch-inconsistent-field-map.d.ts +12 -0
- package/dist/permissions/modules/fetch-inconsistent-field-map/fetch-inconsistent-field-map.js +32 -0
- package/dist/permissions/modules/fetch-policies-ip-access/fetch-policies-ip-access.d.ts +4 -0
- package/dist/permissions/modules/fetch-policies-ip-access/fetch-policies-ip-access.js +29 -0
- package/dist/permissions/modules/process-ast/lib/extract-fields-from-children.d.ts +4 -0
- package/dist/permissions/modules/process-ast/lib/extract-fields-from-children.js +49 -0
- package/dist/permissions/modules/process-ast/lib/extract-fields-from-query.d.ts +3 -0
- package/dist/permissions/modules/process-ast/lib/extract-fields-from-query.js +56 -0
- package/dist/permissions/modules/process-ast/lib/field-map-from-ast.d.ts +4 -0
- package/dist/permissions/modules/process-ast/lib/field-map-from-ast.js +8 -0
- package/dist/permissions/modules/process-ast/lib/inject-cases.d.ts +9 -0
- package/dist/permissions/modules/process-ast/lib/inject-cases.js +93 -0
- package/dist/permissions/modules/process-ast/process-ast.d.ts +9 -0
- package/dist/permissions/modules/process-ast/process-ast.js +39 -0
- package/dist/permissions/modules/process-ast/types.d.ts +18 -0
- package/dist/permissions/modules/process-ast/types.js +1 -0
- package/dist/permissions/modules/process-ast/utils/collections-in-field-map.d.ts +2 -0
- package/dist/permissions/modules/process-ast/utils/collections-in-field-map.js +7 -0
- package/dist/permissions/modules/process-ast/utils/dedupe-access.d.ts +12 -0
- package/dist/permissions/modules/process-ast/utils/dedupe-access.js +30 -0
- package/dist/permissions/modules/process-ast/utils/extract-paths-from-query.d.ts +15 -0
- package/dist/permissions/modules/process-ast/utils/extract-paths-from-query.js +60 -0
- package/dist/permissions/modules/process-ast/utils/find-related-collection.d.ts +3 -0
- package/dist/permissions/modules/process-ast/utils/find-related-collection.js +9 -0
- package/dist/permissions/modules/process-ast/utils/flatten-filter.d.ts +3 -0
- package/dist/permissions/modules/process-ast/utils/flatten-filter.js +34 -0
- package/dist/permissions/modules/process-ast/utils/format-a2o-key.d.ts +1 -0
- package/dist/permissions/modules/process-ast/utils/format-a2o-key.js +3 -0
- package/dist/permissions/modules/process-ast/utils/get-info-for-path.d.ts +5 -0
- package/dist/permissions/modules/process-ast/utils/get-info-for-path.js +7 -0
- package/dist/permissions/modules/process-ast/utils/has-item-permissions.d.ts +2 -0
- package/dist/permissions/modules/process-ast/utils/has-item-permissions.js +3 -0
- package/dist/permissions/modules/process-ast/utils/stringify-query-path.d.ts +2 -0
- package/dist/permissions/modules/process-ast/utils/stringify-query-path.js +3 -0
- package/dist/permissions/modules/process-ast/utils/validate-path/create-error.d.ts +3 -0
- package/dist/permissions/modules/process-ast/utils/validate-path/create-error.js +16 -0
- package/dist/permissions/modules/process-ast/utils/validate-path/validate-path-existence.d.ts +2 -0
- package/dist/permissions/modules/process-ast/utils/validate-path/validate-path-existence.js +12 -0
- package/dist/permissions/modules/process-ast/utils/validate-path/validate-path-permissions.d.ts +2 -0
- package/dist/permissions/modules/process-ast/utils/validate-path/validate-path-permissions.js +28 -0
- package/dist/permissions/modules/process-payload/lib/is-field-nullable.d.ts +5 -0
- package/dist/permissions/modules/process-payload/lib/is-field-nullable.js +12 -0
- package/dist/permissions/modules/process-payload/process-payload.d.ts +13 -0
- package/dist/permissions/modules/process-payload/process-payload.js +77 -0
- package/dist/permissions/modules/validate-access/lib/validate-collection-access.d.ts +12 -0
- package/dist/permissions/modules/validate-access/lib/validate-collection-access.js +11 -0
- package/dist/permissions/modules/validate-access/lib/validate-item-access.d.ts +9 -0
- package/dist/permissions/modules/validate-access/lib/validate-item-access.js +33 -0
- package/dist/permissions/modules/validate-access/validate-access.d.ts +14 -0
- package/dist/permissions/modules/validate-access/validate-access.js +28 -0
- package/dist/permissions/modules/validate-remaining-admin/validate-remaining-admin-count.d.ts +1 -0
- package/dist/permissions/modules/validate-remaining-admin/validate-remaining-admin-count.js +8 -0
- package/dist/permissions/modules/validate-remaining-admin/validate-remaining-admin-users.d.ts +5 -0
- package/dist/permissions/modules/validate-remaining-admin/validate-remaining-admin-users.js +10 -0
- package/dist/permissions/types.d.ts +6 -0
- package/dist/permissions/types.js +1 -0
- package/dist/permissions/utils/create-default-accountability.d.ts +2 -0
- package/dist/permissions/utils/create-default-accountability.js +11 -0
- package/dist/permissions/utils/extract-required-dynamic-variable-context.d.ts +8 -0
- package/dist/permissions/utils/extract-required-dynamic-variable-context.js +27 -0
- package/dist/permissions/utils/fetch-dynamic-variable-context.d.ts +9 -0
- package/dist/permissions/utils/fetch-dynamic-variable-context.js +43 -0
- package/dist/permissions/utils/filter-policies-by-ip.d.ts +2 -0
- package/dist/permissions/utils/filter-policies-by-ip.js +15 -0
- package/dist/permissions/utils/get-unaliased-field-key.d.ts +5 -0
- package/dist/permissions/utils/get-unaliased-field-key.js +17 -0
- package/dist/permissions/utils/process-permissions.d.ts +7 -0
- package/dist/permissions/utils/process-permissions.js +9 -0
- package/dist/permissions/utils/with-cache.d.ts +10 -0
- package/dist/permissions/utils/with-cache.js +25 -0
- package/dist/services/access.d.ts +10 -0
- package/dist/services/access.js +43 -0
- package/dist/services/activity.js +22 -10
- package/dist/services/assets.d.ts +2 -3
- package/dist/services/assets.js +10 -5
- package/dist/services/authentication.js +18 -18
- package/dist/services/collections.js +18 -17
- package/dist/services/fields.d.ts +0 -1
- package/dist/services/fields.js +54 -25
- package/dist/services/files.js +10 -3
- package/dist/services/graphql/index.d.ts +3 -3
- package/dist/services/graphql/index.js +126 -22
- package/dist/services/graphql/subscription.js +2 -4
- package/dist/services/import-export.d.ts +3 -1
- package/dist/services/import-export.js +67 -9
- package/dist/services/index.d.ts +3 -2
- package/dist/services/index.js +3 -2
- package/dist/services/items.js +115 -44
- package/dist/services/meta.js +60 -23
- package/dist/services/notifications.js +14 -6
- package/dist/services/payload.d.ts +9 -10
- package/dist/services/payload.js +18 -3
- package/dist/services/{permissions/index.d.ts → permissions.d.ts} +5 -7
- package/dist/services/{permissions/index.js → permissions.js} +30 -54
- package/dist/services/policies.d.ts +12 -0
- package/dist/services/policies.js +87 -0
- package/dist/services/relations.d.ts +0 -6
- package/dist/services/relations.js +27 -30
- package/dist/services/roles.d.ts +4 -12
- package/dist/services/roles.js +57 -424
- package/dist/services/shares.d.ts +0 -2
- package/dist/services/shares.js +12 -8
- package/dist/services/specifications.d.ts +2 -2
- package/dist/services/specifications.js +39 -27
- package/dist/services/users.d.ts +1 -5
- package/dist/services/users.js +78 -161
- package/dist/services/utils.js +11 -7
- package/dist/services/versions.d.ts +0 -2
- package/dist/services/versions.js +34 -10
- package/dist/telemetry/lib/get-report.js +2 -2
- package/dist/telemetry/utils/check-user-limits.d.ts +5 -0
- package/dist/telemetry/utils/check-user-limits.js +19 -0
- package/dist/types/ast.d.ts +43 -1
- package/dist/types/items.d.ts +11 -0
- package/dist/utils/apply-query.d.ts +11 -7
- package/dist/utils/apply-query.js +69 -11
- package/dist/utils/fetch-user-count/fetch-access-lookup.d.ts +19 -0
- package/dist/utils/fetch-user-count/fetch-access-lookup.js +23 -0
- package/dist/utils/fetch-user-count/fetch-access-roles.d.ts +16 -0
- package/dist/utils/fetch-user-count/fetch-access-roles.js +37 -0
- package/dist/utils/fetch-user-count/fetch-active-users.d.ts +6 -0
- package/dist/utils/fetch-user-count/fetch-active-users.js +3 -0
- package/dist/utils/fetch-user-count/fetch-user-count.d.ts +12 -0
- package/dist/utils/fetch-user-count/fetch-user-count.js +64 -0
- package/dist/utils/fetch-user-count/get-user-count-query.d.ts +20 -0
- package/dist/utils/fetch-user-count/get-user-count-query.js +17 -0
- package/dist/utils/get-accountability-for-role.js +16 -25
- package/dist/utils/get-accountability-for-token.js +17 -16
- package/dist/utils/get-cache-key.d.ts +1 -1
- package/dist/utils/get-cache-key.js +12 -1
- package/dist/utils/get-column.d.ts +2 -1
- package/dist/utils/get-column.js +1 -0
- package/dist/utils/get-service.js +5 -1
- package/dist/utils/reduce-schema.d.ts +4 -6
- package/dist/utils/reduce-schema.js +16 -32
- package/dist/utils/sanitize-schema.d.ts +1 -1
- package/dist/utils/validate-user-count-integrity.d.ts +13 -0
- package/dist/utils/validate-user-count-integrity.js +29 -0
- package/dist/websocket/authenticate.d.ts +0 -2
- package/dist/websocket/authenticate.js +0 -12
- package/dist/websocket/controllers/graphql.js +1 -4
- package/dist/websocket/controllers/hooks.js +4 -0
- package/dist/websocket/controllers/rest.js +0 -2
- package/dist/websocket/handlers/subscribe.js +0 -2
- package/dist/websocket/utils/items.d.ts +1 -1
- package/package.json +30 -29
- package/dist/database/run-ast.js +0 -458
- package/dist/middleware/check-ip.d.ts +0 -2
- package/dist/middleware/check-ip.js +0 -37
- package/dist/middleware/get-permissions.d.ts +0 -3
- package/dist/middleware/get-permissions.js +0 -10
- package/dist/services/authorization.d.ts +0 -17
- package/dist/services/authorization.js +0 -456
- package/dist/services/permissions/lib/with-app-minimal-permissions.js +0 -13
- package/dist/telemetry/utils/check-increased-user-limits.d.ts +0 -7
- package/dist/telemetry/utils/check-increased-user-limits.js +0 -25
- package/dist/telemetry/utils/get-role-counts-by-roles.d.ts +0 -6
- package/dist/telemetry/utils/get-role-counts-by-roles.js +0 -27
- package/dist/telemetry/utils/get-role-counts-by-users.d.ts +0 -11
- package/dist/telemetry/utils/get-role-counts-by-users.js +0 -34
- package/dist/telemetry/utils/get-user-count.d.ts +0 -8
- package/dist/telemetry/utils/get-user-count.js +0 -33
- package/dist/telemetry/utils/get-user-counts-by-roles.d.ts +0 -7
- package/dist/telemetry/utils/get-user-counts-by-roles.js +0 -35
- package/dist/utils/get-ast-from-query.d.ts +0 -13
- package/dist/utils/get-ast-from-query.js +0 -297
- package/dist/utils/get-permissions.d.ts +0 -2
- package/dist/utils/get-permissions.js +0 -150
- package/dist/utils/merge-permissions-for-share.d.ts +0 -4
- package/dist/utils/merge-permissions-for-share.js +0 -109
- package/dist/utils/merge-permissions.js +0 -95
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
import { processChunk, toBoolean } from '@directus/utils';
|
|
2
|
+
import { flatten, intersection, isEqual, merge, omit, uniq } from 'lodash-es';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { fetchPermissions } from '../../permissions/lib/fetch-permissions.js';
|
|
5
|
+
import { fetchPolicies } from '../../permissions/lib/fetch-policies.js';
|
|
6
|
+
import { fetchRolesTree } from '../../permissions/lib/fetch-roles-tree.js';
|
|
7
|
+
import { getSchema } from '../../utils/get-schema.js';
|
|
8
|
+
// Adapted from https://github.com/directus/directus/blob/141b8adbf4dd8e06530a7929f34e3fc68a522053/api/src/utils/merge-permissions.ts#L4
|
|
9
|
+
export function mergePermissions(strategy, ...permissions) {
|
|
10
|
+
const allPermissions = flatten(permissions);
|
|
11
|
+
const mergedPermissions = allPermissions
|
|
12
|
+
.reduce((acc, val) => {
|
|
13
|
+
const key = `${val.collection}__${val.action}`;
|
|
14
|
+
const current = acc.get(key);
|
|
15
|
+
acc.set(key, current ? mergePermission(strategy, current, val) : val);
|
|
16
|
+
return acc;
|
|
17
|
+
}, new Map())
|
|
18
|
+
.values();
|
|
19
|
+
return Array.from(mergedPermissions);
|
|
20
|
+
}
|
|
21
|
+
export function mergePermission(strategy, currentPerm, newPerm) {
|
|
22
|
+
const logicalKey = `_${strategy}`;
|
|
23
|
+
let { permissions, validation, fields, presets } = currentPerm;
|
|
24
|
+
if (newPerm.permissions) {
|
|
25
|
+
if (currentPerm.permissions && Object.keys(currentPerm.permissions)[0] === logicalKey) {
|
|
26
|
+
permissions = {
|
|
27
|
+
[logicalKey]: [
|
|
28
|
+
...currentPerm.permissions[logicalKey],
|
|
29
|
+
newPerm.permissions,
|
|
30
|
+
],
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
else if (currentPerm.permissions) {
|
|
34
|
+
// Empty {} supersedes other permissions in _OR merge
|
|
35
|
+
if (strategy === 'or' && (isEqual(currentPerm.permissions, {}) || isEqual(newPerm.permissions, {}))) {
|
|
36
|
+
permissions = {};
|
|
37
|
+
}
|
|
38
|
+
else {
|
|
39
|
+
permissions = {
|
|
40
|
+
[logicalKey]: [currentPerm.permissions, newPerm.permissions],
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
else {
|
|
45
|
+
permissions = {
|
|
46
|
+
[logicalKey]: [newPerm.permissions],
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
if (newPerm.validation) {
|
|
51
|
+
if (currentPerm.validation && Object.keys(currentPerm.validation)[0] === logicalKey) {
|
|
52
|
+
validation = {
|
|
53
|
+
[logicalKey]: [
|
|
54
|
+
...currentPerm.validation[logicalKey],
|
|
55
|
+
newPerm.validation,
|
|
56
|
+
],
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
else if (currentPerm.validation) {
|
|
60
|
+
// Empty {} supersedes other validations in _OR merge
|
|
61
|
+
if (strategy === 'or' && (isEqual(currentPerm.validation, {}) || isEqual(newPerm.validation, {}))) {
|
|
62
|
+
validation = {};
|
|
63
|
+
}
|
|
64
|
+
else {
|
|
65
|
+
validation = {
|
|
66
|
+
[logicalKey]: [currentPerm.validation, newPerm.validation],
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
else {
|
|
71
|
+
validation = {
|
|
72
|
+
[logicalKey]: [newPerm.validation],
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (newPerm.fields) {
|
|
77
|
+
if (Array.isArray(currentPerm.fields) && strategy === 'or') {
|
|
78
|
+
fields = uniq([...currentPerm.fields, ...newPerm.fields]);
|
|
79
|
+
}
|
|
80
|
+
else if (Array.isArray(currentPerm.fields) && strategy === 'and') {
|
|
81
|
+
fields = intersection(currentPerm.fields, newPerm.fields);
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
fields = newPerm.fields;
|
|
85
|
+
}
|
|
86
|
+
if (fields.includes('*'))
|
|
87
|
+
fields = ['*'];
|
|
88
|
+
}
|
|
89
|
+
if (newPerm.presets) {
|
|
90
|
+
presets = merge({}, presets, newPerm.presets);
|
|
91
|
+
}
|
|
92
|
+
return omit({
|
|
93
|
+
...currentPerm,
|
|
94
|
+
permissions,
|
|
95
|
+
validation,
|
|
96
|
+
fields,
|
|
97
|
+
presets,
|
|
98
|
+
}, ['id', 'system']);
|
|
99
|
+
}
|
|
100
|
+
async function fetchRoleAccess(roles, context) {
|
|
101
|
+
const roleAccess = {
|
|
102
|
+
admin_access: false,
|
|
103
|
+
app_access: false,
|
|
104
|
+
ip_access: null,
|
|
105
|
+
enforce_tfa: false,
|
|
106
|
+
};
|
|
107
|
+
const accessRows = await context
|
|
108
|
+
.knex('directus_access')
|
|
109
|
+
.select('directus_policies.id', 'directus_policies.admin_access', 'directus_policies.app_access', 'directus_policies.ip_access', 'directus_policies.enforce_tfa')
|
|
110
|
+
.where('role', 'in', roles)
|
|
111
|
+
.leftJoin('directus_policies', 'directus_policies.id', 'directus_access.policy');
|
|
112
|
+
const ipAccess = new Set();
|
|
113
|
+
for (const { admin_access, app_access, ip_access, enforce_tfa } of accessRows) {
|
|
114
|
+
roleAccess.admin_access ||= toBoolean(admin_access);
|
|
115
|
+
roleAccess.app_access ||= toBoolean(app_access);
|
|
116
|
+
roleAccess.enforce_tfa ||= toBoolean(enforce_tfa);
|
|
117
|
+
if (ip_access && ip_access.length) {
|
|
118
|
+
ip_access.split(',').forEach((ip) => ipAccess.add(ip));
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
if (ipAccess.size > 0) {
|
|
122
|
+
roleAccess.ip_access = Array.from(ipAccess).join(',');
|
|
123
|
+
}
|
|
124
|
+
return roleAccess;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* The public role used to be `null`, we gotta create a single new policy for the permissions
|
|
128
|
+
* previously attached to the public role (marked through `role = null`).
|
|
129
|
+
*/
|
|
130
|
+
const PUBLIC_POLICY_ID = 'abf8a154-5b1c-4a46-ac9c-7300570f4f17';
|
|
131
|
+
export async function up(knex) {
|
|
132
|
+
/////////////////////////////////////////////////////////////////////////////////////////////////
|
|
133
|
+
// If the policies table already exists the migration has already run
|
|
134
|
+
if (await knex.schema.hasTable('directus_policies')) {
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
/////////////////////////////////////////////////////////////////////////////////////////////////
|
|
138
|
+
// Create new policies table that mirrors previous Roles
|
|
139
|
+
await knex.schema.createTable('directus_policies', (table) => {
|
|
140
|
+
table.uuid('id').primary();
|
|
141
|
+
table.string('name', 100).notNullable();
|
|
142
|
+
table.string('icon', 64).notNullable().defaultTo('badge');
|
|
143
|
+
table.text('description');
|
|
144
|
+
table.text('ip_access');
|
|
145
|
+
table.boolean('enforce_tfa').defaultTo(false).notNullable();
|
|
146
|
+
table.boolean('admin_access').defaultTo(false).notNullable();
|
|
147
|
+
table.boolean('app_access').defaultTo(false).notNullable();
|
|
148
|
+
});
|
|
149
|
+
/////////////////////////////////////////////////////////////////////////////////////////////////
|
|
150
|
+
// Copy over all existing roles into new policies
|
|
151
|
+
const roles = await knex
|
|
152
|
+
.select('id', 'name', 'icon', 'description', 'ip_access', 'enforce_tfa', 'admin_access', 'app_access')
|
|
153
|
+
.from('directus_roles');
|
|
154
|
+
if (roles.length > 0) {
|
|
155
|
+
await processChunk(roles, 100, async (chunk) => {
|
|
156
|
+
await knex('directus_policies').insert(chunk);
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
await knex
|
|
160
|
+
.insert({
|
|
161
|
+
id: PUBLIC_POLICY_ID,
|
|
162
|
+
name: '$t:public_label',
|
|
163
|
+
icon: 'public',
|
|
164
|
+
description: '$t:public_description',
|
|
165
|
+
app_access: false,
|
|
166
|
+
})
|
|
167
|
+
.into('directus_policies');
|
|
168
|
+
// Change the admin policy description to $t:admin_policy_description
|
|
169
|
+
await knex('directus_policies')
|
|
170
|
+
.update({
|
|
171
|
+
description: '$t:admin_policy_description',
|
|
172
|
+
})
|
|
173
|
+
.where('description', 'LIKE', '$t:admin_description');
|
|
174
|
+
/////////////////////////////////////////////////////////////////////////////////////////////////
|
|
175
|
+
// Remove access control + add nesting to roles
|
|
176
|
+
await knex.schema.alterTable('directus_roles', (table) => {
|
|
177
|
+
table.dropColumn('ip_access');
|
|
178
|
+
table.dropColumn('enforce_tfa');
|
|
179
|
+
table.dropColumn('admin_access');
|
|
180
|
+
table.dropColumn('app_access');
|
|
181
|
+
table.uuid('parent').references('directus_roles.id');
|
|
182
|
+
});
|
|
183
|
+
/////////////////////////////////////////////////////////////////////////////////////////////////
|
|
184
|
+
// Link permissions to policies instead of roles
|
|
185
|
+
await knex.schema.alterTable('directus_permissions', (table) => {
|
|
186
|
+
table.uuid('policy').references('directus_policies.id').onDelete('CASCADE');
|
|
187
|
+
// Drop the foreign key constraint here in order to update `null` role to public policy ID
|
|
188
|
+
table.dropForeign('role');
|
|
189
|
+
});
|
|
190
|
+
await knex('directus_permissions')
|
|
191
|
+
.update({
|
|
192
|
+
role: PUBLIC_POLICY_ID,
|
|
193
|
+
})
|
|
194
|
+
.whereNull('role');
|
|
195
|
+
await knex('directus_permissions').update({
|
|
196
|
+
policy: knex.ref('role'),
|
|
197
|
+
});
|
|
198
|
+
await knex.schema.alterTable('directus_permissions', (table) => {
|
|
199
|
+
table.dropColumns('role');
|
|
200
|
+
table.dropNullable('policy');
|
|
201
|
+
});
|
|
202
|
+
/////////////////////////////////////////////////////////////////////////////////////////////////
|
|
203
|
+
// Setup junction table between roles/users and policies
|
|
204
|
+
// This could be a A2O style setup with a collection/item field rather than individual foreign
|
|
205
|
+
// keys, but we want to be able to show the reverse-relationship on the individual policies as
|
|
206
|
+
// well, which would require the O2A type to exist in Directus which currently doesn't.
|
|
207
|
+
// Shouldn't be the end of the world here, as we know we're only attaching policies to two other
|
|
208
|
+
// collections.
|
|
209
|
+
await knex.schema.createTable('directus_access', (table) => {
|
|
210
|
+
table.uuid('id').primary();
|
|
211
|
+
table.uuid('role').references('directus_roles.id').nullable().onDelete('CASCADE');
|
|
212
|
+
table.uuid('user').references('directus_users.id').nullable().onDelete('CASCADE');
|
|
213
|
+
table.uuid('policy').references('directus_policies.id').notNullable().onDelete('CASCADE');
|
|
214
|
+
table.integer('sort');
|
|
215
|
+
});
|
|
216
|
+
/////////////////////////////////////////////////////////////////////////////////////////////////
|
|
217
|
+
// Attach policies to existing roles for backwards compatibility
|
|
218
|
+
const policyAttachments = roles.map((role) => ({
|
|
219
|
+
id: randomUUID(),
|
|
220
|
+
role: role.id,
|
|
221
|
+
user: null,
|
|
222
|
+
policy: role.id,
|
|
223
|
+
sort: 1,
|
|
224
|
+
}));
|
|
225
|
+
await processChunk(policyAttachments, 100, async (chunk) => {
|
|
226
|
+
await knex('directus_access').insert(chunk);
|
|
227
|
+
});
|
|
228
|
+
await knex('directus_access').insert({
|
|
229
|
+
id: randomUUID(),
|
|
230
|
+
role: null,
|
|
231
|
+
user: null,
|
|
232
|
+
policy: PUBLIC_POLICY_ID,
|
|
233
|
+
sort: 1,
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
export async function down(knex) {
|
|
237
|
+
/////////////////////////////////////////////////////////////////////////////////////////////////
|
|
238
|
+
// Reinstate access control fields on directus roles
|
|
239
|
+
await knex.schema.alterTable('directus_roles', (table) => {
|
|
240
|
+
table.text('ip_access');
|
|
241
|
+
table.boolean('enforce_tfa').defaultTo(false).notNullable();
|
|
242
|
+
table.boolean('admin_access').defaultTo(false).notNullable();
|
|
243
|
+
table.boolean('app_access').defaultTo(true).notNullable();
|
|
244
|
+
});
|
|
245
|
+
/////////////////////////////////////////////////////////////////////////////////////////////////
|
|
246
|
+
// Copy policy access control rules back to roles
|
|
247
|
+
const originalPermissions = await knex
|
|
248
|
+
.select('id')
|
|
249
|
+
.from('directus_permissions')
|
|
250
|
+
.whereNot({ policy: PUBLIC_POLICY_ID });
|
|
251
|
+
await knex.schema.alterTable('directus_permissions', (table) => {
|
|
252
|
+
table.uuid('role').nullable();
|
|
253
|
+
table.setNullable('policy');
|
|
254
|
+
});
|
|
255
|
+
const context = { knex, schema: await getSchema() };
|
|
256
|
+
// fetch all roles
|
|
257
|
+
const roles = await knex.select('id').from('directus_roles');
|
|
258
|
+
// simulate Public Role
|
|
259
|
+
roles.push({ id: null });
|
|
260
|
+
// role permissions to be inserted once all processing is completed
|
|
261
|
+
const rolePermissions = [];
|
|
262
|
+
for (const role of roles) {
|
|
263
|
+
const roleTree = await fetchRolesTree(role.id, knex);
|
|
264
|
+
let roleAccess = null;
|
|
265
|
+
if (role.id !== null) {
|
|
266
|
+
roleAccess = await fetchRoleAccess(roleTree, context);
|
|
267
|
+
await knex('directus_roles').update(roleAccess).where({ id: role.id });
|
|
268
|
+
}
|
|
269
|
+
if (roleAccess === null || !roleAccess.admin_access) {
|
|
270
|
+
// fetch all of the roles policies
|
|
271
|
+
const policies = await fetchPolicies({ roles: roleTree, user: null, ip: null }, context);
|
|
272
|
+
// fetch all of the policies permissions
|
|
273
|
+
const rawPermissions = await fetchPermissions({
|
|
274
|
+
accountability: { role: null, roles: roleTree, user: null, app: roleAccess?.app_access || false },
|
|
275
|
+
policies,
|
|
276
|
+
bypassDynamicVariableProcessing: true,
|
|
277
|
+
}, context);
|
|
278
|
+
// merge all permissions to single version (v10) and save for later use
|
|
279
|
+
mergePermissions('or', rawPermissions).forEach((permission) => {
|
|
280
|
+
// System permissions are automatically populated
|
|
281
|
+
if (permission.system) {
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
// convert merged permissions to storage ready format
|
|
285
|
+
if (Array.isArray(permission.fields)) {
|
|
286
|
+
permission.fields = permission.fields.join(',');
|
|
287
|
+
}
|
|
288
|
+
if (permission.permissions) {
|
|
289
|
+
permission.permissions = JSON.stringify(permission.permissions);
|
|
290
|
+
}
|
|
291
|
+
if (permission.validation) {
|
|
292
|
+
permission.validation = JSON.stringify(permission.validation);
|
|
293
|
+
}
|
|
294
|
+
if (permission.presets) {
|
|
295
|
+
permission.presets = JSON.stringify(permission.presets);
|
|
296
|
+
}
|
|
297
|
+
rolePermissions.push({ role: role.id, ...omit(permission, ['id', 'policy']) });
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
/////////////////////////////////////////////////////////////////////////////////////////////////
|
|
302
|
+
// Remove role nesting support
|
|
303
|
+
await knex.schema.alterTable('directus_roles', (table) => {
|
|
304
|
+
table.dropForeign('parent');
|
|
305
|
+
table.dropColumn('parent');
|
|
306
|
+
});
|
|
307
|
+
/////////////////////////////////////////////////////////////////////////////////////////////////
|
|
308
|
+
// Drop all permissions that are only attached to a user
|
|
309
|
+
// TODO query all policies that are attached to a user and delete their permissions,
|
|
310
|
+
// since we don't know were to put them now and it'll cause a foreign key problem
|
|
311
|
+
// as soon as we reference directus_roles in directus_permissions again
|
|
312
|
+
/////////////////////////////////////////////////////////////////////////////////////////////////
|
|
313
|
+
// Drop policy attachments
|
|
314
|
+
await knex.schema.dropTable('directus_access');
|
|
315
|
+
/////////////////////////////////////////////////////////////////////////////////////////////////
|
|
316
|
+
// Reattach permissions to roles instead of policies
|
|
317
|
+
await knex('directus_permissions')
|
|
318
|
+
.update({
|
|
319
|
+
role: null,
|
|
320
|
+
})
|
|
321
|
+
.where({ role: PUBLIC_POLICY_ID });
|
|
322
|
+
// remove all v11 permissions
|
|
323
|
+
await processChunk(originalPermissions, 100, async (chunk) => {
|
|
324
|
+
await knex('directus_permissions').delete(chunk);
|
|
325
|
+
});
|
|
326
|
+
// insert all v10 permissions
|
|
327
|
+
await processChunk(rolePermissions, 100, async (chunk) => {
|
|
328
|
+
await knex('directus_permissions').insert(chunk);
|
|
329
|
+
});
|
|
330
|
+
await knex.schema.alterTable('directus_permissions', (table) => {
|
|
331
|
+
table.uuid('role').references('directus_roles.id').alter();
|
|
332
|
+
table.dropForeign('policy');
|
|
333
|
+
table.dropColumn('policy');
|
|
334
|
+
});
|
|
335
|
+
/////////////////////////////////////////////////////////////////////////////////////////////////
|
|
336
|
+
// Drop policies table
|
|
337
|
+
await knex.schema.dropTable('directus_policies');
|
|
338
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { Filter, Query, SchemaOverview } from '@directus/types';
|
|
2
|
+
import type { Knex } from 'knex';
|
|
3
|
+
import type { FieldNode, FunctionFieldNode, O2MNode } from '../../../types/ast.js';
|
|
4
|
+
export declare function getDBQuery(schema: SchemaOverview, knex: Knex, table: string, fieldNodes: (FieldNode | FunctionFieldNode)[], o2mNodes: O2MNode[], query: Query, cases: Filter[]): Knex.QueryBuilder;
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import { useEnv } from '@directus/env';
|
|
2
|
+
import { cloneDeep } from 'lodash-es';
|
|
3
|
+
import applyQuery, { applyLimit, applySort, generateAlias } from '../../../utils/apply-query.js';
|
|
4
|
+
import { getCollectionFromAlias } from '../../../utils/get-collection-from-alias.js';
|
|
5
|
+
import { getColumn } from '../../../utils/get-column.js';
|
|
6
|
+
import { getHelpers } from '../../helpers/index.js';
|
|
7
|
+
import { applyCaseWhen } from '../utils/apply-case-when.js';
|
|
8
|
+
import { getColumnPreprocessor } from '../utils/get-column-pre-processor.js';
|
|
9
|
+
import { getNodeAlias } from '../utils/get-field-alias.js';
|
|
10
|
+
import { getInnerQueryColumnPreProcessor } from '../utils/get-inner-query-column-pre-processor.js';
|
|
11
|
+
import { withPreprocessBindings } from '../utils/with-preprocess-bindings.js';
|
|
12
|
+
export function getDBQuery(schema, knex, table, fieldNodes, o2mNodes, query, cases) {
|
|
13
|
+
const aliasMap = Object.create(null);
|
|
14
|
+
const env = useEnv();
|
|
15
|
+
const preProcess = getColumnPreprocessor(knex, schema, table, cases, aliasMap);
|
|
16
|
+
const queryCopy = cloneDeep(query);
|
|
17
|
+
const helpers = getHelpers(knex);
|
|
18
|
+
const hasCaseWhen = o2mNodes.some((node) => node.whenCase && node.whenCase.length > 0) ||
|
|
19
|
+
fieldNodes.some((node) => node.whenCase && node.whenCase.length > 0);
|
|
20
|
+
queryCopy.limit = typeof queryCopy.limit === 'number' ? queryCopy.limit : Number(env['QUERY_LIMIT_DEFAULT']);
|
|
21
|
+
// Queries with aggregates and groupBy will not have duplicate result
|
|
22
|
+
if (queryCopy.aggregate || queryCopy.group) {
|
|
23
|
+
const flatQuery = knex.from(table);
|
|
24
|
+
// Map the group fields to their respective field nodes
|
|
25
|
+
const groupWhenCases = hasCaseWhen
|
|
26
|
+
? queryCopy.group?.map((field) => fieldNodes.find(({ fieldKey }) => fieldKey === field)?.whenCase ?? [])
|
|
27
|
+
: undefined;
|
|
28
|
+
const dbQuery = applyQuery(knex, table, flatQuery, queryCopy, schema, cases, { aliasMap, groupWhenCases }).query;
|
|
29
|
+
flatQuery.select(fieldNodes.map((node) => preProcess(node)));
|
|
30
|
+
withPreprocessBindings(knex, dbQuery);
|
|
31
|
+
return dbQuery;
|
|
32
|
+
}
|
|
33
|
+
const primaryKey = schema.collections[table].primary;
|
|
34
|
+
let dbQuery = knex.from(table);
|
|
35
|
+
let sortRecords;
|
|
36
|
+
const innerQuerySortRecords = [];
|
|
37
|
+
let hasMultiRelationalSort;
|
|
38
|
+
if (queryCopy.sort) {
|
|
39
|
+
const sortResult = applySort(knex, schema, dbQuery, queryCopy, table, aliasMap, true);
|
|
40
|
+
if (sortResult) {
|
|
41
|
+
sortRecords = sortResult.sortRecords;
|
|
42
|
+
hasMultiRelationalSort = sortResult.hasMultiRelationalSort;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
const { hasMultiRelationalFilter } = applyQuery(knex, table, dbQuery, queryCopy, schema, cases, {
|
|
46
|
+
aliasMap,
|
|
47
|
+
isInnerQuery: true,
|
|
48
|
+
hasMultiRelationalSort,
|
|
49
|
+
});
|
|
50
|
+
const needsInnerQuery = hasMultiRelationalSort || hasMultiRelationalFilter;
|
|
51
|
+
if (needsInnerQuery) {
|
|
52
|
+
dbQuery.select(`${table}.${primaryKey}`);
|
|
53
|
+
// Only add distinct if there are no case/when constructs, since otherwise we rely on group by
|
|
54
|
+
if (!hasCaseWhen)
|
|
55
|
+
dbQuery.distinct();
|
|
56
|
+
}
|
|
57
|
+
else {
|
|
58
|
+
dbQuery.select(fieldNodes.map((node) => preProcess(node)));
|
|
59
|
+
// Add flags for o2m fields with case/when to the let the DB to the partial item permissions
|
|
60
|
+
dbQuery.select(o2mNodes
|
|
61
|
+
.filter((node) => node.whenCase && node.whenCase.length > 0)
|
|
62
|
+
.map((node) => {
|
|
63
|
+
const columnCases = node.whenCase.map((index) => cases[index]);
|
|
64
|
+
return applyCaseWhen({
|
|
65
|
+
column: knex.raw(1),
|
|
66
|
+
columnCases,
|
|
67
|
+
aliasMap,
|
|
68
|
+
cases,
|
|
69
|
+
table,
|
|
70
|
+
alias: node.fieldKey,
|
|
71
|
+
}, { knex, schema });
|
|
72
|
+
}));
|
|
73
|
+
}
|
|
74
|
+
if (sortRecords) {
|
|
75
|
+
// Clears the order if any, eg: from MSSQL offset
|
|
76
|
+
dbQuery.clear('order');
|
|
77
|
+
if (needsInnerQuery) {
|
|
78
|
+
let orderByString = '';
|
|
79
|
+
const orderByFields = [];
|
|
80
|
+
sortRecords.map((sortRecord) => {
|
|
81
|
+
if (orderByString.length !== 0) {
|
|
82
|
+
orderByString += ', ';
|
|
83
|
+
}
|
|
84
|
+
const sortAlias = `sort_${generateAlias()}`;
|
|
85
|
+
if (sortRecord.column.includes('.')) {
|
|
86
|
+
const [alias, field] = sortRecord.column.split('.');
|
|
87
|
+
const originalCollectionName = getCollectionFromAlias(alias, aliasMap);
|
|
88
|
+
dbQuery.select(getColumn(knex, alias, field, sortAlias, schema, { originalCollectionName }));
|
|
89
|
+
orderByString += `?? ${sortRecord.order}`;
|
|
90
|
+
orderByFields.push(getColumn(knex, alias, field, false, schema, { originalCollectionName }));
|
|
91
|
+
}
|
|
92
|
+
else {
|
|
93
|
+
dbQuery.select(getColumn(knex, table, sortRecord.column, sortAlias, schema));
|
|
94
|
+
orderByString += `?? ${sortRecord.order}`;
|
|
95
|
+
orderByFields.push(getColumn(knex, table, sortRecord.column, false, schema));
|
|
96
|
+
}
|
|
97
|
+
innerQuerySortRecords.push({ alias: sortAlias, order: sortRecord.order });
|
|
98
|
+
});
|
|
99
|
+
if (hasMultiRelationalSort) {
|
|
100
|
+
dbQuery = helpers.schema.applyMultiRelationalSort(knex, dbQuery, table, primaryKey, orderByString, orderByFields);
|
|
101
|
+
// Start order by with directus_row_number. The directus_row_number is derived from a window function that
|
|
102
|
+
// is ordered by the sort fields within every primary key partition. That ensures that the result with the
|
|
103
|
+
// row number = 1 is the top-most row of every partition, according to the selected sort fields.
|
|
104
|
+
// Since the only relevant result is the first row of this partition, adding the directus_row_number to the
|
|
105
|
+
// order by here ensures that all rows with a directus_row_number = 1 show up first in the inner query result,
|
|
106
|
+
// and are correctly truncated by the limit, but not earlier.
|
|
107
|
+
orderByString = `?? asc, ${orderByString}`;
|
|
108
|
+
orderByFields.unshift(knex.ref('directus_row_number'));
|
|
109
|
+
}
|
|
110
|
+
dbQuery.orderByRaw(orderByString, orderByFields);
|
|
111
|
+
}
|
|
112
|
+
else {
|
|
113
|
+
sortRecords.map((sortRecord) => {
|
|
114
|
+
if (sortRecord.column.includes('.')) {
|
|
115
|
+
const [alias, field] = sortRecord.column.split('.');
|
|
116
|
+
sortRecord.column = getColumn(knex, alias, field, false, schema, {
|
|
117
|
+
originalCollectionName: getCollectionFromAlias(alias, aliasMap),
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
else {
|
|
121
|
+
sortRecord.column = getColumn(knex, table, sortRecord.column, false, schema);
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
dbQuery.orderBy(sortRecords);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
if (!needsInnerQuery)
|
|
128
|
+
return dbQuery;
|
|
129
|
+
const innerCaseWhenAliasPrefix = generateAlias();
|
|
130
|
+
if (hasCaseWhen) {
|
|
131
|
+
/* If there are cases, we need to employ a trick in order to evaluate the case/when structure in the inner query,
|
|
132
|
+
while passing the result of the evaluation to the outer query. The case/when needs to be evaluated in the inner
|
|
133
|
+
query since only there all joined in tables, that might be required for the case/when, are available.
|
|
134
|
+
|
|
135
|
+
The problem is, that the resulting columns can not be directly selected in the inner query,
|
|
136
|
+
as a `SELECT DISTINCT` does not work for all datatypes in all vendors.
|
|
137
|
+
|
|
138
|
+
So instead of having an inner query which might look like this:
|
|
139
|
+
|
|
140
|
+
SELECT DISTINCT ...,
|
|
141
|
+
CASE WHEN <condition> THEN <actual-column> END AS <alias>
|
|
142
|
+
|
|
143
|
+
a group-by query is generated.
|
|
144
|
+
|
|
145
|
+
Another problem is that all not all rows with the same primary key are guaranteed to have the same value for
|
|
146
|
+
the columns with the case/when, so we to `or` those together, but counting the number of flags in a group by
|
|
147
|
+
operation. This way the flag is set to > 0 if any of the rows in the group allows access to the column.
|
|
148
|
+
|
|
149
|
+
The inner query only evaluates the condition and passes up or-ed flag, that is used in the wrapper query to select
|
|
150
|
+
the actual column:
|
|
151
|
+
|
|
152
|
+
SELECT ...,
|
|
153
|
+
COUNT (CASE WHEN <condition> THEN 1 END) AS <random-prefix>_<alias>
|
|
154
|
+
...
|
|
155
|
+
GROUP BY <primary-key>
|
|
156
|
+
|
|
157
|
+
Then, in the wrapper query there is no need to evaluate the condition again, but instead rely on the flag:
|
|
158
|
+
|
|
159
|
+
SELECT ...,
|
|
160
|
+
CASE WHEN `inner`.<random-prefix>_<alias> > 0 THEN <actual-column> END AS <alias>
|
|
161
|
+
*/
|
|
162
|
+
const innerPreprocess = getInnerQueryColumnPreProcessor(knex, schema, table, cases, aliasMap, innerCaseWhenAliasPrefix);
|
|
163
|
+
// To optimize the query we avoid having unnecessary columns in the inner query, that don't have a caseWhen, since
|
|
164
|
+
// they are selected in the outer query directly
|
|
165
|
+
dbQuery.select(fieldNodes.map(innerPreprocess).filter((x) => x !== null));
|
|
166
|
+
// In addition to the regular columns select a flag that indicates if a user has access to o2m related field
|
|
167
|
+
// based on the case/when of that field.
|
|
168
|
+
dbQuery.select(o2mNodes.map(innerPreprocess).filter((x) => x !== null));
|
|
169
|
+
const groupByFields = [knex.raw('??.??', [table, primaryKey])];
|
|
170
|
+
if (hasMultiRelationalSort) {
|
|
171
|
+
// Sort fields that are not directly in the table the primary key is from need to be included in the group
|
|
172
|
+
// by clause, otherwise this causes problems on some DBs
|
|
173
|
+
groupByFields.push(...innerQuerySortRecords.map(({ alias }) => knex.raw('??', alias)));
|
|
174
|
+
}
|
|
175
|
+
dbQuery.groupBy(groupByFields);
|
|
176
|
+
}
|
|
177
|
+
const wrapperQuery = knex
|
|
178
|
+
.from(table)
|
|
179
|
+
.innerJoin(knex.raw('??', dbQuery.as('inner')), `${table}.${primaryKey}`, `inner.${primaryKey}`);
|
|
180
|
+
if (!hasCaseWhen) {
|
|
181
|
+
// No need for case/when in the wrapper query, just select the preprocessed columns
|
|
182
|
+
wrapperQuery.select(fieldNodes.map((node) => preProcess(node)));
|
|
183
|
+
}
|
|
184
|
+
else {
|
|
185
|
+
// This applies a simplified case/when construct in the wrapper query, that only looks at flag > 1
|
|
186
|
+
// Distinguish between column with and without case/when and handle them differently
|
|
187
|
+
const plainColumns = fieldNodes.filter((fieldNode) => !fieldNode.whenCase || fieldNode.whenCase.length === 0);
|
|
188
|
+
const whenCaseColumns = fieldNodes.filter((fieldNode) => fieldNode.whenCase && fieldNode.whenCase.length > 0);
|
|
189
|
+
// Select the plain columns
|
|
190
|
+
wrapperQuery.select(plainColumns.map((node) => preProcess(node)));
|
|
191
|
+
// Select the case/when columns based on the flag from the inner query
|
|
192
|
+
wrapperQuery.select(whenCaseColumns.map((fieldNode) => {
|
|
193
|
+
const alias = getNodeAlias(fieldNode);
|
|
194
|
+
const innerAlias = `${innerCaseWhenAliasPrefix}_${alias}`;
|
|
195
|
+
// Preprocess the column without the case/when, since that is applied in a simpler fashion in the select
|
|
196
|
+
const column = preProcess({ ...fieldNode, whenCase: [] }, { noAlias: true });
|
|
197
|
+
return knex.raw(`CASE WHEN ??.?? > 0 THEN ?? END as ??`, ['inner', innerAlias, column, alias]);
|
|
198
|
+
}));
|
|
199
|
+
// Pass the flags of o2m fields up through the wrapper query
|
|
200
|
+
wrapperQuery.select(o2mNodes
|
|
201
|
+
.filter((node) => node.whenCase && node.whenCase.length > 0)
|
|
202
|
+
.map((node) => {
|
|
203
|
+
const alias = node.fieldKey;
|
|
204
|
+
const innerAlias = `${innerCaseWhenAliasPrefix}_${alias}`;
|
|
205
|
+
return knex.raw(`CASE WHEN ??.?? > 0 THEN 1 END as ??`, ['inner', innerAlias, alias]);
|
|
206
|
+
}));
|
|
207
|
+
}
|
|
208
|
+
if (sortRecords) {
|
|
209
|
+
innerQuerySortRecords.map((innerQuerySortRecord) => {
|
|
210
|
+
wrapperQuery.orderBy(`inner.${innerQuerySortRecord.alias}`, innerQuerySortRecord.order);
|
|
211
|
+
});
|
|
212
|
+
if (hasMultiRelationalSort) {
|
|
213
|
+
wrapperQuery.where('inner.directus_row_number', '=', 1);
|
|
214
|
+
applyLimit(knex, wrapperQuery, queryCopy.limit);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
return wrapperQuery;
|
|
218
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Query, SchemaOverview } from '@directus/types';
|
|
2
|
+
import type { FieldNode, FunctionFieldNode, NestedCollectionNode } from '../../../types/ast.js';
|
|
3
|
+
export declare function parseCurrentLevel(schema: SchemaOverview, collection: string, children: (NestedCollectionNode | FieldNode | FunctionFieldNode)[], query: Query): Promise<{
|
|
4
|
+
fieldNodes: FieldNode[];
|
|
5
|
+
nestedCollectionNodes: NestedCollectionNode[];
|
|
6
|
+
primaryKeyField: string;
|
|
7
|
+
}>;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { parseFilterKey } from '../../../utils/parse-filter-key.js';
|
|
2
|
+
export async function parseCurrentLevel(schema, collection, children, query) {
|
|
3
|
+
const primaryKeyField = schema.collections[collection].primary;
|
|
4
|
+
const columnsInCollection = Object.keys(schema.collections[collection].fields);
|
|
5
|
+
const columnsToSelectInternal = [];
|
|
6
|
+
const nestedCollectionNodes = [];
|
|
7
|
+
for (const child of children) {
|
|
8
|
+
if (child.type === 'field' || child.type === 'functionField') {
|
|
9
|
+
const { fieldName } = parseFilterKey(child.name);
|
|
10
|
+
if (columnsInCollection.includes(fieldName)) {
|
|
11
|
+
columnsToSelectInternal.push(child.fieldKey);
|
|
12
|
+
}
|
|
13
|
+
continue;
|
|
14
|
+
}
|
|
15
|
+
if (!child.relation)
|
|
16
|
+
continue;
|
|
17
|
+
if (child.type === 'm2o') {
|
|
18
|
+
columnsToSelectInternal.push(child.relation.field);
|
|
19
|
+
}
|
|
20
|
+
if (child.type === 'a2o') {
|
|
21
|
+
columnsToSelectInternal.push(child.relation.field);
|
|
22
|
+
columnsToSelectInternal.push(child.relation.meta.one_collection_field);
|
|
23
|
+
}
|
|
24
|
+
nestedCollectionNodes.push(child);
|
|
25
|
+
}
|
|
26
|
+
const isAggregate = (query.group || (query.aggregate && Object.keys(query.aggregate).length > 0)) ?? false;
|
|
27
|
+
/** Always fetch primary key in case there's a nested relation that needs it. Aggregate payloads
|
|
28
|
+
* can't have nested relational fields
|
|
29
|
+
*/
|
|
30
|
+
if (isAggregate === false && columnsToSelectInternal.includes(primaryKeyField) === false) {
|
|
31
|
+
columnsToSelectInternal.push(primaryKeyField);
|
|
32
|
+
}
|
|
33
|
+
/** Make sure select list has unique values */
|
|
34
|
+
const columnsToSelect = [...new Set(columnsToSelectInternal)];
|
|
35
|
+
const fieldNodes = columnsToSelect.map((column) => children.find((childNode) => (childNode.type === 'field' || childNode.type === 'functionField') && childNode.fieldKey === column) ?? {
|
|
36
|
+
type: 'field',
|
|
37
|
+
name: column,
|
|
38
|
+
fieldKey: column,
|
|
39
|
+
});
|
|
40
|
+
return { fieldNodes, nestedCollectionNodes, primaryKeyField };
|
|
41
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Item, SchemaOverview } from '@directus/types';
|
|
2
|
+
import type { AST, NestedCollectionNode } from '../../types/ast.js';
|
|
3
|
+
import type { RunASTOptions } from './types.js';
|
|
4
|
+
/**
|
|
5
|
+
* Execute a given AST using Knex. Returns array of items based on requested AST.
|
|
6
|
+
*/
|
|
7
|
+
export declare function runAst(originalAST: AST | NestedCollectionNode, schema: SchemaOverview, options?: RunASTOptions): Promise<null | Item | Item[]>;
|