Files
gridpilot.gg/core/identity/application/use-cases/LoginUseCase.ts
2025-12-21 17:05:36 +01:00

82 lines
2.7 KiB
TypeScript

import { EmailAddress } from '../../domain/value-objects/EmailAddress';
import { User } from '../../domain/entities/User';
import { IAuthRepository } from '../../domain/repositories/IAuthRepository';
import { IPasswordHashingService } from '../../domain/services/PasswordHashingService';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { UseCaseOutputPort, Logger, UseCase } from '@core/shared/application';
export type LoginInput = {
email: string;
password: string;
};
export type LoginResult = {
user: User;
};
export type LoginErrorCode = 'INVALID_CREDENTIALS' | 'REPOSITORY_ERROR';
export type LoginApplicationError = ApplicationErrorCode<LoginErrorCode, { message: string }>;
/**
* Application Use Case: LoginUseCase
*
* Handles user login by verifying credentials.
*/
export class LoginUseCase implements UseCase<LoginInput, LoginResult, LoginErrorCode> {
constructor(
private readonly authRepo: IAuthRepository,
private readonly passwordService: IPasswordHashingService,
private readonly logger: Logger,
private readonly output: UseCaseOutputPort<Result<LoginResult, LoginApplicationError>>,
) {}
async execute(input: LoginInput): Promise<Result<LoginResult, LoginApplicationError>> {
try {
const emailVO = EmailAddress.create(input.email);
const user = await this.authRepo.findByEmail(emailVO);
if (!user || !user.getPasswordHash()) {
const result = Result.err<LoginResult, LoginApplicationError>({
code: 'INVALID_CREDENTIALS',
details: { message: 'Invalid credentials' },
});
this.output.present(result);
return result;
}
const passwordHash = user.getPasswordHash()!;
const isValid = await this.passwordService.verify(input.password, passwordHash.value);
if (!isValid) {
const result = Result.err<LoginResult, LoginApplicationError>({
code: 'INVALID_CREDENTIALS',
details: { message: 'Invalid credentials' },
});
this.output.present(result);
return result;
}
const result = Result.ok<LoginResult, LoginApplicationError>({ user });
this.output.present(result);
return result;
} catch (error) {
const message =
error instanceof Error && error.message
? error.message
: 'Failed to execute LoginUseCase';
this.logger.error('LoginUseCase.execute failed', error instanceof Error ? error : undefined, {
input,
});
const result = Result.err<LoginResult, LoginApplicationError>({
code: 'REPOSITORY_ERROR',
details: { message },
});
this.output.present(result);
return result;
}
}
}