import { UsersRepository } from '@modules/admin/access/users/users.repository' ; import { Injectable , Logger } from '@nestjs/common' ; import { UserStatus } from '@admin/access/users/user-status.enum' ; import { InjectRepository } from '@nestjs/typeorm' ; import { ConfigService } from '@nestjs/config' ; import { JwtService } from '@nestjs/jwt' ; import { RefreshTokenExpiredException , AccessTokenExpiredException , InvalidTokenException , } from '@common/http/exceptions' ; import { ValidateTokenResponseDto , JwtPayload , TokenDto } from '../dtos' ; import { TokenError , TokenType } from '../enums' ; @ Injectable ( ) export class TokenService { constructor ( @ InjectRepository ( UsersRepository ) private usersRepository , private jwtService , private configService ) { } param JwtPayload { JwtPayload } returns public generateAuthToken ( payload ) { const accessTokenExpires = this . configService . get ( 'ACCESS_TOKEN_EXPIRES_IN' ) ; const refreshTokenExpires = this . configService . get ( 'REFRESH_TOKEN_EXPIRES_IN' ) ; const tokenType = this . configService . get ( 'TOKEN_TYPE' ) ; const accessToken = this . generateToken ( payload , accessTokenExpires ) ; const refreshToken = this . generateToken ( payload , refreshTokenExpires ) ; return { tokenType , accessToken , accessTokenExpires , refreshToken , } ; } param payload { JwtPayload } returns public generateRefreshToken ( refreshToken ) { const { id , username } = this . verifyToken ( refreshToken , TokenType . RefreshToken ) ; return this . generateAuthToken ( { id , username } ) ; } param token param type { TokenType } returns public verifyToken ( token , type ) { try { return this . jwtService . verify ( token ) ; } catch ( { name } ) { if ( name == TokenError . TokenExpiredError && type == TokenType . AccessToken ) { throw new AccessTokenExpiredException ( ) ; } if ( name == TokenError . TokenExpiredError && type == TokenType . RefreshToken ) { throw new RefreshTokenExpiredException ( ) ; } throw new InvalidTokenException ( ) ; } } param token { string } returns public async validateToken ( token ) { try { const { id } = this . jwtService . verify ( token ) ; const user = await this . usersRepository . findOne ( id ) ; if ( ! user || user . status == UserStatus . Blocked || user . status == UserStatus . Inactive ) { return { valid : false } ; } return { valid : ! ! id } ; } catch ( error ) { Logger . error ( 'Validation token error' , error ) ; return { valid : false } ; } } private param payload { JwtPayload } param expiresIn { string } returns private generateToken ( payload , expiresIn ) { const token = this . jwtService . sign ( payload , { expiresIn } ) ; return token ; } }