private-api-key.guard.ts
570 Bytes
import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';
@Injectable()
export class PrivateApiKeyGuard implements CanActivate {
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const apiKey = request.headers['x-api-key'];
if (!apiKey) {
throw new UnauthorizedException('No API key provided');
}
if (apiKey !== process.env.PRIVATE_API_KEY) {
throw new UnauthorizedException('Invalid API key');
}
return true;
}
}