auth/src/modules/oldauthentication/domain/usecases/validate-authentication.use...

42 lines
1.5 KiB
TypeScript

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<Authentication> => {
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();
}
};
}