import { HttpException , HttpStatus , Injectable , UnauthorizedException , } from '@nestjs/common' ; import { JwtService } from '@nestjs/jwt' ; import { UsersService } from '../users/users.service' ; import { IUsers } from '../users/interfaces/users.interface' ; import * as bcrypt from 'bcrypt' ; import { JwtPayload } from './interfaces/jwt.payload' ; import { LoginDto } from './dto/login.dto' ; @ Injectable ( ) export class LoginService { constructor ( private readonly usersService , private readonly jwtService ) { } private async validate ( loginDto ) { return await this . usersService . findByEmail ( loginDto . email ) ; } public async login ( loginDto ) { return this . validate ( loginDto ) . then ( ( userData ) => { if ( ! userData ) { throw new UnauthorizedException ( ) ; } const passwordIsValid = bcrypt . compareSync ( loginDto . password , userData . password ) ; if ( ! passwordIsValid == true ) { return { message : 'Authentication failed. Wrong password' , status : 400 , } ; } const payload = { name : userData . name , email : userData . email , id : userData . id , } ; const accessToken = this . jwtService . sign ( payload ) ; return { expiresIn : 3600 , accessToken : accessToken , user : payload , status : 200 , } ; } ) . catch ( ( err ) => { throw new HttpException ( err , HttpStatus . BAD_REQUEST ) ; } ) ; } public async validateUserByJwt ( payload ) { const user = await this . usersService . findByEmail ( payload . email ) ; if ( ! user ) { throw new UnauthorizedException ( ) ; } return this . createJwtPayload ( user ) ; } protected createJwtPayload ( user ) { const data = { email : user . email , } ; const jwt = this . jwtService . sign ( data ) ; return { expiresIn : 3600 , token : jwt , } ; } }