@strapi/permissions 4.12.0-beta.5 → 4.12.1

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.
@@ -0,0 +1,2 @@
1
+ import * as permission from './permission';
2
+ export { permission };
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.permission = void 0;
27
+ const permission = __importStar(require("./permission"));
28
+ exports.permission = permission;
29
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/domain/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,yDAA2C;AAElC,gCAAU"}
@@ -0,0 +1,24 @@
1
+ /// <reference types="lodash" />
2
+ import _ from 'lodash/fp';
3
+ declare const sanitizePermissionFields: _.LodashPick2x1;
4
+ export interface Permission {
5
+ action: string;
6
+ subject?: string | object | null;
7
+ properties?: object;
8
+ conditions?: string[];
9
+ }
10
+ /**
11
+ * Create a new permission based on given attributes
12
+ *
13
+ * @param {object} attributes
14
+ */
15
+ declare const create: <T>(object: T | null | undefined) => Pick<Permission, "subject" | "properties" | "conditions"> & Partial<T>;
16
+ /**
17
+ * Add a condition to a permission
18
+ */
19
+ declare const addCondition: import("lodash").CurriedFunction2<string, Permission, Permission>;
20
+ /**
21
+ * Gets a property or a part of a property from a permission.
22
+ */
23
+ declare const getProperty: (...args: any[]) => any;
24
+ export { create, sanitizePermissionFields, addCondition, getProperty };
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getProperty = exports.addCondition = exports.sanitizePermissionFields = exports.create = void 0;
7
+ const fp_1 = __importDefault(require("lodash/fp"));
8
+ const PERMISSION_FIELDS = ['action', 'subject', 'properties', 'conditions'];
9
+ const sanitizePermissionFields = fp_1.default.pick(PERMISSION_FIELDS);
10
+ exports.sanitizePermissionFields = sanitizePermissionFields;
11
+ /**
12
+ * Creates a permission with default values for optional properties
13
+ */
14
+ const getDefaultPermission = () => ({
15
+ conditions: [],
16
+ properties: {},
17
+ subject: null,
18
+ });
19
+ /**
20
+ * Create a new permission based on given attributes
21
+ *
22
+ * @param {object} attributes
23
+ */
24
+ const create = fp_1.default.pipe(fp_1.default.pick(PERMISSION_FIELDS), fp_1.default.merge(getDefaultPermission()));
25
+ exports.create = create;
26
+ /**
27
+ * Add a condition to a permission
28
+ */
29
+ const addCondition = fp_1.default.curry((condition, permission) => {
30
+ const { conditions } = permission;
31
+ const newConditions = Array.isArray(conditions)
32
+ ? fp_1.default.uniq(conditions.concat(condition))
33
+ : [condition];
34
+ return fp_1.default.set('conditions', newConditions, permission);
35
+ });
36
+ exports.addCondition = addCondition;
37
+ /**
38
+ * Gets a property or a part of a property from a permission.
39
+ */
40
+ const getProperty = fp_1.default.curry((property, permission) => fp_1.default.get(`properties.${property}`, permission));
41
+ exports.getProperty = getProperty;
42
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/domain/permission/index.ts"],"names":[],"mappings":";;;;;;AAAA,mDAA0B;AAE1B,MAAM,iBAAiB,GAAG,CAAC,QAAQ,EAAE,SAAS,EAAE,YAAY,EAAE,YAAY,CAAU,CAAC;AAErF,MAAM,wBAAwB,GAAG,YAAC,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC;AAgD1C,4DAAwB;AAvCzC;;GAEG;AACH,MAAM,oBAAoB,GAAG,GAA8D,EAAE,CAAC,CAAC;IAC7F,UAAU,EAAE,EAAE;IACd,UAAU,EAAE,EAAE;IACd,OAAO,EAAE,IAAI;CACd,CAAC,CAAC;AAEH;;;;GAIG;AACH,MAAM,MAAM,GAAG,YAAC,CAAC,IAAI,CAAC,YAAC,CAAC,IAAI,CAAC,iBAAiB,CAAC,EAAE,YAAC,CAAC,KAAK,CAAC,oBAAoB,EAAE,CAAC,CAAC,CAAC;AAyBzE,wBAAM;AAvBf;;GAEG;AACH,MAAM,YAAY,GAAG,YAAC,CAAC,KAAK,CAAC,CAAC,SAAiB,EAAE,UAAsB,EAAc,EAAE;IACrF,MAAM,EAAE,UAAU,EAAE,GAAG,UAAU,CAAC;IAElC,MAAM,aAAa,GAAG,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC;QAC7C,CAAC,CAAC,YAAC,CAAC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;QACtC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;IAEhB,OAAO,YAAC,CAAC,GAAG,CAAC,YAAY,EAAE,aAAa,EAAE,UAAU,CAAC,CAAC;AACxD,CAAC,CAAC,CAAC;AAYwC,oCAAY;AAVvD;;GAEG;AACH,MAAM,WAAW,GAAG,YAAC,CAAC,KAAK,CACzB,CACE,QAAW,EACX,UAAsB,EACO,EAAE,CAAC,YAAC,CAAC,GAAG,CAAC,cAAc,QAAQ,EAAE,EAAE,UAAU,CAAC,CAC9E,CAAC;AAEuD,kCAAW"}
@@ -0,0 +1,17 @@
1
+ import { AbilityBuilder, Ability, Subject } from '@casl/ability';
2
+ export interface PermissionRule {
3
+ action: string;
4
+ subject?: Subject | null;
5
+ properties?: {
6
+ fields?: string[];
7
+ };
8
+ condition?: Record<string, unknown>;
9
+ }
10
+ export interface CustomAbilityBuilder {
11
+ can(permission: PermissionRule): ReturnType<AbilityBuilder<Ability>['can']>;
12
+ build(): Ability;
13
+ }
14
+ /**
15
+ * Casl Ability Builder.
16
+ */
17
+ export declare const caslAbilityBuilder: () => CustomAbilityBuilder;
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.caslAbilityBuilder = void 0;
27
+ const sift = __importStar(require("sift"));
28
+ const ability_1 = require("@casl/ability");
29
+ const fp_1 = require("lodash/fp");
30
+ const allowedOperations = [
31
+ '$or',
32
+ '$and',
33
+ '$eq',
34
+ '$ne',
35
+ '$in',
36
+ '$nin',
37
+ '$lt',
38
+ '$lte',
39
+ '$gt',
40
+ '$gte',
41
+ '$exists',
42
+ '$elemMatch',
43
+ ];
44
+ const operations = (0, fp_1.pick)(allowedOperations, sift);
45
+ const conditionsMatcher = (conditions) => {
46
+ return sift.createQueryTester(conditions, { operations });
47
+ };
48
+ /**
49
+ * Casl Ability Builder.
50
+ */
51
+ const caslAbilityBuilder = () => {
52
+ const { can, build, ...rest } = new ability_1.AbilityBuilder(ability_1.Ability);
53
+ return {
54
+ can(permission) {
55
+ const { action, subject, properties = {}, condition } = permission;
56
+ const { fields } = properties;
57
+ return can(action, (0, fp_1.isNil)(subject) ? 'all' : subject, fields, (0, fp_1.isObject)(condition) ? condition : undefined);
58
+ },
59
+ build() {
60
+ return build({ conditionsMatcher });
61
+ },
62
+ ...rest,
63
+ };
64
+ };
65
+ exports.caslAbilityBuilder = caslAbilityBuilder;
66
+ //# sourceMappingURL=casl-ability.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"casl-ability.js","sourceRoot":"","sources":["../../../src/engine/abilities/casl-ability.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,2CAA6B;AAC7B,2CAAiE;AACjE,kCAAkD;AAgBlD,MAAM,iBAAiB,GAAG;IACxB,KAAK;IACL,MAAM;IACN,KAAK;IACL,KAAK;IACL,KAAK;IACL,MAAM;IACN,KAAK;IACL,MAAM;IACN,KAAK;IACL,MAAM;IACN,SAAS;IACT,YAAY;CACJ,CAAC;AAEX,MAAM,UAAU,GAAG,IAAA,SAAI,EAAC,iBAAiB,EAAE,IAAI,CAAC,CAAC;AAEjD,MAAM,iBAAiB,GAAG,CAAC,UAAmB,EAAE,EAAE;IAChD,OAAO,IAAI,CAAC,iBAAiB,CAAC,UAAU,EAAE,EAAE,UAAU,EAAE,CAAC,CAAC;AAC5D,CAAC,CAAC;AAEF;;GAEG;AACI,MAAM,kBAAkB,GAAG,GAAyB,EAAE;IAC3D,MAAM,EAAE,GAAG,EAAE,KAAK,EAAE,GAAG,IAAI,EAAE,GAAG,IAAI,wBAAc,CAAC,iBAAO,CAAC,CAAC;IAE5D,OAAO;QACL,GAAG,CAAC,UAA0B;YAC5B,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,UAAU,GAAG,EAAE,EAAE,SAAS,EAAE,GAAG,UAAU,CAAC;YACnE,MAAM,EAAE,MAAM,EAAE,GAAG,UAAU,CAAC;YAE9B,OAAO,GAAG,CACR,MAAM,EACN,IAAA,UAAK,EAAC,OAAO,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,OAAO,EAChC,MAAM,EACN,IAAA,aAAQ,EAAC,SAAS,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAC5C,CAAC;QACJ,CAAC;QAED,KAAK;YACH,OAAO,KAAK,CAAC,EAAE,iBAAiB,EAAE,CAAC,CAAC;QACtC,CAAC;QAED,GAAG,IAAI;KACR,CAAC;AACJ,CAAC,CAAC;AAtBW,QAAA,kBAAkB,sBAsB7B"}
@@ -0,0 +1 @@
1
+ export * from './casl-ability';
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./casl-ability"), exports);
18
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/engine/abilities/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,iDAA+B"}
@@ -0,0 +1,54 @@
1
+ import { hooks } from '@strapi/utils';
2
+ import * as domain from '../domain';
3
+ import type { Permission } from '../domain/permission';
4
+ import type { PermissionRule } from './abilities';
5
+ export interface PermissionEngineHooks {
6
+ 'before-format::validate.permission': ReturnType<typeof hooks.createAsyncBailHook>;
7
+ 'format.permission': ReturnType<typeof hooks.createAsyncSeriesWaterfallHook>;
8
+ 'after-format::validate.permission': ReturnType<typeof hooks.createAsyncBailHook>;
9
+ 'before-evaluate.permission': ReturnType<typeof hooks.createAsyncSeriesHook>;
10
+ 'before-register.permission': ReturnType<typeof hooks.createAsyncSeriesHook>;
11
+ }
12
+ export type HookName = keyof PermissionEngineHooks;
13
+ /**
14
+ * Create a hook map used by the permission Engine
15
+ */
16
+ declare const createEngineHooks: () => PermissionEngineHooks;
17
+ /**
18
+ * Create a context from a domain {@link Permission} used by the validate hooks
19
+ */
20
+ declare const createValidateContext: (permission: Permission) => {
21
+ readonly permission: Readonly<domain.permission.Permission>;
22
+ };
23
+ /**
24
+ * Create a context from a domain {@link Permission} used by the before valuate hook
25
+ */
26
+ declare const createBeforeEvaluateContext: (permission: Permission) => {
27
+ readonly permission: Readonly<domain.permission.Permission>;
28
+ addCondition(condition: string): {
29
+ readonly permission: Readonly<domain.permission.Permission>;
30
+ addCondition(condition: string): any;
31
+ };
32
+ };
33
+ interface WillRegisterContextParams {
34
+ permission: PermissionRule;
35
+ options: Record<string, unknown>;
36
+ }
37
+ /**
38
+ * Create a context from a casl Permission & some options
39
+ * @param caslPermission
40
+ */
41
+ declare const createWillRegisterContext: ({ permission, options }: WillRegisterContextParams) => {
42
+ permission: PermissionRule;
43
+ condition: {
44
+ and(rawConditionObject: unknown): {
45
+ and(rawConditionObject: unknown): any;
46
+ or(rawConditionObject: unknown): any;
47
+ };
48
+ or(rawConditionObject: unknown): {
49
+ and(rawConditionObject: unknown): any;
50
+ or(rawConditionObject: unknown): any;
51
+ };
52
+ };
53
+ };
54
+ export { createEngineHooks, createValidateContext, createBeforeEvaluateContext, createWillRegisterContext, };
@@ -0,0 +1,100 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.createWillRegisterContext = exports.createBeforeEvaluateContext = exports.createValidateContext = exports.createEngineHooks = void 0;
27
+ const fp_1 = require("lodash/fp");
28
+ const utils_1 = require("@strapi/utils");
29
+ const domain = __importStar(require("../domain"));
30
+ /**
31
+ * Create a hook map used by the permission Engine
32
+ */
33
+ const createEngineHooks = () => ({
34
+ 'before-format::validate.permission': utils_1.hooks.createAsyncBailHook(),
35
+ 'format.permission': utils_1.hooks.createAsyncSeriesWaterfallHook(),
36
+ 'after-format::validate.permission': utils_1.hooks.createAsyncBailHook(),
37
+ 'before-evaluate.permission': utils_1.hooks.createAsyncSeriesHook(),
38
+ 'before-register.permission': utils_1.hooks.createAsyncSeriesHook(),
39
+ });
40
+ exports.createEngineHooks = createEngineHooks;
41
+ /**
42
+ * Create a context from a domain {@link Permission} used by the validate hooks
43
+ */
44
+ const createValidateContext = (permission) => ({
45
+ get permission() {
46
+ return (0, fp_1.cloneDeep)(permission);
47
+ },
48
+ });
49
+ exports.createValidateContext = createValidateContext;
50
+ /**
51
+ * Create a context from a domain {@link Permission} used by the before valuate hook
52
+ */
53
+ const createBeforeEvaluateContext = (permission) => ({
54
+ get permission() {
55
+ return (0, fp_1.cloneDeep)(permission);
56
+ },
57
+ addCondition(condition) {
58
+ Object.assign(permission, domain.permission.addCondition(condition, permission));
59
+ return this;
60
+ },
61
+ });
62
+ exports.createBeforeEvaluateContext = createBeforeEvaluateContext;
63
+ /**
64
+ * Create a context from a casl Permission & some options
65
+ * @param caslPermission
66
+ */
67
+ const createWillRegisterContext = ({ permission, options }) => ({
68
+ ...options,
69
+ get permission() {
70
+ return (0, fp_1.cloneDeep)(permission);
71
+ },
72
+ condition: {
73
+ and(rawConditionObject) {
74
+ if (!permission.condition) {
75
+ permission.condition = { $and: [] };
76
+ }
77
+ if ((0, fp_1.isArray)(permission.condition.$and)) {
78
+ permission.condition.$and.push(rawConditionObject);
79
+ }
80
+ return this;
81
+ },
82
+ or(rawConditionObject) {
83
+ if (!permission.condition) {
84
+ permission.condition = { $and: [] };
85
+ }
86
+ if ((0, fp_1.isArray)(permission.condition.$and)) {
87
+ const orClause = permission.condition.$and.find((0, fp_1.has)('$or'));
88
+ if (orClause) {
89
+ orClause.$or.push(rawConditionObject);
90
+ }
91
+ else {
92
+ permission.condition.$and.push({ $or: [rawConditionObject] });
93
+ }
94
+ }
95
+ return this;
96
+ },
97
+ },
98
+ });
99
+ exports.createWillRegisterContext = createWillRegisterContext;
100
+ //# sourceMappingURL=hooks.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hooks.js","sourceRoot":"","sources":["../../src/engine/hooks.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,kCAAoD;AACpD,yCAAsC;AAEtC,kDAAoC;AAcpC;;GAEG;AACH,MAAM,iBAAiB,GAAG,GAA0B,EAAE,CAAC,CAAC;IACtD,oCAAoC,EAAE,aAAK,CAAC,mBAAmB,EAAE;IACjE,mBAAmB,EAAE,aAAK,CAAC,8BAA8B,EAAE;IAC3D,mCAAmC,EAAE,aAAK,CAAC,mBAAmB,EAAE;IAChE,4BAA4B,EAAE,aAAK,CAAC,qBAAqB,EAAE;IAC3D,4BAA4B,EAAE,aAAK,CAAC,qBAAqB,EAAE;CAC5D,CAAC,CAAC;AA4ED,8CAAiB;AA1EnB;;GAEG;AACH,MAAM,qBAAqB,GAAG,CAAC,UAAsB,EAAE,EAAE,CAAC,CAAC;IACzD,IAAI,UAAU;QACZ,OAAO,IAAA,cAAS,EAAC,UAAU,CAAC,CAAC;IAC/B,CAAC;CACF,CAAC,CAAC;AAoED,sDAAqB;AAlEvB;;GAEG;AACH,MAAM,2BAA2B,GAAG,CAAC,UAAsB,EAAE,EAAE,CAAC,CAAC;IAC/D,IAAI,UAAU;QACZ,OAAO,IAAA,cAAS,EAAC,UAAU,CAAC,CAAC;IAC/B,CAAC;IAED,YAAY,CAAC,SAAiB;QAC5B,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE,MAAM,CAAC,UAAU,CAAC,YAAY,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC,CAAC;QAEjF,OAAO,IAAI,CAAC;IACd,CAAC;CACF,CAAC,CAAC;AAsDD,kEAA2B;AA/C7B;;;GAGG;AACH,MAAM,yBAAyB,GAAG,CAAC,EAAE,UAAU,EAAE,OAAO,EAA6B,EAAE,EAAE,CAAC,CAAC;IACzF,GAAG,OAAO;IAEV,IAAI,UAAU;QACZ,OAAO,IAAA,cAAS,EAAC,UAAU,CAAC,CAAC;IAC/B,CAAC;IAED,SAAS,EAAE;QACT,GAAG,CAAC,kBAA2B;YAC7B,IAAI,CAAC,UAAU,CAAC,SAAS,EAAE;gBACzB,UAAU,CAAC,SAAS,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC;aACrC;YAED,IAAI,IAAA,YAAO,EAAC,UAAU,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE;gBACtC,UAAU,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC;aACpD;YAED,OAAO,IAAI,CAAC;QACd,CAAC;QAED,EAAE,CAAC,kBAA2B;YAC5B,IAAI,CAAC,UAAU,CAAC,SAAS,EAAE;gBACzB,UAAU,CAAC,SAAS,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC;aACrC;YAED,IAAI,IAAA,YAAO,EAAC,UAAU,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE;gBACtC,MAAM,QAAQ,GAAG,UAAU,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,IAAA,QAAG,EAAC,KAAK,CAAC,CAAC,CAAC;gBAE5D,IAAI,QAAQ,EAAE;oBACZ,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC;iBACvC;qBAAM;oBACL,UAAU,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC,kBAAkB,CAAC,EAAE,CAAC,CAAC;iBAC/D;aACF;YAED,OAAO,IAAI,CAAC;QACd,CAAC;KACF;CACF,CAAC,CAAC;AAMD,8DAAyB"}
@@ -0,0 +1,24 @@
1
+ import { Ability } from '@casl/ability';
2
+ import { providerFactory } from '@strapi/utils';
3
+ import type { PermissionEngineHooks, HookName } from './hooks';
4
+ import * as abilities from './abilities';
5
+ import { Permission } from '../domain/permission';
6
+ export { abilities };
7
+ type Provider = ReturnType<typeof providerFactory>;
8
+ type ActionProvider = Provider;
9
+ type ConditionProvider = Provider;
10
+ export interface Engine {
11
+ hooks: PermissionEngineHooks;
12
+ on(hook: HookName, handler: (...args: unknown[]) => unknown): Engine;
13
+ generateAbility(permissions: Permission[], options?: object): Promise<Ability>;
14
+ createRegisterFunction(can: (permission: abilities.PermissionRule) => unknown, options: Record<string, unknown>): (permission: abilities.PermissionRule) => Promise<unknown>;
15
+ }
16
+ export interface EngineParams {
17
+ providers: {
18
+ action: ActionProvider;
19
+ condition: ConditionProvider;
20
+ };
21
+ abilityBuilderFactory?(): abilities.CustomAbilityBuilder;
22
+ }
23
+ declare const newEngine: (params: EngineParams) => Engine;
24
+ export { newEngine as new };
@@ -0,0 +1,140 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.new = exports.abilities = void 0;
30
+ const fp_1 = __importDefault(require("lodash/fp"));
31
+ const hooks_1 = require("./hooks");
32
+ const abilities = __importStar(require("./abilities"));
33
+ exports.abilities = abilities;
34
+ /**
35
+ * Create a default state object for the engine
36
+ */
37
+ const createEngineState = () => {
38
+ const hooks = (0, hooks_1.createEngineHooks)();
39
+ return { hooks };
40
+ };
41
+ const newEngine = (params) => {
42
+ const { providers, abilityBuilderFactory = abilities.caslAbilityBuilder } = params;
43
+ const state = createEngineState();
44
+ const runValidationHook = async (hook, context) => state.hooks[hook].call(context);
45
+ /**
46
+ * Evaluate a permission using local and registered behaviors (using hooks).
47
+ * Validate, format (add condition, etc...), evaluate (evaluate conditions) and register a permission
48
+ */
49
+ const evaluate = async (params) => {
50
+ const { options, register } = params;
51
+ const preFormatValidation = await runValidationHook('before-format::validate.permission', (0, hooks_1.createBeforeEvaluateContext)(params.permission));
52
+ if (preFormatValidation === false) {
53
+ return;
54
+ }
55
+ const permission = (await state.hooks['format.permission'].call(params.permission));
56
+ const afterFormatValidation = await runValidationHook('after-format::validate.permission', (0, hooks_1.createValidateContext)(permission));
57
+ if (afterFormatValidation === false) {
58
+ return;
59
+ }
60
+ await state.hooks['before-evaluate.permission'].call((0, hooks_1.createBeforeEvaluateContext)(permission));
61
+ const { action, subject, properties, conditions = [] } = permission;
62
+ if (conditions.length === 0) {
63
+ return register({ action, subject, properties });
64
+ }
65
+ const resolveConditions = fp_1.default.map(providers.condition.get);
66
+ const removeInvalidConditions = fp_1.default.filter((condition) => fp_1.default.isFunction(condition.handler));
67
+ const evaluateConditions = (conditions) => {
68
+ return Promise.all(conditions.map(async (condition) => ({
69
+ condition,
70
+ result: await condition.handler(fp_1.default.merge(options, { permission: fp_1.default.cloneDeep(permission) })),
71
+ })));
72
+ };
73
+ const removeInvalidResults = fp_1.default.filter(({ result }) => fp_1.default.isBoolean(result) || fp_1.default.isObject(result));
74
+ const evaluatedConditions = await Promise.resolve(conditions)
75
+ .then(resolveConditions)
76
+ .then(removeInvalidConditions)
77
+ .then(evaluateConditions)
78
+ .then(removeInvalidResults);
79
+ const resultPropEq = fp_1.default.propEq('result');
80
+ const pickResults = fp_1.default.map(fp_1.default.prop('result'));
81
+ if (evaluatedConditions.every(resultPropEq(false))) {
82
+ return;
83
+ }
84
+ if (fp_1.default.isEmpty(evaluatedConditions) || evaluatedConditions.some(resultPropEq(true))) {
85
+ return register({ action, subject, properties });
86
+ }
87
+ const results = pickResults(evaluatedConditions).filter(fp_1.default.isObject);
88
+ if (fp_1.default.isEmpty(results)) {
89
+ return register({ action, subject, properties });
90
+ }
91
+ return register({
92
+ action,
93
+ subject,
94
+ properties,
95
+ condition: { $and: [{ $or: results }] },
96
+ });
97
+ };
98
+ return {
99
+ get hooks() {
100
+ return state.hooks;
101
+ },
102
+ /**
103
+ * Create a register function that wraps a `can` function
104
+ * used to register a permission in the ability builder
105
+ */
106
+ createRegisterFunction(can, options) {
107
+ return async (permission) => {
108
+ const hookContext = (0, hooks_1.createWillRegisterContext)({ options, permission });
109
+ await state.hooks['before-register.permission'].call(hookContext);
110
+ return can(permission);
111
+ };
112
+ },
113
+ /**
114
+ * Register a new handler for a given hook
115
+ */
116
+ on(hook, handler) {
117
+ const validHooks = Object.keys(state.hooks);
118
+ const isValidHook = validHooks.includes(hook);
119
+ if (!isValidHook) {
120
+ throw new Error(`Invalid hook supplied when trying to register an handler to the permission engine. Got "${hook}" but expected one of ${validHooks.join(', ')}`);
121
+ }
122
+ state.hooks[hook].register(handler);
123
+ return this;
124
+ },
125
+ /**
126
+ * Generate an ability based on the instance's
127
+ * ability builder and the given permissions
128
+ */
129
+ async generateAbility(permissions, options = {}) {
130
+ const { can, build } = abilityBuilderFactory();
131
+ for (const permission of permissions) {
132
+ const register = this.createRegisterFunction(can, options);
133
+ await evaluate({ permission, options, register });
134
+ }
135
+ return build();
136
+ },
137
+ };
138
+ };
139
+ exports.new = newEngine;
140
+ //# sourceMappingURL=index.js.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B,EAAC,EAAE,OAAO,EAAE,UAAU,EAAE,CAAC,CAAC;gBAEvE,MAAM,KAAK,CAAC,KAAK,CAAC,4BAA4B,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;gBAElE,OAAO,GAAG,CAAC,UAAU,CAAC,CAAC;YACzB,CAAC,CAAC;QACJ,CAAC;QAED;;WAEG;QACH,EAAE,CAAC,IAAI,EAAE,OAAO;YACd,MAAM,UAAU,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;YAC5C,MAAM,WAAW,GAAG,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;YAE9C,IAAI,CAAC,WAAW,EAAE;gBAChB,MAAM,IAAI,KAAK,CACb,2FAA2F,IAAI,yBAAyB,UAAU,CAAC,IAAI,CACrI,IAAI,CACL,EAAE,CACJ,CAAC;aACH;YAED,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;YAEpC,OAAO,IAAI,CAAC;QACd,CAAC;QAED;;;WAGG;QACH,KAAK,CAAC,eAAe,CAAC,WAAW,EAAE,UAAmC,EAAE;YACtE,MAAM,EAAE,GAAG,EAAE,KAAK,EAAE,GAAG,qBAAqB,EAAE,CAAC;YAE/C,KAAK,MAAM,UAAU,IAAI,WAAW,EAAE;gBACpC,MAAM,QAAQ,GAAG,IAAI,CAAC,sBAAsB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;gBAE3D,MAAM,QAAQ,CAAC,EAAE,UAAU,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,CAAC;aACnD;YAED,OAAO,KAAK,EAAE,CAAC;QACjB,CAAC;KACF,CAAC;AACJ,CAAC,CAAC;AAEoB,wBAAG"}
@@ -0,0 +1,7 @@
1
+ import * as domain from './domain';
2
+ import * as engine from './engine';
3
+ declare const _default: {
4
+ domain: typeof domain;
5
+ engine: typeof engine;
6
+ };
7
+ export = _default;
package/dist/index.js ADDED
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ const domain = __importStar(require("./domain"));
26
+ const engine = __importStar(require("./engine"));
27
+ module.exports = {
28
+ domain,
29
+ engine,
30
+ };
31
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAAA,iDAAmC;AACnC,iDAAmC;AAEnC,iBAAS;IACP,MAAM;IACN,MAAM;CACP,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@strapi/permissions",
3
- "version": "4.12.0-beta.5",
3
+ "version": "4.12.1",
4
4
  "description": "Strapi's permission layer.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -19,21 +19,34 @@
