Skip to content

Commit

Permalink
[WIP] login したユーザーは自分の情報にのみアクセスできる (#32)
Browse files Browse the repository at this point in the history
* yarn nest generate guard (user)

* [backend] Implement UserGuard and add it to UserController

* user guard don't user UserService class
  • Loading branch information
kotto5 authored Nov 8, 2023
1 parent 1d01b8a commit 1cd1664
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
4 changes: 4 additions & 0 deletions backend/src/user/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand All @@ -44,6 +45,7 @@ export class UserController {
}

@Get(':id')
@UseGuards(UserGuard)
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiOkResponse({ type: UserEntity })
Expand All @@ -52,6 +54,7 @@ export class UserController {
}

@Patch(':id')
@UseGuards(UserGuard)
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiOkResponse({ type: UserEntity })
Expand All @@ -64,6 +67,7 @@ export class UserController {

@Delete(':id')
@HttpCode(204)
@UseGuards(UserGuard)
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiNoContentResponse()
Expand Down
7 changes: 7 additions & 0 deletions backend/src/user/user.guard.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { UserGuard } from './user.guard';

describe('UserGuard', () => {
it('should be defined', () => {
expect(new UserGuard()).toBeDefined();
});
});
16 changes: 16 additions & 0 deletions backend/src/user/user.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { CanActivate, ExecutionContext } from '@nestjs/common';
import { Observable } from 'rxjs';

export class UserGuard implements CanActivate {

canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
const req = context.switchToHttp().getRequest();
const { params, user } = req;
if (params?.id == null) {
return true;
}
return user.id === Number(params.id);
}
}

0 comments on commit 1cd1664

Please sign in to comment.