From 28e42b22484d3418adb78cec23db0fd071fe5342 Mon Sep 17 00:00:00 2001 From: M1000fr Date: Wed, 11 Dec 2024 18:51:48 +0100 Subject: [PATCH] feat: Add error handling for invalid token in JwtAuthGuard --- src/modules/auth/guards/jwt.guard.ts | 10 +++++++--- src/modules/user/user.service.ts | 25 +++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/src/modules/auth/guards/jwt.guard.ts b/src/modules/auth/guards/jwt.guard.ts index a31b8fe..07da1aa 100644 --- a/src/modules/auth/guards/jwt.guard.ts +++ b/src/modules/auth/guards/jwt.guard.ts @@ -47,9 +47,13 @@ export class JwtAuthGuard implements CanActivate { algorithms: ["RS256"], }); - let user = await this.userService.findByProviderId( - verifiedToken.sub.toString(), - ); + if (typeof verifiedToken == "string") + throw new UnauthorizedException("Invalid token"); + + let user = await this.userService.findOrCreateByProviderId({ + providerId: verifiedToken.sub.toString(), + username: verifiedToken.preferred_username, + }); request.user = user; diff --git a/src/modules/user/user.service.ts b/src/modules/user/user.service.ts index 1531787..f13d968 100644 --- a/src/modules/user/user.service.ts +++ b/src/modules/user/user.service.ts @@ -45,6 +45,31 @@ export class UserService { }); } + async findOrCreateByProviderId({ + providerId, + username, + }: { + providerId: string; + username: string; + }) { + let user = await this.prisma.user.findUnique({ + where: { + providerId, + username, + }, + }); + + if (!user) + user = await this.prisma.user.create({ + data: { + providerId, + username, + }, + }); + + return user; + } + async create(createUserDto: CreateUserDTO) { return await this.prisma.user.create({ data: {