Skip to content

Commit

Permalink
feat: AuthUser 데코레이터 추가, 장소 컨트롤러에 가드 적용 #81
Browse files Browse the repository at this point in the history
  • Loading branch information
Miensoap committed Nov 9, 2024
1 parent 74987f5 commit d677759
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
31 changes: 31 additions & 0 deletions backend/src/auth/AuthUser.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { AuthenticationException } from './exception/AuthenticationException';

export const AuthUser = createParamDecorator(
(data: unknown, ctx: ExecutionContext) => {
const requestingUser = ctx.switchToHttp().getRequest().user;
if (!requestingUser) {
throw new AuthenticationException('인증 정보가 없습니다.');
}

if (!isAuthUser(requestingUser)) {
throw new AuthenticationException('유효하지 않은 인증 정보입니다.');
}

return requestingUser as AuthUser;
},
);

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

function isAuthUser(obj: any): obj is AuthUser {
return (
typeof obj === 'object' &&
obj !== null &&
typeof obj.userId === 'number' &&
typeof obj.role === 'string'
);
}
12 changes: 11 additions & 1 deletion backend/src/place/place.controller.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,21 @@
import { Body, Controller, Get, Param, Post, Query } from '@nestjs/common';
import {
Body,
Controller,
Get,
Param,
Post,
Query,
UseGuards,
} from '@nestjs/common';
import { PlaceService } from './place.service';
import { CreatePlaceRequest } from './dto/CreatePlaceRequest';
import { JwtAuthGuard } from '../auth/JwtAuthGuard.';

@Controller('places')
export class PlaceController {
constructor(private readonly placeService: PlaceService) {}

@UseGuards(JwtAuthGuard)
@Post()
async addPlace(@Body() createPlaceDto: CreatePlaceRequest) {
return this.placeService.addPlace(createPlaceDto);
Expand Down

0 comments on commit d677759

Please sign in to comment.