From 6b425eba6f7f46b4d950d266642dfff22cce7129 Mon Sep 17 00:00:00 2001 From: unknown Date: Sun, 11 Aug 2024 15:32:20 +0300 Subject: [PATCH] error handling for login --- src/auth/services/user-auth.service.ts | 67 +++++++++++++------------- 1 file changed, 34 insertions(+), 33 deletions(-) diff --git a/src/auth/services/user-auth.service.ts b/src/auth/services/user-auth.service.ts index 1e0aa41..7cf7435 100644 --- a/src/auth/services/user-auth.service.ts +++ b/src/auth/services/user-auth.service.ts @@ -40,7 +40,7 @@ export class UserAuthService { throw new BadRequestException('User already registered with given email'); } const salt = this.helperHashService.randomSalt(10); // Hash the password using bcrypt - const hashedPassword = await this.helperHashService.bcrypt( + const hashedPassword = this.helperHashService.bcrypt( userSignUpDto.password, salt, ); @@ -90,39 +90,40 @@ export class UserAuthService { } async userLogin(data: UserLoginDto) { - const user = await this.authService.validateUser( - data.email, - data.password, - data.regionUuid, - ); - - if (!user) { - throw new UnauthorizedException('Invalid login credentials.'); - } - - const session = await Promise.all([ - await this.sessionRepository.update( - { userId: user.id }, - { - isLoggedOut: true, - }, - ), - await this.authService.createSession({ + try { + const user = await this.authService.validateUser( + data.email, + data.password, + data.regionUuid, + ); + if (!user) { + throw new UnauthorizedException('Invalid login credentials.'); + } + const session = await Promise.all([ + await this.sessionRepository.update( + { userId: user.id }, + { + isLoggedOut: true, + }, + ), + await this.authService.createSession({ + userId: user.uuid, + loginTime: new Date(), + isLoggedOut: false, + }), + ]); + return await this.authService.login({ + email: user.email, userId: user.uuid, - loginTime: new Date(), - isLoggedOut: false, - }), - ]); - - return await this.authService.login({ - email: user.email, - userId: user.uuid, - uuid: user.uuid, - roles: user?.roles?.map((role) => { - return { uuid: role.uuid, type: role.roleType.type }; - }), - sessionId: session[1].uuid, - }); + uuid: user.uuid, + roles: user?.roles?.map((role) => { + return { uuid: role.uuid, type: role.roleType.type }; + }), + sessionId: session[1].uuid, + }); + } catch (error) { + throw new UnauthorizedException('User unauthorized'); + } } async deleteUser(uuid: string) {