update refreshToken

This commit is contained in:
秦秋旭 2023-02-22 16:41:46 +08:00
parent 5bc8a7e072
commit 167d2e096a
3 changed files with 28 additions and 6 deletions

View File

@ -3,7 +3,7 @@ import { registerAs, ConfigType } from '@nestjs/config'
export const securityConfig = registerAs('security', () => ({
jwt_access_secret: process.env.JWT_ACCESS_SECRET || 'JWT_ACCESS_SECRET',
jwt_refresh_secret: process.env.JWT_REFRESH_SECRET || 'JWT_REFRESH_SECRET',
expiresIn: process.env.expiresIn || '30m',
expiresIn: process.env.expiresIn || '15m',
refreshIn: process.env.refreshIn || '7d',
bcryptSaltOrRound: Number(process.env.bcryptSaltOrRound) || 10,
}))

View File

@ -17,3 +17,10 @@ export class TokenRefreshPayload {
export class TokenPayload {
userId: string
}
export class TokenContnet extends TokenPayload {
/** Issued at */
iat: number
/** Expiration time */
exp: number
}

View File

@ -1,7 +1,7 @@
import { Inject, Injectable, ForbiddenException } from '@nestjs/common'
import { Inject, Injectable, UnauthorizedException } from '@nestjs/common'
import * as bcrypt from 'bcrypt'
import { PrismaService } from 'nestjs-prisma'
import { Token, TokenPayload } from './dto/token.dto'
import { Token, TokenPayload, TokenContnet } from './dto/token.dto'
import { JwtService } from '@nestjs/jwt'
import { securityConfig, SecurityConfig } from 'src/common/configs'
@ -22,17 +22,32 @@ export class TokenService {
const passwordValid = await bcrypt.compare(password, user.password)
if (!passwordValid) {
throw new ForbiddenException('Invalid password')
throw new UnauthorizedException('Invalid password')
}
return this.generateTokens({ userId: user.id })
}
async refreshToken(token: string) {
const { userId } = this.jwtService.verify<TokenPayload>(token, {
const { userId, iat } = this.jwtService.verify<TokenContnet>(token, {
secret: this.secureConfig.jwt_refresh_secret,
})
return this.generateTokens({ userId })
const user = await this.prismaService.user.findUniqueOrThrow({
where: { id: userId },
})
if (iat * 1000 < user.updatedAt.getTime()) {
throw new UnauthorizedException('token失效请重新登录')
}
return {
refreshToken: token,
accessToken: this.jwtService.sign(
{ userId },
{
secret: this.secureConfig.jwt_refresh_secret,
expiresIn: this.secureConfig.refreshIn,
},
),
}
}
generateTokens(payload: TokenPayload): Token {