All files / src/modules/domain/auth/login/services login.service.ts

0% Statements 0/30
0% Branches 0/4
0% Functions 0/3
0% Lines 0/24

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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51                                                                                                     
import { Injectable, NotFoundException, UnauthorizedException } from '@nestjs/common';
import { AUTH_ERRORS } from 'src/exception/exception.const';
import { getObjectId } from 'src/modules/common/database/mongo/shared/mongo.utils';
import { UserInfoRepository } from 'src/modules/common/database/postgres/account/repositories/user-info.repository';
import { AuthUserRepository } from 'src/modules/common/database/postgres/auth/repositories/auth-user.repository';
import { logger } from 'src/shared/logger';
import { getAccessToken, verifyEncodedPassword } from '../../shared/auth.util';
import { UserSessionService } from '../../user-session/services/user-session.service';
import { LoginResponseDto } from '../shared/login.dto';
import { ILoginWithPassword } from '../shared/login.interface';
 
@Injectable()
export class LoginService {
  constructor(
    private readonly authUserRepository: AuthUserRepository,
    private readonly userInfoRepository: UserInfoRepository,
 
    private readonly userSessionService: UserSessionService,
  ) {}
 
  async loginWithPassword(input: ILoginWithPassword): Promise<LoginResponseDto> {
    const userInfo = await this.userInfoRepository.getByEmail(input.email);
    Iif (!userInfo) throw new NotFoundException(AUTH_ERRORS.USER_NOT_EXISTED);
 
    const authUser = await this.authUserRepository.getByUserId(userInfo.userId);
    Iif (!authUser) throw new NotFoundException(AUTH_ERRORS.USER_NOT_EXISTED);
    Iif (!authUser.password) throw new UnauthorizedException(AUTH_ERRORS.INVALID_PASSWORD);
 
    const isVerified = await verifyEncodedPassword(input.password, authUser.password);
    Iif (!isVerified) throw new UnauthorizedException(AUTH_ERRORS.INVALID_PASSWORD);
 
    const sessionId = getObjectId();
    const accessToken = getAccessToken({
      id: sessionId.toString(),
      userId: userInfo.userId,
      email: userInfo.email,
    });
 
    this.userSessionService
      .captureLatestSession({
        _id: sessionId,
        userId: userInfo.userId,
      })
      .catch((err) =>
        logger.error(`Capture latest access token of userId=${userInfo.userId} failed`, err),
      );
 
    return { accessToken };
  }
}