Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

장소 모듈에 유저 모듈 연동해 권한 확인 및 AuthUser 데코레이터 버그 수정 #84

Merged
merged 9 commits into from
Nov 9, 2024
Merged
2 changes: 1 addition & 1 deletion backend/src/auth/AuthUser.decorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ function isAuthUser(obj: any): obj is AuthUser {
return (
typeof obj === 'object' &&
obj !== null &&
typeof obj.userId === 'number' &&
!isNaN(obj.userId) &&
Miensoap marked this conversation as resolved.
Show resolved Hide resolved
typeof obj.role === 'string'
);
}
6 changes: 2 additions & 4 deletions backend/src/auth/JwtAuthGuard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { TokenExpiredError } from 'jsonwebtoken';
import { ConfigService } from '@nestjs/config';
import { AuthenticationException } from './exception/AuthenticationException';
import { extractBearerToken } from './utils';
import { AuthUser } from './AuthUser.decorator';

@Injectable()
export class JwtAuthGuard implements CanActivate {
Expand All @@ -20,10 +21,7 @@ export class JwtAuthGuard implements CanActivate {
throw new AuthenticationException('토큰이 없습니다.');
}
try {
request.user = jwt.verify(token, this.jwtSecretKey) as {
userId: string;
role: string;
};
request.user = jwt.verify(token, this.jwtSecretKey) as AuthUser;
return true;
} catch (error) {
if (error instanceof TokenExpiredError) {
Expand Down
3 changes: 3 additions & 0 deletions backend/src/auth/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ const BEARER = 'Bearer';
const BEARER_REGEX = new RegExp(`^${BEARER}\\s+([A-Za-z0-9\\-._~+\\/=]*)$`);

export function extractBearerToken(header: string): string | null {
if (!header) {
return null;
}
const match = header.match(BEARER_REGEX);
Miensoap marked this conversation as resolved.
Show resolved Hide resolved
return match ? match[1] : null;
}
Expand Down
26 changes: 21 additions & 5 deletions backend/src/course/course.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,15 @@ import {
Param,
Patch,
Put,
UseGuards,
} from '@nestjs/common';
import { CreateCourseRequest } from './dto/CreateCourseRequest';
import { UpdateCourseInfoRequest } from './dto/UpdateCourseInfoRequest';
import { CourseService } from './course.service';
import { SetPlacesOfCourseRequest } from './dto/AddPlaceToCourseRequest';
import { JwtAuthGuard } from '../auth/JwtAuthGuard';
import { AuthUser } from '../auth/AuthUser.decorator';
import { CoursePermissionGuard } from './guards/CoursePermissionGuard';

@Controller('/courses')
export class CourseController {
Expand All @@ -31,8 +35,9 @@ export class CourseController {
}

@Get('/my')
async getMyCourseList() {
const userId = 1; // Todo. 로그인 기능 완성 후 수정
@UseGuards(JwtAuthGuard)
async getMyCourseList(@AuthUser() user: AuthUser) {
const userId = Number(user.userId);
return await this.courseService.getOwnCourses(userId);
}

Expand All @@ -42,13 +47,19 @@ export class CourseController {
}

@Post()
async createCourse(@Body() createCourseRequest: CreateCourseRequest) {
const userId = 1; // Todo. 로그인 기능 완성 후 수정
@UseGuards(JwtAuthGuard)
async createCourse(
@AuthUser() user: AuthUser,
@Body() createCourseRequest: CreateCourseRequest,
) {
const userId = Number(user.userId);
return await this.courseService.createCourse(userId, createCourseRequest);
}

@Put('/:id/places')
@UseGuards(JwtAuthGuard, CoursePermissionGuard)
async setPlacesOfCourse(
@AuthUser() user: AuthUser,
@Param('id') id: number,
@Body() setPlacesOfCourseRequest: SetPlacesOfCourseRequest,
) {
Expand All @@ -59,7 +70,9 @@ export class CourseController {
}

@Patch('/:id/info')
@UseGuards(JwtAuthGuard, CoursePermissionGuard)
async updateCourseInfo(
@AuthUser() user: AuthUser,
@Param('id') id: number,
@Body() updateCourseInfoRequest: UpdateCourseInfoRequest,
) {
Expand All @@ -68,7 +81,9 @@ export class CourseController {
}

@Patch('/:id/visibility')
@UseGuards(JwtAuthGuard, CoursePermissionGuard)
async updateCourseVisibility(
@AuthUser() user: AuthUser,
@Param('id') id: number,
@Body('isPublic') isPublic: boolean,
) {
Expand All @@ -77,7 +92,8 @@ export class CourseController {
}

@Delete('/:id')
async deleteCourse(@Param('id') id: number) {
@UseGuards(JwtAuthGuard, CoursePermissionGuard)
async deleteCourse(@AuthUser() user: AuthUser, @Param('id') id: number) {
Miensoap marked this conversation as resolved.
Show resolved Hide resolved
return await this.courseService.deleteCourse(id);
}
}
12 changes: 12 additions & 0 deletions backend/src/course/exception/CoursePermissionException.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { BaseException } from '../../common/exception/BaseException';
import { HttpStatus } from '@nestjs/common';

export class CoursePermissionException extends BaseException {
constructor(id: number) {
super({
code: 903,
Miensoap marked this conversation as resolved.
Show resolved Hide resolved
message: `id:${id} 코스에 대한 권한이 없습니다.`,
status: HttpStatus.FORBIDDEN,
});
}
}
20 changes: 20 additions & 0 deletions backend/src/course/guards/CoursePermissionGuard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { CourseService } from '../course.service';
import { CoursePermissionException } from '../exception/CoursePermissionException';

@Injectable()
export class CoursePermissionGuard implements CanActivate {
constructor(private readonly courseService: CourseService) {}

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

const course = await this.courseService.getCourseById(courseId);
if (course.user.id !== userId) {
throw new CoursePermissionException(courseId);
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

p2.

    const courseOwnerId = await this.courseService.getCourseOwnerId(courseId);
    if (courseOwnerId !== userId) {
      throw new CoursePermissionException(courseId);
    }

메서드 추가해서
이렇게 필요한 부분만 조회하는건 어떨까요?

return course.user.id === userId;
}
}
Loading