Skip to content

Commit cfcd91e

Browse files
committed
feat(keto-client-wrapper): create unauthorizedFactory option and improve error handling
1 parent 91173df commit cfcd91e

File tree

1 file changed

+25
-8
lines changed

1 file changed

+25
-8
lines changed

packages/keto-client-wrapper/src/lib/ory-authorization.guard.ts

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
import {
66
CanActivate,
77
ExecutionContext,
8+
ForbiddenException,
89
Injectable,
910
mixin,
1011
Type,
@@ -17,10 +18,17 @@ import { OryPermissionsService } from './ory-permissions';
1718
export interface OryAuthorizationGuardOptions {
1819
errorFactory?: (error: Error) => Error;
1920
postCheck?: (relationTuple: RelationTuple, isPermitted: boolean) => void;
21+
unauthorizedFactory: (ctx: ExecutionContext, error: unknown) => Error;
2022
}
2123

24+
const defaultOptions: OryAuthorizationGuardOptions = {
25+
unauthorizedFactory: (ctx, error) => {
26+
return new ForbiddenException(error);
27+
},
28+
};
29+
2230
export const OryAuthorizationGuard = (
23-
options: OryAuthorizationGuardOptions = {}
31+
options: Partial<OryAuthorizationGuardOptions> = {}
2432
): Type<CanActivate> => {
2533
@Injectable()
2634
class AuthorizationGuard implements CanActivate {
@@ -35,22 +43,31 @@ export const OryAuthorizationGuard = (
3543
if (!factories?.length) {
3644
return true;
3745
}
46+
const { unauthorizedFactory } = {
47+
...defaultOptions,
48+
...options,
49+
};
3850
for (const { relationTupleFactory } of factories) {
3951
const relationTuple = relationTupleFactory(context);
4052
const result = createPermissionCheckQuery(relationTuple);
4153
if (result.hasError()) {
42-
if (options.errorFactory) {
43-
throw options.errorFactory(result.error);
44-
}
45-
return false;
54+
throw unauthorizedFactory(context, result.error);
55+
}
56+
let isPermitted = false;
57+
try {
58+
const { data } = await this.oryService.checkPermission(result.value);
59+
isPermitted = data.allowed;
60+
} catch (error) {
61+
throw unauthorizedFactory(context, error);
4662
}
47-
const { data } = await this.oryService.checkPermission(result.value);
48-
const isPermitted = data.allowed;
4963
if (options.postCheck) {
5064
options.postCheck(relationTuple, isPermitted);
5165
}
5266
if (!isPermitted) {
53-
return false;
67+
throw unauthorizedFactory(
68+
context,
69+
new Error(`Unauthorized access for ${relationTuple}`)
70+
);
5471
}
5572
}
5673
return true;

0 commit comments

Comments
 (0)