From 7ffbca223090e18bc448c00d81a69deb3fd8b0aa Mon Sep 17 00:00:00 2001 From: Shun Usami Date: Wed, 8 Nov 2023 10:53:00 +0900 Subject: [PATCH] [backend] Implement UserGuard and add it to UserController --- backend/src/user/user.controller.ts | 4 ++++ backend/src/user/user.guard.ts | 15 ++++++++++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/backend/src/user/user.controller.ts b/backend/src/user/user.controller.ts index 96989ebf..4f536ab2 100644 --- a/backend/src/user/user.controller.ts +++ b/backend/src/user/user.controller.ts @@ -23,6 +23,7 @@ import { } from '@nestjs/swagger'; import { UserEntity } from './entities/user.entity'; import { JwtAuthGuard } from 'src/auth/jwt-auth.guard'; +import { UserGuard } from './user.guard'; @Controller('user') @ApiTags('user') @@ -44,6 +45,7 @@ export class UserController { } @Get(':id') + @UseGuards(UserGuard) @UseGuards(JwtAuthGuard) @ApiBearerAuth() @ApiOkResponse({ type: UserEntity }) @@ -52,6 +54,7 @@ export class UserController { } @Patch(':id') + @UseGuards(UserGuard) @UseGuards(JwtAuthGuard) @ApiBearerAuth() @ApiOkResponse({ type: UserEntity }) @@ -64,6 +67,7 @@ export class UserController { @Delete(':id') @HttpCode(204) + @UseGuards(UserGuard) @UseGuards(JwtAuthGuard) @ApiBearerAuth() @ApiNoContentResponse() diff --git a/backend/src/user/user.guard.ts b/backend/src/user/user.guard.ts index 2ac11f66..dc526660 100644 --- a/backend/src/user/user.guard.ts +++ b/backend/src/user/user.guard.ts @@ -1,11 +1,24 @@ import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'; import { Observable } from 'rxjs'; +import { UserService } from './user.service'; @Injectable() export class UserGuard implements CanActivate { + constructor(private readonly userService: UserService) {} + canActivate( context: ExecutionContext, ): boolean | Promise | Observable { - return true; + const req = context.switchToHttp().getRequest(); + // https://docs.nestjs.com/recipes/passport + // Passport automatically creates a user object, based on the value we return from the validate() method, and assigns it to the Request object as req.user. + const { params, user } = req; + + if (params?.id == null) { + return true; // this request isn't scoped to a single existing todo + } + + // user.id is a number, params.id is a string + return user.id === Number(params.id); } }