logout
This commit is contained in:
parent
699897b071
commit
388f2869fd
@ -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) {
|
||||
|
@ -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<TokenContnet>(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) {
|
||||
|
Loading…
Reference in New Issue
Block a user