File

src/modules/auth/services/auth.service.ts

Index

Properties
Methods

Constructor

constructor(_jwtService: JwtService, _configService: ConfigService, _userAuthService: UserAuthService)
Parameters :
Name Type Optional
_jwtService JwtService No
_configService ConfigService No
_userAuthService UserAuthService No

Methods

Public Async createToken
createToken(user: UserEntity)
Parameters :
Name Type Optional
user UserEntity No
Static getAuthUser
getAuthUser()
Returns : UserEntity
Static setAuthUser
setAuthUser(user: UserEntity)
Parameters :
Name Type Optional
user UserEntity No
Returns : void
Public Async validateUser
validateUser(userLoginDto: UserLoginDto)
Parameters :
Name Type Optional
userLoginDto UserLoginDto No

Properties

Private Static _authUserKey
Type : string
Default value : 'user_key'
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import {
  UserNotFoundException,
  UserPasswordNotValidException,
} from 'exceptions';
import { TokenPayloadDto, UserLoginDto } from 'modules/auth/dtos';
import { UserEntity } from 'modules/user/entities';
import { UserAuthService } from 'modules/user/services';
import { ContextService } from 'providers';
import { UtilsService } from 'utils/services';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class AuthService {
  private static _authUserKey = 'user_key';

  constructor(
    private readonly _jwtService: JwtService,
    private readonly _configService: ConfigService,
    private readonly _userAuthService: UserAuthService,
  ) {}

  public async createToken(user: UserEntity): Promise<TokenPayloadDto> {
    const {
      uuid,
      userAuth: { role },
    } = user;

    return new TokenPayloadDto({
      expiresIn: this._configService.get('JWT_EXPIRATION_TIME'),
      accessToken: await this._jwtService.signAsync({ uuid, role }),
    });
  }

  public async validateUser(userLoginDto: UserLoginDto): Promise<UserEntity> {
    const { email, password } = userLoginDto;
    let user = await this._userAuthService.findUserAuth({ email });

    if (!user) {
      throw new UserNotFoundException();
    }

    const isPasswordValid = await UtilsService.validateHash(
      password,
      user.userAuth.password,
    );

    user = await this._userAuthService.updateLastLoggedDate(
      user,
      isPasswordValid,
    );

    if (!isPasswordValid) {
      throw new UserPasswordNotValidException();
    }

    return user;
  }

  public static setAuthUser(user: UserEntity): void {
    ContextService.set(AuthService._authUserKey, user);
  }

  public static getAuthUser(): UserEntity {
    return ContextService.get(AuthService._authUserKey);
  }
}

result-matching ""

    No results matching ""