From 3b571620bdeb38a744f21c839be5a86e069a744c Mon Sep 17 00:00:00 2001 From: Kosta <68782786+KostaD02@users.noreply.github.com> Date: Fri, 18 Aug 2023 17:08:52 +0400 Subject: [PATCH] fix(auth): process env reading in other module & refactored jwt guard --- src/enums/exceptions.enum.ts | 3 ++ .../user/auth/guards/jwt-auth.guard.ts | 52 +++++++++++++++++-- src/modules/user/user.module.ts | 4 +- 3 files changed, 55 insertions(+), 4 deletions(-) diff --git a/src/enums/exceptions.enum.ts b/src/enums/exceptions.enum.ts index eb3e43e..0b10fde 100644 --- a/src/enums/exceptions.enum.ts +++ b/src/enums/exceptions.enum.ts @@ -38,4 +38,7 @@ export enum GlobalExceptionKeys { export enum AuthExpectionKeys { IncorrectEmailOrPassword = 'errors.incorrect_email_or_password', EmailInUse = 'errors.email_in_use', + TokenInvalid = 'errors.token_invalid', + TokenExpired = 'errors.token_expired', + TokenNotFound = 'errors.token_not_found', } diff --git a/src/modules/user/auth/guards/jwt-auth.guard.ts b/src/modules/user/auth/guards/jwt-auth.guard.ts index f65f845..21778ba 100644 --- a/src/modules/user/auth/guards/jwt-auth.guard.ts +++ b/src/modules/user/auth/guards/jwt-auth.guard.ts @@ -1,5 +1,51 @@ -import { Injectable } from '@nestjs/common'; -import { AuthGuard } from '@nestjs/passport'; +import { ExceptionService } from './../../../../shared/exception.service'; +import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'; +import { JwtService } from '@nestjs/jwt'; +import { Request } from 'express'; +import { AuthExpectionKeys, ExceptionStatusKeys } from 'src/enums'; @Injectable() -export class JwtGuard extends AuthGuard('jwt') {} +export class JwtGuard implements CanActivate { + constructor( + private jwtService: JwtService, + private exceptionService: ExceptionService, + ) {} + + async canActivate(context: ExecutionContext): Promise { + const request = context.switchToHttp().getRequest(); + const token = this.extractTokenFromHeader(request); + if (!token) { + this.exceptionService.throwError( + ExceptionStatusKeys.BadRequest, + 'Token not found', + AuthExpectionKeys.TokenNotFound, + ); + } + try { + const payload = await this.jwtService.verifyAsync(token, { + secret: `${process.env.JWT_SECRET}`, + }); + request['user'] = payload; + } catch (err) { + this.exceptionService.throwError( + ExceptionStatusKeys.BadRequest, + 'Invalid token', + AuthExpectionKeys.TokenInvalid, + ); + } + return true; + } + + private extractTokenFromHeader(request: Request): string | undefined { + const authHeader = request.headers['authorization']; + const accessTokenCookie = request.cookies.access_token; + let accessToken: string; + + if (authHeader && authHeader.startsWith('Bearer ')) { + accessToken = authHeader.substring(7); + } else if (accessTokenCookie) { + accessToken = accessTokenCookie; + } + return accessToken; + } +} diff --git a/src/modules/user/user.module.ts b/src/modules/user/user.module.ts index 5b46234..3431714 100644 --- a/src/modules/user/user.module.ts +++ b/src/modules/user/user.module.ts @@ -1,14 +1,16 @@ import { Module } from '@nestjs/common'; +import { ConfigModule } from '@nestjs/config'; +import { JwtModule } from '@nestjs/jwt'; import { EncryptionService, ExceptionService } from 'src/shared'; import { AuthController, AuthService } from './auth'; import { MongooseModule } from '@nestjs/mongoose'; import { User, UserSchema } from 'src/schemas'; -import { JwtModule } from '@nestjs/jwt'; import { JwtStrategy, LocalStrategy } from './auth/strategies'; import { RefreshJwtGuard } from './auth/guards'; @Module({ imports: [ + ConfigModule.forRoot(), MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]), JwtModule.register({ secret: `${process.env.JWT_SECRET}`,