Skip to content

Commit fed0300

Browse files
committed
fix(examples-nestjs-guard): error on missing userId in params; Adds Readme
1 parent 63fe491 commit fed0300

2 files changed

Lines changed: 33 additions & 4 deletions

File tree

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
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

‎packages/examples/nestjs-guard/src/app/guard/keto-guard.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff 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
}

0 commit comments

Comments
 (0)