nest-project/src/users/token.service.ts

51 lines
1.5 KiB
TypeScript

import { Inject, Injectable, ForbiddenException } from '@nestjs/common'
import * as bcrypt from 'bcrypt'
import { PrismaService } from 'nestjs-prisma'
import { Token, TokenPayload } from './dto/token.dto'
import { JwtService } from '@nestjs/jwt'
import { securityConfig, SecurityConfig } from 'src/common/configs'
@Injectable()
export class TokenService {
constructor(
private jwtService: JwtService,
private prismaService: PrismaService,
@Inject(securityConfig.KEY)
private secureConfig: SecurityConfig,
) {}
async login(email: string, password: string) {
const user = await this.prismaService.user.findUniqueOrThrow({
where: { email },
})
const passwordValid = await bcrypt.compare(password, user.password)
if (!passwordValid) {
throw new ForbiddenException('Invalid password')
}
return this.generateTokens({ userId: user.id })
}
async refreshToken(token: string) {
const { userId } = this.jwtService.verify<TokenPayload>(token, {
secret: this.secureConfig.jwt_refresh_secret,
})
return this.generateTokens({ userId })
}
generateTokens(payload: TokenPayload): Token {
const accessToken = this.jwtService.sign(payload, {
secret: this.secureConfig.jwt_access_secret,
expiresIn: this.secureConfig.expiresIn,
})
const refreshToken = this.jwtService.sign(payload, {
secret: this.secureConfig.jwt_refresh_secret,
expiresIn: this.secureConfig.refreshIn,
})
return { accessToken, refreshToken }
}
}