Skip to content

Commit

Permalink
Merge pull request #126 from boostcampwm2023/feature-be-#125
Browse files Browse the repository at this point in the history
[BE] feat#125 Guard를 설정한다
  • Loading branch information
flydog98 authored Nov 27, 2023
2 parents b2db071 + cd301a7 commit adf9b95
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 14 deletions.
10 changes: 10 additions & 0 deletions packages/backend/src/command.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';

@Injectable()
export class CommandGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest<Request>();
const command = request.body['command'];
return typeof command === 'string' && command.startsWith('git');
}
}
25 changes: 11 additions & 14 deletions packages/backend/src/quizzes/quizzes.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ import {
HttpException,
HttpStatus,
Res,
Req,
Inject,
Delete,
UseGuards,
} from '@nestjs/common';
import {
ApiTags,
Expand All @@ -25,8 +25,11 @@ import { QuizzesDto } from './dto/quizzes.dto';
import { CommandRequestDto } from './dto/command-request.dto';
import { CommandResponseDto } from './dto/command-response.dto';
import { SessionService } from '../session/session.service';
import { Request, Response } from 'express';
import { Response } from 'express';
import { ContainersService } from '../containers/containers.service';
import { SessionId } from '../session/session.decorator';
import { SessionGuard } from '../session/session.guard';
import { CommandGuard } from '../command.guard';

@ApiTags('quizzes')
@Controller('api/v1/quizzes')
Expand Down Expand Up @@ -66,6 +69,7 @@ export class QuizzesController {
}

@Post(':id/command')
@UseGuards(CommandGuard)
@ApiOperation({ summary: 'Git 명령을 실행합니다.' })
@ApiResponse({
status: 200,
Expand All @@ -78,22 +82,20 @@ export class QuizzesController {
@Param('id') id: number,
@Body() execCommandDto: CommandRequestDto,
@Res() response: Response,
@Req() request: Request,
@SessionId() sessionId: string,
): Promise<CommandResponseDto> {
try {
let sessionId = request.cookies?.sessionId;

if (!sessionId) {
// 세션 아이디가 없다면
this.logger.log('info', 'no session id. creating session..');
response.cookie(
'sessionId',
(sessionId = await this.sessionService.createSession()),
{
httpOnly: true,
// 개발 이후 활성화 시켜야함
// secure: true,
},
); // 세션 아이디를 생성한다.
this.logger.log('info', `session id: ${sessionId} created`);
}

let containerId = await this.sessionService.getContainerIdBySessionId(
Expand Down Expand Up @@ -148,6 +150,7 @@ export class QuizzesController {
}

@Delete(':id/command')
@UseGuards(SessionGuard)
@ApiOperation({ summary: 'Git 명령기록과, 할당된 컨테이너를 삭제합니다' })
@ApiResponse({
status: 200,
Expand All @@ -157,15 +160,9 @@ export class QuizzesController {
@ApiParam({ name: 'id', description: '문제 ID' })
async deleteCommandHistory(
@Param('id') id: number,
@Req() request: Request,
@SessionId() sessionId: string,
): Promise<void> {
try {
const sessionId = request.cookies?.sessionId;

if (!sessionId) {
return;
}

const containerId = await this.sessionService.getContainerIdBySessionId(
sessionId,
id,
Expand Down
8 changes: 8 additions & 0 deletions packages/backend/src/session/session.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { createParamDecorator, ExecutionContext } from '@nestjs/common';

export const SessionId = createParamDecorator(
(data: unknown, ctx: ExecutionContext) => {
const request = ctx.switchToHttp().getRequest();
return request.cookies['sessionId'];
},
);
16 changes: 16 additions & 0 deletions packages/backend/src/session/session.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';

/**
* @description session guard
* @returns {boolean}
* check if sessionId exists
* @dependency cookie-parser
*/
@Injectable()
export class SessionGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest<Request>();
// cookie-parser must be used before this guard
return request['cookies'].sessionId;
}
}

0 comments on commit adf9b95

Please sign in to comment.