import { Injectable, UnauthorizedException, Inject } from '@nestjs/common'; import { IAuthService } from '../interfaces/auth-service.interface'; import { LoggerService } from '../services/logger.service'; @Injectable() export class LoginUserCommand { constructor( @Inject('IAuthService') private readonly authService: IAuthService, @Inject(LoggerService) private readonly logger: LoggerService, ) {} async execute(username: string, password: string): Promise { try { this.logger.log(`Login attempt for user: ${username}`, LoginUserCommand.name); // Validate input parameters this.validateInput(username, password); const token = await this.authService.authenticate(username, password); if (!token) { this.logger.warn(`Authentication failed for user: ${username}`, LoginUserCommand.name); throw new UnauthorizedException('Invalid username or password'); } this.logger.log(`Successfully authenticated user: ${username}`, LoginUserCommand.name); return token; } catch (error) { if (error instanceof UnauthorizedException) { throw error; } this.logger.error(`Failed to login user ${username}: ${error.message}`, undefined, LoginUserCommand.name); throw new Error(`Failed to login: ${error.message}`); } } private validateInput(username: string, password: string): void { if (!username || username.trim().length === 0) { throw new Error('Username cannot be empty'); } if (!password || password.trim().length === 0) { throw new Error('Password cannot be empty'); } } }