import { CanActivate, ExecutionContext, Injectable, } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { Request } from 'express'; import { API_KEY_HEADER } from '../../common/constants/app.constants'; import { AppException } from '../../common/exceptions/app-exception'; /** * API key authentication for inquiry endpoints. * Expects x-api-key header matching configured API_KEY. */ @Injectable() export class ApiKeyGuard implements CanActivate { constructor(private readonly configService: ConfigService) {} canActivate(context: ExecutionContext): boolean { const request = context.switchToHttp().getRequest(); const apiKey = request.headers[API_KEY_HEADER] as string | undefined; const expected = this.configService.get('auth.apiKey'); if (!expected) { throw new AppException('API_KEY_NOT_CONFIGURED'); } if (!apiKey || apiKey !== expected) { throw new AppException('INVALID_API_KEY'); } return true; } }