From 388f2869fde784720d9f971cc068d13ef094d343 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A7=A6=E7=A7=8B=E6=97=AD?= Date: Tue, 28 Feb 2023 00:52:48 +0800 Subject: [PATCH] logout --- src/users/me.controller.ts | 20 +++++++++++++++----- src/users/me.service.ts | 12 ++++++++---- 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/src/users/me.controller.ts b/src/users/me.controller.ts index bc6d8d2..6f47d49 100644 --- a/src/users/me.controller.ts +++ b/src/users/me.controller.ts @@ -9,12 +9,16 @@ import { UseInterceptors, BadRequestException, Query, - UnauthorizedException, } from '@nestjs/common' import type { Response } from 'express' import { Cookies } from 'src/common/decorators/cookies.decorator' import { MeService } from './me.service' -import { ApiTags, ApiOperation, ApiUnauthorizedResponse } from '@nestjs/swagger' +import { + ApiTags, + ApiOperation, + ApiUnauthorizedResponse, + ApiCookieAuth, +} from '@nestjs/swagger' import { User } from 'src/common/decorators/user.decorator' import { NeedAuth } from 'src/common/decorators/need-auth.decorator' import { PasswordInterceptor } from 'src/common/interceptors/password.interceptor' @@ -43,6 +47,14 @@ export class MeController { }) } + @Delete('token') + @ApiOperation({ summary: '退出登录' }) + @NeedAuth() + async logout(@Res({ passthrough: true }) res: Response) { + res.clearCookie('refreshToken') + return + } + @Patch() @ApiOperation({ summary: '修改用户信息(用户名等)' }) @UseInterceptors(PasswordInterceptor) @@ -95,14 +107,12 @@ export class MeController { @Put('token') @ApiOperation({ summary: '刷新token' }) + @ApiCookieAuth() @ApiUnauthorizedResponse({ description: 'Unauthorized' }) async updateAccessToken( @Res({ passthrough: true }) res: Response, @Cookies('refreshToken') refreshToken: string, ) { - if (!refreshToken) { - throw new UnauthorizedException('no refresh token') - } try { return this.meService.updateAccessToken(refreshToken) } catch (err) { diff --git a/src/users/me.service.ts b/src/users/me.service.ts index ec4812c..a7b318f 100644 --- a/src/users/me.service.ts +++ b/src/users/me.service.ts @@ -66,7 +66,10 @@ export class MeService { }) } - async updateAccessToken(refreshToken: string) { + async updateAccessToken(refreshToken: string | undefined) { + if (!refreshToken) { + throw new UnauthorizedException('没有令牌,请重新登录') + } const { userId, iat } = this.jwtService.verify(refreshToken, { secret: this.secureConfig.jwt_refresh_secret, }) @@ -75,15 +78,16 @@ export class MeService { }) // TODO:不使用updatedAt,而是自定义的一个refreshTime字段 if (iat * 1000 < user.updatedAt.getTime()) { - throw new UnauthorizedException('token失效,请重新登录') + throw new UnauthorizedException('令牌失效,请重新登录') } - return this.jwtService.sign( + const accessToken = this.jwtService.sign( { userId }, { secret: this.secureConfig.jwt_access_secret, - expiresIn: this.secureConfig.refreshIn, + expiresIn: this.secureConfig.expiresIn, }, ) + return accessToken } private async checkPassword(pwd: string, hashPwd: string) {