Skip to content

Commit

Permalink
feat(action-policy): add whyCan and whyCannot methods (#59)
Browse files Browse the repository at this point in the history
these methods returns all the statements that allow or not an action
  • Loading branch information
roggervalf committed Nov 8, 2021
1 parent 0bcb9ac commit fef8e89
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/ActionBasedPolicy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,21 @@ describe('ActionBasedPolicy Class', () => {
context: { user: { id: 123 } }
})
).toBe(true);
expect(
policy.whyCan({
action: 'getUser/123',
context: { user: { id: 123 } }
})
).toMatchObject([
{
effect: 'allow',
action: [
'createProject',
'getUser/${user.id}',
'updateUser/${user.id}'
]
}
]);
expect(
policy.can({
action: 'createProject'
Expand Down Expand Up @@ -371,6 +386,21 @@ describe('ActionBasedPolicy Class', () => {
context: { user: { id: 123 } }
})
).toBe(true);
expect(
policy.whyCannot({
action: 'getUser/123',
context: { user: { id: 123 } }
})
).toMatchObject([
{
effect: 'deny',
action: [
'createProject',
'getUser/${user.id}',
'updateUser/${user.id}'
]
}
]);
expect(
policy.cannot({
action: 'createProject'
Expand Down
34 changes: 34 additions & 0 deletions src/ActionBasedPolicy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,23 @@ export class ActionBasedPolicy<T extends object> extends Policy<
);
}

whyCan(
this: ActionBasedPolicy<T>,
{ action, context }: EvaluateActionBasedInterface<T>
): ActionBasedType[] {
return this.allowStatements.reduce((statements, currentStatement) => {
const matches = currentStatement.matches({
action,
context: context || this.context,
conditionResolver: this.conditionResolver
});
if (matches) {
return [...statements, currentStatement.getStatement()];
}
return statements;
}, [] as ActionBasedType[]);
}

cannot(
this: ActionBasedPolicy<T>,
{ action, context }: EvaluateActionBasedInterface<T>
Expand All @@ -87,6 +104,23 @@ export class ActionBasedPolicy<T extends object> extends Policy<
);
}

whyCannot(
this: ActionBasedPolicy<T>,
{ action, context }: EvaluateActionBasedInterface<T>
): ActionBasedType[] {
return this.denyStatements.reduce((statements, currentStatement) => {
const matches = currentStatement.matches({
action,
context: context || this.context,
conditionResolver: this.conditionResolver
});
if (matches) {
return [...statements, currentStatement.getStatement()];
}
return statements;
}, [] as ActionBasedType[]);
}

generateProxy<U extends object>(
this: ActionBasedPolicy<T>,
obj: U,
Expand Down

0 comments on commit fef8e89

Please sign in to comment.