From 93af1ff153100686b0eb97a1003cca105908356f Mon Sep 17 00:00:00 2001 From: SiWooJinSeok <59861974+SiWooJinSeok@users.noreply.github.com> Date: Thu, 25 Apr 2024 15:47:05 +0900 Subject: [PATCH 1/3] =?UTF-8?q?chore=20:=20=EC=9E=84=EC=8B=9C=20=EC=A0=80?= =?UTF-8?q?=EC=9E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/auth/auth.service.ts | 3 +++ src/auth/jwt-auth-guard.ts | 30 ++++++++++++++++++++++++++++++ src/auth/password.controller.ts | 15 +++++++++++++-- src/main.ts | 4 ++++ 4 files changed, 50 insertions(+), 2 deletions(-) create mode 100644 src/auth/jwt-auth-guard.ts diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.ts index 2c2c4d5..25f4834 100644 --- a/src/auth/auth.service.ts +++ b/src/auth/auth.service.ts @@ -163,6 +163,7 @@ export class AuthService { } } + // 토큰 얻기 async getToken(refreshToken: string) { this.logger.info( `Attempting to refresh token with refresh token: ${refreshToken}`, @@ -189,6 +190,7 @@ export class AuthService { } } + // 비밀번호 잊었을 때 이메일로 코드요청 async forgotPassword(emailDto: EmailDto) { this.logger.info( `Attempting to initiate forgot password for email: ${emailDto.email}`, @@ -212,6 +214,7 @@ export class AuthService { } } + // 새 비밀번호로 변경 async confirmPasswordReset(forgotPasswordDto: ForgotPasswordDto) { this.logger.info( `Attempting to confirm password reset for user: ${forgotPasswordDto.email}`, diff --git a/src/auth/jwt-auth-guard.ts b/src/auth/jwt-auth-guard.ts new file mode 100644 index 0000000..de3f110 --- /dev/null +++ b/src/auth/jwt-auth-guard.ts @@ -0,0 +1,30 @@ +import { AuthService } from './auth.service'; +import { + CanActivate, + ExecutionContext, + Injectable, + UnauthorizedException, + Request, +} from '@nestjs/common'; + +@Injectable() +export class JwtAuthGuard implements CanActivate { + constructor(private readonly authService: AuthService) {} + + async canActivate(context: ExecutionContext): Promise { + const request = context.switchToHttp().getRequest(); + const accessToken = request.headers['authorization']?.split(' ')[1]; + + if (!accessToken) { + throw new UnauthorizedException('헤더에 토큰이 없습니다.'); + } + + const user = await this.authService.tokenGetUser(accessToken); + if (!user || !user.email) { + throw new UnauthorizedException('유저가 없습니다.'); + } + + request['userId'] = user.id; + return true; + } +} diff --git a/src/auth/password.controller.ts b/src/auth/password.controller.ts index b71b612..41b8afa 100644 --- a/src/auth/password.controller.ts +++ b/src/auth/password.controller.ts @@ -5,8 +5,15 @@ import { HttpStatus, Post, Request, + UseGuards, } from '@nestjs/common'; -import { ApiBody, ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger'; +import { + ApiBearerAuth, + ApiBody, + ApiOperation, + ApiResponse, + ApiTags, +} from '@nestjs/swagger'; import { AuthService } from './auth.service'; import { ForgotSchema } from './schema/forgot.schema'; import { ForgotConfirmSchema } from './schema/forgotConfirm.schema'; @@ -18,6 +25,7 @@ import { import { EmailDto } from './../dto/email.dto'; import { ForgotPasswordDto } from './../dto/forgotPassword.dto'; import { ChangePasswordDto } from './../dto/changePassword.dto'; +import { JwtAuthGuard } from './jwt-auth-guard'; @Controller('api/user/v1/') export class PasswordController { @@ -56,6 +64,8 @@ export class PasswordController { // 비밀번호 변경 @ApiTags('auth') @Post('user/password') + @UseGuards(JwtAuthGuard) + @ApiBearerAuth('accessToken') @ApiOperation({ summary: '비밀번호 변경', }) @@ -70,6 +80,7 @@ export class PasswordController { throw new HttpException('토큰이 없습니다.', HttpStatus.BAD_REQUEST); } - return await this.authService.changePassword(token, changePasswordDto); + return request.userId; + // return await this.authService.changePassword(token, changePasswordDto); } } diff --git a/src/main.ts b/src/main.ts index b54d1ee..5a80a95 100644 --- a/src/main.ts +++ b/src/main.ts @@ -20,6 +20,10 @@ async function bootstrap() { .setDescription('pqsoft') .setVersion('1.0') .addTag('auth') + .addBearerAuth( + { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' }, + 'accessToken', // 이 이름이 스웨거 UI에서 보안 스키마를 참조하는 데 사용됩니다. + ) .build(); const document = SwaggerModule.createDocument(app, config); SwaggerModule.setup('api/user/v1', app, document); From 8ff0a89e940dfb945f3ac46a80f5288f515e3891 Mon Sep 17 00:00:00 2001 From: SiWooJinSeok <59861974+SiWooJinSeok@users.noreply.github.com> Date: Thu, 25 Apr 2024 17:03:50 +0900 Subject: [PATCH 2/3] =?UTF-8?q?feat=20:=20JwtAuthGuard=20=EC=99=84?= =?UTF-8?q?=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/auth/auth.controller.ts | 2 +- src/auth/password.controller.ts | 22 ++++++---------------- 2 files changed, 7 insertions(+), 17 deletions(-) diff --git a/src/auth/auth.controller.ts b/src/auth/auth.controller.ts index 51ac0a2..b60fa1d 100644 --- a/src/auth/auth.controller.ts +++ b/src/auth/auth.controller.ts @@ -61,7 +61,7 @@ export class AuthController { summary: '회원가입 이메일 인증', }) async confirmSignup(@Body() confirmSignupDto: ConfirmSignupDto) { - return await this.authService.confirmSignUp(confirmSignupDto); + await this.authService.confirmSignUp(confirmSignupDto); } // 인증번호 다시보내기 diff --git a/src/auth/password.controller.ts b/src/auth/password.controller.ts index 41b8afa..ec3eb92 100644 --- a/src/auth/password.controller.ts +++ b/src/auth/password.controller.ts @@ -1,12 +1,4 @@ -import { - Body, - Controller, - HttpException, - HttpStatus, - Post, - Request, - UseGuards, -} from '@nestjs/common'; +import { Body, Controller, Post, Request, UseGuards } from '@nestjs/common'; import { ApiBearerAuth, ApiBody, @@ -75,12 +67,10 @@ export class PasswordController { @Request() request, @Body() changePasswordDto: ChangePasswordDto, ) { - const [type, token] = request.headers.authorization?.split(' ') ?? []; - if (type !== 'Bearer' || !token) { - throw new HttpException('토큰이 없습니다.', HttpStatus.BAD_REQUEST); - } - - return request.userId; - // return await this.authService.changePassword(token, changePasswordDto); + const accessToken = request.headers['authorization']?.split(' ')[1]; + return await this.authService.changePassword( + accessToken, + changePasswordDto, + ); } } From 5c2d3f5b423adaac70c3c454af108febbfc3f857 Mon Sep 17 00:00:00 2001 From: SiWooJinSeok <59861974+SiWooJinSeok@users.noreply.github.com> Date: Thu, 25 Apr 2024 18:35:35 +0900 Subject: [PATCH 3/3] =?UTF-8?q?fix=20:=20return=20=EB=AC=B8=20=EC=A0=9C?= =?UTF-8?q?=EA=B1=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/auth/auth.service.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.ts index 350c032..2151758 100644 --- a/src/auth/auth.service.ts +++ b/src/auth/auth.service.ts @@ -72,7 +72,7 @@ export class AuthService { try { this.logger.info(`User ${signupDto.email} signed up successfully.`); - return await this.cognitoClient.signUp(params).promise(); + await this.cognitoClient.signUp(params).promise(); return await this.userService.createUser(signupDto); } catch (e) {