2
2
CanActivate ,
3
3
ExecutionContext ,
4
4
Injectable ,
5
- Logger ,
6
5
mixin ,
7
6
Type ,
7
+ UnauthorizedException ,
8
8
} from '@nestjs/common' ;
9
9
import type { Session } from '@ory/client' ;
10
10
@@ -18,6 +18,7 @@ export interface OryAuthenticationGuardOptions {
18
18
ctx : ExecutionContext ,
19
19
session : Session
20
20
) => void | Promise < void > ;
21
+ unauthorizedFactory : ( ctx : ExecutionContext , error : unknown ) => Error ;
21
22
}
22
23
23
24
const defaultOptions : OryAuthenticationGuardOptions = {
@@ -30,15 +31,16 @@ const defaultOptions: OryAuthenticationGuardOptions = {
30
31
. getRequest ( )
31
32
?. headers ?. authorization ?. replace ( 'Bearer ' , '' ) ,
32
33
cookieResolver : ( ctx ) => ctx . switchToHttp ( ) . getRequest ( ) ?. headers ?. cookie ,
34
+ unauthorizedFactory ( ) {
35
+ return new UnauthorizedException ( ) ;
36
+ } ,
33
37
} ;
34
38
35
39
export const OryAuthenticationGuard = (
36
40
options : Partial < OryAuthenticationGuardOptions > = defaultOptions
37
41
) : Type < CanActivate > => {
38
42
@Injectable ( )
39
43
class AuthenticationGuard implements CanActivate {
40
- readonly logger = new Logger ( AuthenticationGuard . name ) ;
41
-
42
44
constructor ( readonly oryService : OryFrontendService ) { }
43
45
44
46
async canActivate ( context : ExecutionContext ) : Promise < boolean > {
@@ -47,29 +49,32 @@ export const OryAuthenticationGuard = (
47
49
sessionTokenResolver,
48
50
isValidSession,
49
51
postValidationHook,
52
+ unauthorizedFactory,
50
53
} = {
51
54
...defaultOptions ,
52
55
...options ,
53
56
} ;
54
57
58
+ let session : Session ;
55
59
try {
56
60
const cookie = cookieResolver ( context ) ;
57
61
const xSessionToken = sessionTokenResolver ( context ) ;
58
- const { data : session } = await this . oryService . toSession ( {
62
+ const { data } = await this . oryService . toSession ( {
59
63
cookie,
60
64
xSessionToken,
61
65
} ) ;
62
- if ( ! isValidSession ( session ) ) {
63
- return false ;
64
- }
65
- if ( typeof postValidationHook === 'function' ) {
66
- await postValidationHook ( context , session ) ;
67
- }
68
- return true ;
66
+ session = data ;
69
67
} catch ( error ) {
70
- this . logger . error ( error ) ;
71
- return false ;
68
+ throw unauthorizedFactory ( context , error ) ;
69
+ }
70
+
71
+ if ( ! isValidSession ( session ) ) {
72
+ throw unauthorizedFactory ( context , new Error ( 'Invalid session' ) ) ;
73
+ }
74
+ if ( typeof postValidationHook === 'function' ) {
75
+ await postValidationHook ( context , session ) ;
72
76
}
77
+ return true ;
73
78
}
74
79
}
75
80
return mixin ( AuthenticationGuard ) ;
0 commit comments