File tree Expand file tree Collapse file tree
packages/examples/nestjs-guard Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # relation-tuple-parser/examples/nestjs-guard
2+
3+ ## Startup
4+
5+ Start Keto:
6+
7+ ``` bash
8+ docker-compose up
9+ ```
10+
11+ Start nestjs-app:
12+
13+ ``` bash
14+ nx serve examples-nestjs-guard
15+ ```
16+
17+ Urls:
18+
19+ - Allowed access: http://localhost:3333/api?userId=user1
20+ - Allowed access: http://localhost:3333/api?userId=user2
21+ - Forbidden access: http://localhost:3333/api?userId=user3
22+ - Forbidden access: http://localhost:3333/api
23+
24+ ## Files
25+
26+ - [ src/app/app.controller.ts] ( ./src/app/app.controller.ts ) : Contains the secured endpoint
27+ - [ src/app/guard/keto-guard.ts] ( ./src/app/guard/keto-guard.ts ) : Contains guard that protects the app
Original file line number Diff line number Diff line change @@ -20,8 +20,10 @@ export class KetoGuard implements CanActivate {
2020 return false // Deny every request by default
2121 }
2222
23- let userId = this . getUserId ( ctx )
24- const ketoResult = await this . _ketoReadClient . validateRelationTuple ( relationTuple , { userId } )
23+ const userId = this . getUserId ( ctx )
24+ const ketoResult = await this . _ketoReadClient . validateRelationTuple ( relationTuple , {
25+ userId : userId ?? 'Unauthorized' ,
26+ } )
2527
2628 if ( ketoResult . hasError ( ) ) {
2729 const { error } = ketoResult
@@ -45,14 +47,14 @@ export class KetoGuard implements CanActivate {
4547 * @param ctx
4648 * @private
4749 */
48- private getUserId ( ctx : HttpArgumentsHost ) {
50+ private getUserId ( ctx : HttpArgumentsHost ) : string | null {
4951 const request = ctx . getRequest < IncomingMessage > ( )
5052 const { userId : rawUserId } = Url . parse ( request . url , true ) . query
5153
5254 if ( Array . isArray ( rawUserId ) ) {
5355 return rawUserId [ 0 ]
5456 } else {
55- return rawUserId
57+ return rawUserId ?? null
5658 }
5759 }
5860}
You can’t perform that action at this time.
0 commit comments