You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
49 lines
1.6 KiB
49 lines
1.6 KiB
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<string> { |
|
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'); |
|
} |
|
} |
|
} |