import { QueryHandler } from '@nestjs/cqrs'; import { AuthenticationRepository } from '../../adapters/secondaries/authentication.repository'; import { ValidateAuthenticationQuery as ValidateAuthenticationQuery } from '../../queries/validate-authentication.query'; import { Authentication } from '../entities/authentication'; import * as bcrypt from 'bcrypt'; import { NotFoundException, UnauthorizedException } from '@nestjs/common'; import { UsernameRepository } from '../../adapters/secondaries/username.repository'; import { Username } from '../entities/username'; @QueryHandler(ValidateAuthenticationQuery) export class ValidateAuthenticationUseCase { constructor( private readonly authenticationRepository: AuthenticationRepository, private readonly usernameRepository: UsernameRepository, ) {} execute = async ( validate: ValidateAuthenticationQuery, ): Promise => { let username = new Username(); try { username = await this.usernameRepository.findOne({ username: validate.username, }); } catch (e) { throw new NotFoundException(); } try { const auth = await this.authenticationRepository.findOne({ uuid: username.uuid, }); if (auth) { const isMatch = await bcrypt.compare(validate.password, auth.password); if (isMatch) return auth; } throw new UnauthorizedException(); } catch (e) { throw new UnauthorizedException(); } }; }