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: {