19
19
  "url": "https://strapi.io"
20
20
  }
21
21
  ],
22
- "main": "./lib/index.js",
22
+ "files": [
23
+ "./dist"
24
+ ],
25
+ "main": "./dist/index.js",
26
+ "types": "./dist/index.d.ts",
23
27
  "scripts": {
28
+ "build": "run -T tsc",
29
+ "build:ts": "run build",
30
+ "watch": "run -T tsc -w --preserveWatchOutput",
31
+ "clean": "run -T rimraf ./dist",
32
+ "prepublishOnly": "yarn clean && yarn build",
24
33
  "test:unit": "run -T jest",
25
34
  "test:unit:watch": "run -T jest --watch",
26
35
  "lint": "run -T eslint ."
27
36
  },
28
37
  "dependencies": {
29
38
  "@casl/ability": "5.4.4",
30
- "@strapi/utils": "4.12.0-beta.5",
39
+ "@strapi/utils": "4.12.1",
31
40
  "lodash": "4.17.21",
32
41
  "sift": "16.0.1"
33
42
  },
43
+ "devDependencies": {
44
+ "eslint-config-custom": "4.12.1",
45
+ "tsconfig": "4.12.1"
46
+ },
34
47
  "engines": {
35
- "node": ">=14.19.1 <=18.x.x",
48
+ "node": ">=16.0.0 <=20.x.x",
36
49
  "npm": ">=6.0.0"
37
50
  },
