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
178 changes: 107 additions & 71 deletions backend/resources/sql/Mock.sql

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions backend/src/auth/AuthUser.decorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,15 @@ export const AuthUser = createParamDecorator(
);

export interface AuthUser {
userId: string;
userId: number;
role: string;
}

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
2 changes: 1 addition & 1 deletion backend/src/auth/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const BEARER = 'Bearer';
const BEARER_REGEX = new RegExp(`^${BEARER}\\s+([A-Za-z0-9\\-._~+\\/=]*)$`);

export function extractBearerToken(header: string): string | null {
const match = header.match(BEARER_REGEX);
const match = header?.match(BEARER_REGEX);
return match ? match[1] : null;
}

Expand Down
26 changes: 20 additions & 6 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,9 +35,9 @@ export class CourseController {
}

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

@Get('/:id')
Expand All @@ -42,12 +46,19 @@ export class CourseController {
}

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

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

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

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

@Delete('/:id')
@UseGuards(JwtAuthGuard, CoursePermissionGuard)
async deleteCourse(@Param('id') id: number) {
return await this.courseService.deleteCourse(id);
}
Expand Down
7 changes: 7 additions & 0 deletions backend/src/course/course.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,13 @@ export class CourseService {
return await CourseDetailResponse.from(map);
}

async getCourseOwnerId(courseId: number) {
const course = await this.courseRepository.findById(courseId);
if (!course) throw new CourseNotFoundException(courseId);

return course.user.id;
}

async createCourse(userId: number, createMapForm: CreateCourseRequest) {
const user = { id: userId } as User;
const map = createMapForm.toEntity(user);
Expand Down
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: 905,
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.getCourseOwnerId(courseId);
if (course !== userId) {
throw new CoursePermissionException(courseId);
}
return true;
}
}
Loading