Files
dsc-api/src/modules/auth/guards/api-key.guard.ts
T
2026-04-06 12:28:38 +03:30

34 lines
1.2 KiB
TypeScript

import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { FastifyRequest } from "fastify";
import { AuthMessage } from "../../../common/enums/message.enum";
@Injectable()
export class ApiKeyGuard implements CanActivate {
constructor(private configService: ConfigService) {}
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest<FastifyRequest>();
const apiKey = request.headers["x-api-key"] as string;
if (!apiKey) throw new UnauthorizedException(AuthMessage.UNAUTHORIZED_ACCESS);
// Get allowed API keys from environment (comma-separated)
const allowedApiKeys = this.configService.getOrThrow<string>("EXTERNAL_API_KEYS");
const validApiKeys = allowedApiKeys.split(",").filter((key) => key.trim().length > 0);
if (validApiKeys.length === 0) throw new UnauthorizedException(AuthMessage.UNAUTHORIZED_ACCESS);
const isValidApiKey = validApiKeys.includes(apiKey);
if (!isValidApiKey) throw new UnauthorizedException(AuthMessage.UNAUTHORIZED_ACCESS);
console.log("true");
return true;
}
}