import { Injectable , UnauthorizedException , NotAcceptableException , Inject } from "@nestjs/common" ; import { JwtService } from "@nestjs/jwt" ; import { JwtPayload , AccessToken , IUserService } from "./interfaces" ; import { LoginReq , LoginRes } from "./dto/login.dto" ; import { RegisterReq } from "./dto/Register.dto" ; @ Injectable ( ) export class AuthService { constructor ( private readonly jwtService , @ Inject ( "IUserService" ) private readonly userService ) { } async login ( payload ) { const user = await this . userService . login ( payload . username , payload . password ) ; if ( user ) { const token = await this . createToken ( user ) ; const { username , avatar , email , name , mobile , isAdmin , isApproved , expired , roles } = user ; return { token , username , avatar , email , name , mobile , isAdmin , isApproved , expired , roles } ; } else { throw new UnauthorizedException ( ) ; } } async logout ( ) { return true ; } async createToken ( payload ) { const accessToken = this . jwtService . sign ( { account : payload . username } ) ; return { expiresIn : 3600 , accessToken } ; } async register ( payload ) { const validate = await this . userService . verifyCode ( payload . veryCode , payload . mobile ) ; if ( ! validate ) { throw new NotAcceptableException ( "verycode failure" ) ; } const user = await this . userService . register ( payload ) . catch ( ( error ) => { throw new NotAcceptableException ( "register failure might duplicate with username, email or mobile." ) ; } ) ; return await this . createToken ( user ) ; } async captcha ( mobile ) { const code = await this . userService . sendVeryCode ( mobile ) ; return { ok : true } ; } async validateUser ( payload ) { return this . userService . findOne ( { username : payload . account } ) ; } }