feat: add detailed request logging and error tracing to API key and JWT guards
Build and Push Multi-Platform Images / build-and-push (push) Successful in 29s
Build and Push Multi-Platform Images / build-and-push (push) Successful in 29s
This commit is contained in:
@@ -1,28 +1,31 @@
|
||||
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
|
||||
import { CanActivate, ExecutionContext, Injectable, Logger } from '@nestjs/common';
|
||||
import { JwtAuthGuard } from './jwt-auth.guard';
|
||||
import { ApiKeyGuard } from './api-key.guard';
|
||||
import { lastValueFrom, isObservable } from 'rxjs';
|
||||
|
||||
/**
|
||||
* Combined guard that accepts either a valid JWT Bearer token
|
||||
* or a valid API key (X-API-Key header / apiKey query param).
|
||||
* Tries JWT first, falls back to API key.
|
||||
*/
|
||||
@Injectable()
|
||||
export class JwtOrApiKeyGuard implements CanActivate {
|
||||
private readonly logger = new Logger(JwtOrApiKeyGuard.name);
|
||||
|
||||
constructor(
|
||||
private readonly jwtGuard: JwtAuthGuard,
|
||||
private readonly apiKeyGuard: ApiKeyGuard,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest();
|
||||
const tag = `[${req.method} ${req.url}]`;
|
||||
|
||||
// Try JWT first
|
||||
try {
|
||||
const result = this.jwtGuard.canActivate(context);
|
||||
const jwtOk = isObservable(result) ? await lastValueFrom(result) : await result;
|
||||
if (jwtOk) return true;
|
||||
} catch {
|
||||
// JWT failed, try API key
|
||||
if (jwtOk) {
|
||||
this.logger.debug(`${tag} authenticated via JWT`);
|
||||
return true;
|
||||
}
|
||||
} catch (err) {
|
||||
this.logger.debug(`${tag} JWT failed (${err.message}), trying API key…`);
|
||||
}
|
||||
|
||||
// Fall back to API key
|
||||
|
||||
Reference in New Issue
Block a user