""" External API key authentication for DRF. """ import logging from rest_framework import authentication, exceptions logger = logging.getLogger("apps.integrations") class ExternalAPIKeyAuthentication(authentication.BaseAuthentication): """ Authenticate requests using an API key passed via X-API-Key header. Sets `request.api_key` on successful authentication for downstream use. """ HEADER_NAME = "HTTP_X_API_KEY" def authenticate(self, request): raw_key = request.META.get(self.HEADER_NAME) if not raw_key: raise exceptions.AuthenticationFailed("API key required. Provide X-API-Key header.") from .models import ExternalAPIKey # Look up by prefix to avoid scanning all keys prefix = raw_key[:8] candidates = ExternalAPIKey.objects.filter( key_prefix=prefix, is_active=True, ) for api_key in candidates: if api_key.verify(raw_key): # Rate limit check # (simple per-key check; could be enhanced with cache) api_key.record_usage() request.api_key = api_key return (None, api_key) raise exceptions.AuthenticationFailed("Invalid or expired API key.") def authenticate_header(self, request): return "X-API-Key"