/
index.ts
228 lines (179 loc) 路 6.13 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import _ from 'lodash/fp';
import qs from 'qs';
import { Ability } from '@casl/ability';
import { providerFactory } from '@strapi/utils';
import {
createEngineHooks,
createWillRegisterContext,
createBeforeEvaluateContext,
createValidateContext,
} from './hooks';
import type { PermissionEngineHooks, HookName } from './hooks';
import * as abilities from './abilities';
import { Permission } from '../domain/permission';
import type { PermissionRule } from '../types';
export { abilities };
type Provider = Omit<ReturnType<typeof providerFactory>, 'register'> & {
register(...args: unknown[]): Promise<Provider> | Provider;
};
type ActionProvider = Provider;
type ConditionProvider = Provider;
export interface Engine {
hooks: PermissionEngineHooks;
on(hook: HookName, handler: (...args: any[]) => any): Engine;
generateAbility(permissions: Permission[], options?: object): Promise<Ability>;
createRegisterFunction(
can: (permission: PermissionRule) => unknown,
options: Record<string, unknown>
): (permission: PermissionRule) => Promise<unknown>;
}
export interface EngineParams {
providers: { action: ActionProvider; condition: ConditionProvider };
abilityBuilderFactory?(): abilities.CustomAbilityBuilder;
}
interface EvaluateParams {
options: Record<string, unknown>;
register: (permission: PermissionRule) => Promise<unknown>;
permission: Permission;
}
interface Condition {
name: string;
handler(...params: unknown[]): boolean | object;
}
/**
* Create a default state object for the engine
*/
const createEngineState = () => {
const hooks = createEngineHooks();
return { hooks };
};
const newEngine = (params: EngineParams): Engine => {
const { providers, abilityBuilderFactory = abilities.caslAbilityBuilder } = params;
const state = createEngineState();
const runValidationHook = async (hook: HookName, context: unknown) =>
state.hooks[hook].call(context);
/**
* Evaluate a permission using local and registered behaviors (using hooks).
* Validate, format (add condition, etc...), evaluate (evaluate conditions) and register a permission
*/
const evaluate = async (params: EvaluateParams) => {
const { options, register } = params;
const preFormatValidation = await runValidationHook(
'before-format::validate.permission',
createBeforeEvaluateContext(params.permission)
);
if (preFormatValidation === false) {
return;
}
const permission = (await state.hooks['format.permission'].call(
params.permission
)) as Permission;
const afterFormatValidation = await runValidationHook(
'after-format::validate.permission',
createValidateContext(permission)
);
if (afterFormatValidation === false) {
return;
}
await state.hooks['before-evaluate.permission'].call(createBeforeEvaluateContext(permission));
const {
action: actionName,
subject,
properties,
conditions = [],
actionParameters = {},
} = permission;
let action = actionName;
if (actionParameters && Object.keys(actionParameters).length > 0) {
action = `${actionName}?${qs.stringify(actionParameters)}`;
}
if (conditions.length === 0) {
return register({ action, subject, properties });
}
const resolveConditions = _.map(providers.condition.get);
const removeInvalidConditions = _.filter((condition: Condition) =>
_.isFunction(condition.handler)
);
const evaluateConditions = (conditions: Condition[]) => {
return Promise.all(
conditions.map(async (condition) => ({
condition,
result: await condition.handler(
_.merge(options, { permission: _.cloneDeep(permission) })
),
}))
);
};
const removeInvalidResults = _.filter(
({ result }) => _.isBoolean(result) || _.isObject(result)
);
const evaluatedConditions = await Promise.resolve(conditions)
.then(resolveConditions)
.then(removeInvalidConditions)
.then(evaluateConditions)
.then(removeInvalidResults);
const resultPropEq = _.propEq('result');
const pickResults = _.map(_.prop('result'));
if (evaluatedConditions.every(resultPropEq(false))) {
return;
}
if (_.isEmpty(evaluatedConditions) || evaluatedConditions.some(resultPropEq(true))) {
return register({ action, subject, properties });
}
const results = pickResults(evaluatedConditions).filter(_.isObject);
if (_.isEmpty(results)) {
return register({ action, subject, properties });
}
return register({
action,
subject,
properties,
condition: { $and: [{ $or: results }] },
});
};
return {
get hooks() {
return state.hooks;
},
/**
* Create a register function that wraps a `can` function
* used to register a permission in the ability builder
*/
createRegisterFunction(can, options: Record<string, unknown>) {
return async (permission: PermissionRule) => {
const hookContext = createWillRegisterContext({ options, permission });
await state.hooks['before-register.permission'].call(hookContext);
return can(permission);
};
},
/**
* Register a new handler for a given hook
*/
on(hook, handler) {
const validHooks = Object.keys(state.hooks);
const isValidHook = validHooks.includes(hook);
if (!isValidHook) {
throw new Error(
`Invalid hook supplied when trying to register an handler to the permission engine. Got "${hook}" but expected one of ${validHooks.join(
', '
)}`
);
}
state.hooks[hook].register(handler);
return this;
},
/**
* Generate an ability based on the instance's
* ability builder and the given permissions
*/
async generateAbility(permissions, options: Record<string, unknown> = {}) {
const { can, build } = abilityBuilderFactory();
for (const permission of permissions) {
const register = this.createRegisterFunction(can, options);
await evaluate({ permission, options, register });
}
return build();
},
};
};
export { newEngine as new };