import { hash , compare } from 'bcrypt' ; import { sign } from 'jsonwebtoken' ; import { SECRET_KEY } from '@config' ; import { CreateUserDto } from '@dtos/users.dto' ; import { HttpException } from '@exceptions/HttpException' ; import { DataStoredInToken , TokenData } from '@interfaces/auth.interface' ; import { User } from '@interfaces/users.interface' ; import userModel from '@models/users.model' ; import { isEmpty } from '@utils/util' ; class AuthService { public async signup ( userData ) { if ( isEmpty ( userData ) ) throw new HttpException ( 400 , "You're not userData" ) ; const findUser = await userModel . findOne ( { email : userData . email } ) ; if ( findUser ) throw new HttpException ( 409 , `You're email ${ userData . email } already exists` ) ; const hashedPassword = await hash ( userData . password , 10 ) ; const createUserData = await userModel . create ( { ... userData , password : hashedPassword } ) ; return createUserData ; } public async login ( userData ) { if ( isEmpty ( userData ) ) throw new HttpException ( 400 , "You're not userData" ) ; const findUser = await userModel . findOne ( { email : userData . email } ) ; if ( ! findUser ) throw new HttpException ( 409 , `You're email ${ userData . email } not found` ) ; const isPasswordMatching = await compare ( userData . password , findUser . password ) ; if ( ! isPasswordMatching ) throw new HttpException ( 409 , "You're password not matching" ) ; const tokenData = this . createToken ( findUser ) ; const cookie = this . createCookie ( tokenData ) ; return { cookie , findUser } ; } public async logout ( userData ) { if ( isEmpty ( userData ) ) throw new HttpException ( 400 , "You're not userData" ) ; const findUser = await userModel . findOne ( { email : userData . email , password : userData . password } ) ; if ( ! findUser ) throw new HttpException ( 409 , `You're email ${ userData . email } not found` ) ; return findUser ; } public createToken ( user ) { const dataStoredInToken = { _id : user . _id } ; const secretKey = SECRET_KEY ; const expiresIn = 60 * 60 ; return { expiresIn , token : sign ( dataStoredInToken , secretKey , { expiresIn } ) } ; } public createCookie ( tokenData ) { return `Authorization=${ tokenData . token }; HttpOnly; Max-Age=${ tokenData . expiresIn };` ; } } export default AuthService ;