From b8841e52b777f767417d4db07ff95d381f905a63 Mon Sep 17 00:00:00 2001 From: vchikalkin Date: Sun, 14 Jul 2024 16:23:37 +0300 Subject: [PATCH] api: add /check-auth method for account mode --- apps/api/src/account/account.controller.ts | 14 ++++++++++++++ apps/api/src/account/account.service.ts | 13 +++++++++++-- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/apps/api/src/account/account.controller.ts b/apps/api/src/account/account.controller.ts index ce6a81c..0ce83b4 100644 --- a/apps/api/src/account/account.controller.ts +++ b/apps/api/src/account/account.controller.ts @@ -158,4 +158,18 @@ export class AccountController implements BaseAuthController { return reply.send(account); } + + @Get('/check-auth') + @ApiResponse({ + status: HttpStatus.OK, + }) + async checkAuth(@AuthToken() token: string, @Res() reply: FastifyReply) { + const { authId } = await this.accountService.parseToken(token, { ignoreExpiration: true }); + + if (authId) return reply.status(HttpStatus.UNAUTHORIZED).send(); + + const user = await this.accountService.getUser(token, { ignoreExpiration: true }); + + return reply.status(200).send(user); + } } diff --git a/apps/api/src/account/account.service.ts b/apps/api/src/account/account.service.ts index 39356e6..1784e3c 100644 --- a/apps/api/src/account/account.service.ts +++ b/apps/api/src/account/account.service.ts @@ -2,6 +2,7 @@ import type { CreateAccountDto } from './dto/create-account.dto'; import type { ResetPasswordDto } from './dto/reset-password.dto'; import type { UpdateAccountDto } from './dto/update-account.dto'; import { BadRequestException, Injectable, UnauthorizedException } from '@nestjs/common'; +import type { JwtVerifyOptions } from '@nestjs/jwt'; import { JwtService } from '@nestjs/jwt'; import { InjectModel } from '@nestjs/mongoose'; import * as bcrypt from 'bcrypt'; @@ -112,9 +113,9 @@ export class AccountService { } } - public async getUser(token: string) { + public async getUser(token: string, options?: JwtVerifyOptions) { try { - const { username } = this.jwtService.verify(token) as TokenPayload; + const { username } = this.jwtService.verify(token, options); return this.accountModel.findOne({ username, @@ -123,4 +124,12 @@ export class AccountService { throw new UnauthorizedException('Invalid token'); } } + + public async parseToken(token: string, options?: JwtVerifyOptions) { + try { + return this.jwtService.verify(token, options); + } catch (error) { + throw new UnauthorizedException(error); + } + } }