Skip to content

Commit

Permalink
feat: 유저 본인이 아니면 유저 정보를 가져올 수 없도록 권한 부여 #158
Browse files Browse the repository at this point in the history
  • Loading branch information
koomchang committed Nov 20, 2024
1 parent 9793638 commit 7ec0da8
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 2 deletions.
2 changes: 1 addition & 1 deletion backend/src/course/exception/CoursePermissionException.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { BaseException } from '../../common/exception/BaseException';
import { BaseException } from '@src/common/exception/BaseException';
import { HttpStatus } from '@nestjs/common';

export class CoursePermissionException extends BaseException {
Expand Down
11 changes: 11 additions & 0 deletions backend/src/user/exception/UserPermissionException.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { BaseException } from '@src/common/exception/BaseException';

export class UserPermissionException extends BaseException {
constructor(id: number) {
super({
code: 2001,
message: `id:${id} 유저에 대한 권한이 없습니다.`,
status: 403,
});
}
}
20 changes: 20 additions & 0 deletions backend/src/user/guards/UserPermissionGuard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { UserService } from '@src/user/user.service';
import { UserPermissionException } from '@src/user/exception/UserPermissionException';

@Injectable()
export class UserPermissionGuard implements CanActivate {
constructor(private readonly userService: UserService) {}

async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const userId = Number(request.params.id);
const requesterId = Number(request.user.userId);

const user = await this.userService.getUserInfo(userId);
if (user.id !== requesterId) {
throw new UserPermissionException(userId);
}
return true;
}
}
5 changes: 4 additions & 1 deletion backend/src/user/user.controller.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import { Controller, Get, Param } from '@nestjs/common';
import { Controller, Get, Param, UseGuards } from '@nestjs/common';
import { UserService } from './user.service';
import { JwtAuthGuard } from '@src/auth/JwtAuthGuard';
import { UserPermissionGuard } from '@src/user/guards/UserPermissionGuard';

@Controller('users')
export class UserController {
constructor(private readonly userService: UserService) {}

@Get('/:id')
@UseGuards(JwtAuthGuard, UserPermissionGuard)
async getUserInfo(@Param('id') id: number) {
return await this.userService.getUserInfo(id);
}
Expand Down

0 comments on commit 7ec0da8

Please sign in to comment.