Skip to content

Commit 33a4e07

Browse files
committed
feat(kratos-client-wrapper): create OryAuthenticationGuard
1 parent d33ab07 commit 33a4e07

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

packages/kratos-client-wrapper/src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
export { OryAuthenticationGuard } from './lib/ory-authentication.guard';
12
export {
23
OryIdentitiesModuleAsyncOptions,
34
OryIdentitiesModuleOptions,
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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+
};

0 commit comments

Comments
 (0)