25 lines
843 B
TypeScript
25 lines
843 B
TypeScript
import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';
|
|
import { ConfigService } from '@nestjs/config';
|
|
|
|
/**
|
|
* Guard for service-to-service internal API calls.
|
|
* Validates the X-Internal-Api-Key header.
|
|
*/
|
|
@Injectable()
|
|
export class InternalApiGuard implements CanActivate {
|
|
private readonly internalKey: string;
|
|
|
|
constructor(private readonly configService: ConfigService) {
|
|
this.internalKey = this.configService.get<string>('INTERNAL_API_KEY', 'changeme-internal-key');
|
|
}
|
|
|
|
canActivate(context: ExecutionContext): boolean {
|
|
const request = context.switchToHttp().getRequest();
|
|
const apiKey = request.headers['x-internal-api-key'];
|
|
if (!apiKey || apiKey !== this.internalKey) {
|
|
throw new UnauthorizedException('Invalid internal API key');
|
|
}
|
|
return true;
|
|
}
|
|
}
|