All files / src/application/user authenticate-user.use-case.ts

100% Statements 10/10
100% Branches 4/4
100% Functions 2/2
100% Lines 10/10

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34                        25x 25x 25x       211x   211x 4x     207x   207x 2x     205x      
import { UserRepository } from './user-repository';
import { PasswordHasher } from './password-hasher';
import { TokenPair, TokenService } from './token-service';
import { InvalidCredentialsError } from './errors/invalid-credentials.error';
 
export interface AuthenticateUserInput {
  email: string;
  password: string;
}
 
export class AuthenticateUserUseCase {
  constructor(
    private readonly userRepository: UserRepository,
    private readonly passwordHasher: PasswordHasher,
    private readonly tokenService: TokenService,
  ) {}
 
  async execute(input: AuthenticateUserInput): Promise<TokenPair> {
    const user = await this.userRepository.findByEmail(input.email);
 
    if (!user) {
      throw new InvalidCredentialsError();
    }
 
    const isPasswordValid = await this.passwordHasher.compare(input.password, user.passwordHash);
 
    if (!isPasswordValid) {
      throw new InvalidCredentialsError();
    }
 
    return this.tokenService.generateTokenPair(user.id, user.sessionVersion);
  }
}