From 3577925932193c210a598bd63eafa9e41f8a1bf4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi?= Date: Thu, 2 Jan 2025 18:33:53 +0100 Subject: [PATCH] refactor: Simplify jwksRsa import and enhance username extraction logic in JwtAuthGuard --- src/modules/auth/auth.service.ts | 4 ++-- src/modules/auth/guards/jwt.guard.ts | 6 ++++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/modules/auth/auth.service.ts b/src/modules/auth/auth.service.ts index 9753d40..88f68a1 100644 --- a/src/modules/auth/auth.service.ts +++ b/src/modules/auth/auth.service.ts @@ -1,11 +1,11 @@ import { Injectable, UnauthorizedException } from "@nestjs/common"; import { ConfigService } from "@nestjs/config"; import * as jwt from "jsonwebtoken"; -import JwksRsa, * as jwksRsa from "jwks-rsa"; +import * as jwksRsa from "jwks-rsa"; @Injectable() export class AuthService { - private jwksClient: JwksRsa.JwksClient; + private jwksClient: jwksRsa.JwksClient; constructor(configService: ConfigService) { this.jwksClient = jwksRsa({ diff --git a/src/modules/auth/guards/jwt.guard.ts b/src/modules/auth/guards/jwt.guard.ts index 2d3444a..5a17fc3 100644 --- a/src/modules/auth/guards/jwt.guard.ts +++ b/src/modules/auth/guards/jwt.guard.ts @@ -14,7 +14,7 @@ export class JwtAuthGuard implements CanActivate { private readonly userService: UserService, private readonly authService: AuthService, private readonly configService: ConfigService, - ) {} + ) { } async canActivate(context: ExecutionContext): Promise { const request = context.switchToHttp().getRequest(); @@ -30,7 +30,9 @@ export class JwtAuthGuard implements CanActivate { let user = await this.userService.findOrCreate({ id: jwtPayload.sub.toString(), username: - jwtPayload[this.configService.get("auth.usernameField")], + jwtPayload[this.configService.get("auth.usernameField")] || + jwtPayload["preferred_username"] || + jwtPayload["email"], }); request.user = user;