refactor: Simplify jwksRsa import and enhance username extraction logic in JwtAuthGuard

This commit is contained in:
Rémi 2025-01-02 18:33:53 +01:00
parent 7b43387a0c
commit 3577925932
2 changed files with 6 additions and 4 deletions

View File

@ -1,11 +1,11 @@
import { Injectable, UnauthorizedException } from "@nestjs/common"; import { Injectable, UnauthorizedException } from "@nestjs/common";
import { ConfigService } from "@nestjs/config"; import { ConfigService } from "@nestjs/config";
import * as jwt from "jsonwebtoken"; import * as jwt from "jsonwebtoken";
import JwksRsa, * as jwksRsa from "jwks-rsa"; import * as jwksRsa from "jwks-rsa";
@Injectable() @Injectable()
export class AuthService { export class AuthService {
private jwksClient: JwksRsa.JwksClient; private jwksClient: jwksRsa.JwksClient;
constructor(configService: ConfigService) { constructor(configService: ConfigService) {
this.jwksClient = jwksRsa({ this.jwksClient = jwksRsa({

View File

@ -14,7 +14,7 @@ export class JwtAuthGuard implements CanActivate {
private readonly userService: UserService, private readonly userService: UserService,
private readonly authService: AuthService, private readonly authService: AuthService,
private readonly configService: ConfigService, private readonly configService: ConfigService,
) {} ) { }
async canActivate(context: ExecutionContext): Promise<boolean> { async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest(); const request = context.switchToHttp().getRequest();
@ -30,7 +30,9 @@ export class JwtAuthGuard implements CanActivate {
let user = await this.userService.findOrCreate({ let user = await this.userService.findOrCreate({
id: jwtPayload.sub.toString(), id: jwtPayload.sub.toString(),
username: username:
jwtPayload[this.configService.get("auth.usernameField")], jwtPayload[this.configService.get("auth.usernameField")] ||
jwtPayload["preferred_username"] ||
jwtPayload["email"],
}); });
request.user = user; request.user = user;