File tree Expand file tree Collapse file tree 2 files changed +50
-0
lines changed
packages/kratos-client-wrapper/src Expand file tree Collapse file tree 2 files changed +50
-0
lines changed Original file line number Diff line number Diff line change
1
+ export { OryAuthenticationGuard } from './lib/ory-authentication.guard' ;
1
2
export {
2
3
OryIdentitiesModuleAsyncOptions ,
3
4
OryIdentitiesModuleOptions ,
Original file line number Diff line number Diff line change
1
+ import {
2
+ CanActivate ,
3
+ ExecutionContext ,
4
+ Injectable ,
5
+ mixin ,
6
+ } from '@nestjs/common' ;
7
+ import { OryFrontendService } from './ory-frontend' ;
8
+ import type { Session } from '@ory/client' ;
9
+
10
+ export const OryAuthenticationGuard = (
11
+ options : {
12
+ cookieResolver : ( ctx : ExecutionContext ) => string ;
13
+ isValidSession : ( session : Session ) => boolean ;
14
+ sessionTokenResolver : ( ctx : ExecutionContext ) => string ;
15
+ postValidationHook ?: (
16
+ ctx : ExecutionContext ,
17
+ session : Session
18
+ ) => void | Promise < void > ;
19
+ } = {
20
+ isValidSession ( ) : boolean {
21
+ return true ;
22
+ } ,
23
+ sessionTokenResolver : ( ctx ) =>
24
+ ctx . switchToHttp ( ) . getRequest ( ) . headers . authorization ,
25
+ cookieResolver : ( ctx ) => ctx . switchToHttp ( ) . getRequest ( ) . headers . cookie ,
26
+ }
27
+ ) => {
28
+ @Injectable ( )
29
+ class AuthenticationGuard implements CanActivate {
30
+ constructor ( readonly oryService : OryFrontendService ) { }
31
+
32
+ async canActivate ( context : ExecutionContext ) : Promise < boolean > {
33
+ const cookie = options . cookieResolver ( context ) ;
34
+ const xSessionToken = options . sessionTokenResolver ( context ) ;
35
+ const { data : session } = await this . oryService . toSession ( {
36
+ cookie,
37
+ xSessionToken,
38
+ } ) ;
39
+ if ( ! options . isValidSession ( session ) ) {
40
+ return false ;
41
+ }
42
+ if ( typeof options . postValidationHook === 'function' ) {
43
+ await options . postValidationHook ( context , session ) ;
44
+ }
45
+ return true ;
46
+ }
47
+ }
48
+ return mixin ( AuthenticationGuard ) ;
49
+ } ;
You can’t perform that action at this time.
0 commit comments