forked from Shared/esg
initial commit
This commit is contained in:
34
src/auth/guards/api-key.guard.ts
Normal file
34
src/auth/guards/api-key.guard.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { Request } from 'express';
|
||||
import { API_KEY_HEADER } from '../../common/constants/app.constants';
|
||||
|
||||
/**
|
||||
* 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<Request>();
|
||||
const apiKey = request.headers[API_KEY_HEADER] as string | undefined;
|
||||
const expected = this.configService.get<string>('auth.apiKey');
|
||||
|
||||
if (!expected) {
|
||||
throw new UnauthorizedException('API key authentication is not configured');
|
||||
}
|
||||
|
||||
if (!apiKey || apiKey !== expected) {
|
||||
throw new UnauthorizedException('Invalid or missing API key');
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user