From b9f18ccc5d474941eb744295758838a9511be762 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A7=A6=E7=A7=8B=E6=97=AD?= Date: Fri, 17 Feb 2023 15:56:35 +0800 Subject: [PATCH] refreshToken --- src/auth/auth.controller.ts | 6 ++++++ src/auth/auth.service.ts | 21 ++++++++++++++++++++- src/auth/dto/token.dto.ts | 6 ++++++ 3 files changed, 32 insertions(+), 1 deletion(-) diff --git a/src/auth/auth.controller.ts b/src/auth/auth.controller.ts index 289bbdb..8814626 100644 --- a/src/auth/auth.controller.ts +++ b/src/auth/auth.controller.ts @@ -3,6 +3,7 @@ import { AuthService } from './auth.service' import { CreateUserDto } from 'src/users/dto/create-user.dto' import { ApiTags } from '@nestjs/swagger' import { LoginInputDto } from './dto/login-input.dto' +import { RefreshToken } from './dto/token.dto' @ApiTags('Auth') @Controller('api/auth') @@ -18,4 +19,9 @@ export class AuthController { async login(@Body() user: LoginInputDto) { return this.authService.login(user.email, user.password) } + + @Post('token') + async refreshToken(@Body() payload: RefreshToken) { + return this.authService.refreshToken(payload.refreshToken) + } } diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.ts index 03bff76..9e4baea 100644 --- a/src/auth/auth.service.ts +++ b/src/auth/auth.service.ts @@ -1,4 +1,8 @@ -import { Injectable, BadRequestException } from '@nestjs/common' +import { + Injectable, + BadRequestException, + UnauthorizedException, +} from '@nestjs/common' import { PasswordService } from 'src/users/password.service' import { Token, TokenPayload } from './dto/token.dto' import { JwtService } from '@nestjs/jwt' @@ -34,6 +38,21 @@ export class AuthService { return this.generateTokens({ userId: user.id }) } + async refreshToken(token: string) { + try { + const { userId } = this.jwtService.verify(token, { + secret: this.configService.get( + 'JWT_REFRESH_SECRET', + 'JWT_REFRESH_SECRET', + ), + }) + return this.generateTokens({ userId }) + } catch (e) { + console.error(e) + throw new UnauthorizedException(e.message) + } + } + private generateTokens(payload: TokenPayload): Token { const accessToken = this.jwtService.sign(payload, { secret: this.configService.get( diff --git a/src/auth/dto/token.dto.ts b/src/auth/dto/token.dto.ts index d414886..c122cdc 100644 --- a/src/auth/dto/token.dto.ts +++ b/src/auth/dto/token.dto.ts @@ -1,5 +1,6 @@ import '@nestjs/mapped-types' import { ApiProperty } from '@nestjs/swagger' +import { IsString } from 'class-validator' export class Token { @ApiProperty() @@ -8,6 +9,11 @@ export class Token { refreshToken: string } +export class RefreshToken { + @IsString() + refreshToken: string +} + export class TokenPayload { userId: string }