5
5
import {
6
6
CanActivate ,
7
7
ExecutionContext ,
8
+ ForbiddenException ,
8
9
Injectable ,
9
10
mixin ,
10
11
Type ,
@@ -17,10 +18,17 @@ import { OryPermissionsService } from './ory-permissions';
17
18
export interface OryAuthorizationGuardOptions {
18
19
errorFactory ?: ( error : Error ) => Error ;
19
20
postCheck ?: ( relationTuple : RelationTuple , isPermitted : boolean ) => void ;
21
+ unauthorizedFactory : ( ctx : ExecutionContext , error : unknown ) => Error ;
20
22
}
21
23
24
+ const defaultOptions : OryAuthorizationGuardOptions = {
25
+ unauthorizedFactory : ( ctx , error ) => {
26
+ return new ForbiddenException ( error ) ;
27
+ } ,
28
+ } ;
29
+
22
30
export const OryAuthorizationGuard = (
23
- options : OryAuthorizationGuardOptions = { }
31
+ options : Partial < OryAuthorizationGuardOptions > = { }
24
32
) : Type < CanActivate > => {
25
33
@Injectable ( )
26
34
class AuthorizationGuard implements CanActivate {
@@ -35,22 +43,31 @@ export const OryAuthorizationGuard = (
35
43
if ( ! factories ?. length ) {
36
44
return true ;
37
45
}
46
+ const { unauthorizedFactory } = {
47
+ ...defaultOptions ,
48
+ ...options ,
49
+ } ;
38
50
for ( const { relationTupleFactory } of factories ) {
39
51
const relationTuple = relationTupleFactory ( context ) ;
40
52
const result = createPermissionCheckQuery ( relationTuple ) ;
41
53
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 ) ;
46
62
}
47
- const { data } = await this . oryService . checkPermission ( result . value ) ;
48
- const isPermitted = data . allowed ;
49
63
if ( options . postCheck ) {
50
64
options . postCheck ( relationTuple , isPermitted ) ;
51
65
}
52
66
if ( ! isPermitted ) {
53
- return false ;
67
+ throw unauthorizedFactory (
68
+ context ,
69
+ new Error ( `Unauthorized access for ${ relationTuple } ` )
70
+ ) ;
54
71
}
55
72
}
56
73
return true ;
0 commit comments