38
- "gitHead": "690c85458416da815f0e944fa8fc6dbe0fb2d001"
51
+ "gitHead": "be8985fa20cb357981bca97bc65ee5c1b843f801"
39
52
  }
package/.eslintignore DELETED
@@ -1,2 +0,0 @@
1
- node_modules/
2
- .eslintrc.js
package/.eslintrc.js DELETED
@@ -1,4 +0,0 @@
1
- module.exports = {
2
- root: true,
3
- extends: ['custom/back'],
4
- };
package/index.d.ts DELETED
@@ -1,54 +0,0 @@
1
- import { hooks, providerFactory } from '@strapi/utils';
2
-
3
- interface Permission {
4
- action: string;
5
- subject?: string | object | null;
6
- properties?: object;
7
- conditions?: string[];
8
- }
9
-
10
- type Provider = ReturnType<typeof providerFactory>;
11
-
12
- interface BaseAction {
13
- actionId: string;
14
- }
15
-
16
- interface BaseCondition {
17
- name: string;
18
- handler(...params: unknown[]): boolean | object;
19
- }
20
-
21
- interface ActionProvider<T extends Action = Action> extends Provider {}
22
- interface ConditionProvider<T extends Condition = Condition> extends Provider {}
23
-
24
- interface PermissionEngineHooks {
25
- 'before-format::validate.permission': ReturnType<typeof hooks.createAsyncBailHook>;
26
- 'format.permission': ReturnType<typeof hooks.createAsyncSeriesWaterfallHook>;
27
- 'after-format::validate.permission': ReturnType<typeof hooks.createAsyncBailHook>;
28
- 'before-evaluate.permission': ReturnType<typeof hooks.createAsyncSeriesHook>;
29
- 'before-register.permission': ReturnType<typeof hooks.createAsyncSeriesHook>;
30
- }
31
-
32
- type PermissionEngineHookName = keyof PermissionEngineHooks;
33
-
34
- interface PermissionEngine {
35
- hooks: object;
36
-
37
- on(hook: PermissionEngineHookName, handler: Function): PermissionEngine;
38
- generateAbility(permissions: Permission[], options?: object): Ability;
39
- createRegisterFunction(can: Function, options: object): Function;
40
- }
41
-
42
- interface BaseAbility {
43
- can: Function;
44
- }
45
-
46
- interface AbilityBuilder {
47
- can(permission: Permission): void | Promise<void>;
48
- build(): BaseAbility | Promise<BaseAbility>;
49
- }
50
-
51
- interface PermissionEngineParams {
52
- providers: { action: ActionProvider; condition: ConditionProvider };
53
- abilityBuilderFactory(): AbilityBuilder;
54
- }
@@ -1,7 +0,0 @@
1
- 'use strict';
2
-
3
- const permission = require('./permission');
4
-
5
- module.exports = {
6
- permission,
7
- };
@@ -1,68 +0,0 @@
1
- 'use strict';
2
-
3
- const _ = require('lodash/fp');
4
-
5
- const PERMISSION_FIELDS = ['action', 'subject', 'properties', 'conditions'];
6
-
7
- const sanitizePermissionFields = _.pick(PERMISSION_FIELDS);
8
-
9
- /**
10
- * @typedef {import("../../..").Permission} Permission
11
- */
12
-
13
- /**
14
- * Creates a permission with default values for optional properties
15
- *
16
- * @return {Pick<Permission, 'conditions' | 'properties' | 'subject'>}
17
- */
18
- const getDefaultPermission = () => ({
19
- conditions: [],
20
- properties: {},
21
- subject: null,
22
- });
23
-
24
- /**
25
- * Create a new permission based on given attributes
26
- *
27
- * @param {object} attributes
28
- *
29
- * @return {Permission}
30
- */
31
- const create = _.pipe(_.pick(PERMISSION_FIELDS), _.merge(getDefaultPermission()));
32
-
33
- /**
34
- * Add a condition to a permission
35
- *
36
- * @param {string} condition The condition to add
37
- * @param {Permission} permission The permission on which we want to add the condition
38
- *
39
- * @return {Permission}
40
- */
41
- const addCondition = _.curry((condition, permission) => {
42
- const { conditions } = permission;
43
-
44
- const newConditions = Array.isArray(conditions)
45
- ? _.uniq(conditions.concat(condition))
46
- : [condition];
47
-
48
- return _.set('conditions', newConditions, permission);
49
- });
50
-
51
- /**
52
- * Gets a property or a part of a property from a permission.
53
- *
54
- * @function
55
- *
56
- * @param {string} property - The property to get
57
- * @param {Permission} permission - The permission on which we want to access the property
58
- *
59
- * @return {Permission}
60
- */
61
- const getProperty = _.curry((property, permission) => _.get(`properties.${property}`, permission));
62
-
63
- module.exports = {
64
- create,
65
- sanitizePermissionFields,
66
- addCondition,
67
- getProperty,
68
- };
@@ -1,57 +0,0 @@
1
- 'use strict';
2
-
3
- const sift = require('sift');
4
- const { AbilityBuilder, Ability } = require('@casl/ability');
5
- const { pick, isNil, isObject } = require('lodash/fp');
6
-
7
- const allowedOperations = [
8
- '$or',
9
- '$and',
10
- '$eq',
11
- '$ne',
12
- '$in',
13
- '$nin',
14
- '$lt',
15
- '$lte',
16
- '$gt',
17
- '$gte',
18
- '$exists',
19
- '$elemMatch',
20
- ];
21
-
22
- const operations = pick(allowedOperations, sift);
23
-
24
- const conditionsMatcher = (conditions) => {
25
- return sift.createQueryTester(conditions, { operations });
26
- };
27
-
28
- /**
29
- * Casl Ability Builder.
30
- */
31
- const caslAbilityBuilder = () => {
32
- const { can, build, ...rest } = new AbilityBuilder(Ability);
33
-
34
- return {
35
- can(permission) {
36
- const { action, subject, properties = {}, condition } = permission;
37
- const { fields } = properties;
38
-
39
- return can(
40
- action,
41
- isNil(subject) ? 'all' : subject,
42
- fields,
43
- isObject(condition) ? condition : undefined
44
- );
45
- },
46
-
47
- build() {
48
- return build({ conditionsMatcher });
49
- },
50
-
51
- ...rest,
52
- };
53
- };
54
-
55
- module.exports = {
56
- caslAbilityBuilder,
57
- };
@@ -1,7 +0,0 @@
1
- 'use strict';
2
-
3
- const { caslAbilityBuilder } = require('./casl-ability');
4
-
5
- module.exports = {
6
- caslAbilityBuilder,
7
- };
@@ -1,97 +0,0 @@
1
- 'use strict';
2
-
3
- const { cloneDeep, has } = require('lodash/fp');
4
- const { hooks } = require('@strapi/utils');
5
-
6
- const domain = require('../domain');
7
-
8
- /**
9
- * Create a hook map used by the permission Engine
10
- *
11
- * @return {import('../..').PermissionEngineHooks}
12
- */
13
- const createEngineHooks = () => ({
14
- 'before-format::validate.permission': hooks.createAsyncBailHook(),
15
- 'format.permission': hooks.createAsyncSeriesWaterfallHook(),
16
- 'after-format::validate.permission': hooks.createAsyncBailHook(),
17
- 'before-evaluate.permission': hooks.createAsyncSeriesHook(),
18
- 'before-register.permission': hooks.createAsyncSeriesHook(),
19
- });
20
-
21
- /**
22
- * Create a context from a domain {@link Permission} used by the validate hooks
23
- * @param {Permission} permission
24
- * @return {{ readonly permission: Permission }}
25
- */
26
- const createValidateContext = (permission) => ({
27
- get permission() {
28
- return cloneDeep(permission);
29
- },
30
- });
31
-
32
- /**
33
- * Create a context from a domain {@link Permission} used by the before valuate hook
34
- * @param {Permission} permission
35
- * @return {{readonly permission: Permission, addCondition(string): this}}
36
- */
37
- const createBeforeEvaluateContext = (permission) => ({
38
- get permission() {
39
- return cloneDeep(permission);
40
- },
41
-
42
- addCondition(condition) {
43
- Object.assign(permission, domain.permission.addCondition(condition, permission));
44
-
45
- return this;
46
- },
47
- });
48
-
49
- /**
50
- * Create a context from a casl Permission & some options
51
- * @param caslPermission
52
- * @param {object} options
53
- * @param {Permission} options.permission
54
- * @param {object} options.user
55
- */
56
- const createWillRegisterContext = ({ permission, options }) => ({
57
- ...options,
58
-
59
- get permission() {
60
- return cloneDeep(permission);
61
- },
62
-
63
- condition: {
64
- and(rawConditionObject) {
65
- if (!permission.condition) {
66
- Object.assign(permission, { condition: { $and: [] } });
67
- }
68
-
69
- permission.condition.$and.push(rawConditionObject);
70
-
71
- return this;
72
- },
73
-
74
- or(rawConditionObject) {
75
- if (!permission.condition) {
76
- Object.assign(permission, { condition: { $and: [] } });
77
- }
78
-
79
- const orClause = permission.condition.$and.find(has('$or'));
80
-
81
- if (orClause) {
82
- orClause.$or.push(rawConditionObject);
83
- } else {
84
- permission.condition.$and.push({ $or: [rawConditionObject] });
85
- }
86
-
87
- return this;
88
- },
89
- },
90
- });
91
-
92
- module.exports = {
93
- createEngineHooks,
94
- createValidateContext,
95
- createBeforeEvaluateContext,
96
- createWillRegisterContext,
97
- };
@@ -1,209 +0,0 @@
1
- 'use strict';
2
-
3
- const _ = require('lodash/fp');
4
-
5
- const abilities = require('./abilities');
6
-
7
- const {
8
- createEngineHooks,
9
- createWillRegisterContext,
10
- createBeforeEvaluateContext,
11
- createValidateContext,
12
- } = require('./hooks');
13
-
14
- /**
15
- * @typedef {import("../..").PermissionEngine} PermissionEngine
16
- * @typedef {import("../..").ActionProvider} ActionProvider
17
- * @typedef {import("../..").ConditionProvider} ConditionProvider
18
- * @typedef {import("../..").PermissionEngineParams} PermissionEngineParams
19
- * @typedef {import("../..").Permission} Permission
20
- */
21
-
22
- /**
23
- * Create a default state object for the engine
24
- */
25
- const createEngineState = () => {
26
- const hooks = createEngineHooks();
27
-
28
- return { hooks };
29
- };
30
-
31
- module.exports = {
32
- abilities,
33
-
34
- /**
35
- * Create a new instance of a permission engine
36
- *
37
- * @param {PermissionEngineParams} params
38
- *
39
- * @return {PermissionEngine}
40
- */
41
- new(params) {
42
- const { providers, abilityBuilderFactory = abilities.caslAbilityBuilder } = params;
43
-
44
- const state = createEngineState();
45
-
46
- const runValidationHook = async (hook, context) => state.hooks[hook].call(context);
47
-
48
- /**
49
- * Evaluate a permission using local and registered behaviors (using hooks).
50
- * Validate, format (add condition, etc...), evaluate (evaluate conditions) and register a permission
51
- *
52
- * @param {object} params
53
- * @param {object} params.options
54
- * @param {Function} params.register
55
- * @param {Permission} params.permission
56
- */
57
- const evaluate = async (params) => {
58
- const { options, register } = params;
59
-
60
- const preFormatValidation = await runValidationHook(
61
- 'before-format::validate.permission',
62
- createBeforeEvaluateContext(params.permission)
63
- );
64
-
65
- if (preFormatValidation === false) {
66
- return;
67
- }
68
-
69
- const permission = await state.hooks['format.permission'].call(params.permission);
70
-
71
- const afterFormatValidation = await runValidationHook(
72
- 'after-format::validate.permission',
73
- createValidateContext(permission)
74
- );
75
-
76
- if (afterFormatValidation === false) {
77
- return;
78
- }
79
-
80
- await state.hooks['before-evaluate.permission'].call(createBeforeEvaluateContext(permission));
81
-
82
- const { action, subject, properties, conditions = [] } = permission;
83
-
84
- if (conditions.length === 0) {
85
- return register({ action, subject, properties });
86
- }
87
-
88
- const resolveConditions = _.map(providers.condition.get);
89
-
90
- const removeInvalidConditions = _.filter((condition) => _.isFunction(condition.handler));
91
-
92
- const evaluateConditions = (conditions) => {
93
- return Promise.all(
94
- conditions.map(async (condition) => ({
95
- condition,
96
- result: await condition.handler(
97
- _.merge(options, { permission: _.cloneDeep(permission) })
98
- ),
99
- }))
100
- );
101
- };
102
-
103
- const removeInvalidResults = _.filter(
104
- ({ result }) => _.isBoolean(result) || _.isObject(result)
105
- );
106
-
107
- const evaluatedConditions = await Promise.resolve(conditions)
108
- .then(resolveConditions)
109
- .then(removeInvalidConditions)
110
- .then(evaluateConditions)
111
- .then(removeInvalidResults);
112
-
113
- const resultPropEq = _.propEq('result');
114
- const pickResults = _.map(_.prop('result'));
115
-
116
- if (evaluatedConditions.every(resultPropEq(false))) {
117
- return;
118
- }
119
-
120
- if (_.isEmpty(evaluatedConditions) || evaluatedConditions.some(resultPropEq(true))) {
121
- return register({ action, subject, properties });
122
- }
123
-
124
- const results = pickResults(evaluatedConditions).filter(_.isObject);
125
-
126
- if (_.isEmpty(results)) {
127
- return register({ action, subject, properties });
128
- }
129
-
130
- return register({
131
- action,
132
- subject,
133
- properties,
134
- condition: { $and: [{ $or: results }] },
135
- });
136
- };
137
-
138
- return {
139
- get hooks() {
140
- return state.hooks;
141
- },
142
-
143
- /**
144
- * Create a register function that wraps a `can` function
145
- * used to register a permission in the ability builder
146
- *
147
- * @param {Function} can
148
- * @param {object} options
149
- *
150
- * @return {Function}
151
- */
152
- createRegisterFunction(can, options) {
153
- return async (permission) => {
154
- const hookContext = createWillRegisterContext({ options, permission });
155
-
156
- await state.hooks['before-register.permission'].call(hookContext);
157
-
158
- return can(permission);
159
- };
160
- },
161
-
162
- /**
163
- * Register a new handler for a given hook
164
- *
165
- * @param {string} hook
166
- * @param {Function} handler
167
- *
168
- * @return {this}
169
- */
170
- on(hook, handler) {
171
- const validHooks = Object.keys(state.hooks);
172
- const isValidHook = validHooks.includes(hook);
173
-
174
- if (!isValidHook) {
175
- throw new Error(
176
- `Invalid hook supplied when trying to register an handler to the permission engine. Got "${hook}" but expected one of ${validHooks.join(
177
- ', '
178
- )}`
179
- );
180
- }
181
-
182
- state.hooks[hook].register(handler);
183
-
184
- return this;
185
- },
186
-
187
- /**
188
- * Generate an ability based on the instance's
189
- * ability builder and the given permissions
190
- *
191
- * @param {Permission[]} permissions
192
- * @param {object} [options]
193
- *
194
- * @return {object}
195
- */
196
- async generateAbility(permissions, options = {}) {
197
- const { can, build } = abilityBuilderFactory();
198
-
199
- for (const permission of permissions) {
200
- const register = this.createRegisterFunction(can, options);
201
-
202
- await evaluate({ permission, options, register });
203
- }
204
-
205
- return build();
206
- },
207
- };
208
- },
209
- };
package/lib/index.js DELETED
@@ -1,9 +0,0 @@
1
- 'use strict';
2
-
3
- const domain = require('./domain');
4
- const engine = require('./engine');
5
-
6
- module.exports = {
7
- domain,
8
- engine,
9
- };