diff --git a/src/enums/exceptions.enum.ts b/src/enums/exceptions.enum.ts index bc9e68f..d878b0f 100644 --- a/src/enums/exceptions.enum.ts +++ b/src/enums/exceptions.enum.ts @@ -97,6 +97,8 @@ export enum AuthExpectionKeys { UserPermissionNotGranted = 'errors.user_permission_not_granted', NothingToUpdate = 'errors.nothing_to_update', UserNotFound = 'errors.user_not_found', + ShouldProvideEmail = 'errors.should_provide_email', + ShouldProvidePassword = 'errors.should_provide_password', } export enum CartExpectionKeys { diff --git a/src/modules/user/auth/guards/local-auth.guard.ts b/src/modules/user/auth/guards/local-auth.guard.ts index ccf962b..0bb5e3b 100644 --- a/src/modules/user/auth/guards/local-auth.guard.ts +++ b/src/modules/user/auth/guards/local-auth.guard.ts @@ -1,5 +1,47 @@ import { Injectable } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; +import { AuthExpectionKeys, ExceptionStatusKeys } from 'src/enums'; +import { ExceptionService } from 'src/shared'; @Injectable() -export class LocalAuthGuard extends AuthGuard('local') {} +export class LocalAuthGuard extends AuthGuard('local') { + constructor(private exceptionService: ExceptionService) { + super(); + } + + handleRequest(err, user, info, context) { + const request = context.switchToHttp().getRequest(); + const { email, password } = request.body; + if (err || !user) { + if (!email && !password) { + this.exceptionService.throwError( + ExceptionStatusKeys.BadRequest, + 'Should be provide: Email and Password', + [ + AuthExpectionKeys.ShouldProvideEmail, + AuthExpectionKeys.ShouldProvidePassword, + ], + ); + } else if (!email) { + this.exceptionService.throwError( + ExceptionStatusKeys.BadRequest, + 'Email should be provided', + AuthExpectionKeys.ShouldProvideEmail, + ); + } else if (!password) { + this.exceptionService.throwError( + ExceptionStatusKeys.BadRequest, + 'Password should be provided', + AuthExpectionKeys.ShouldProvidePassword, + ); + } else { + this.exceptionService.throwError( + ExceptionStatusKeys.BadRequest, + err.response.error, + err.response.message, + ); + } + } + return user; + } +}