import hmac from django.conf import settings from rest_framework.authentication import BaseAuthentication from rest_framework.exceptions import AuthenticationFailed from rest_framework.permissions import BasePermission class IntegrationTokenAuthentication(BaseAuthentication): """Authenticates 1C using a shared secret. The token is accepted either as ``X-Integration-Token`` or as a ``Bearer`` token in the ``Authorization`` header. """ def authenticate(self, request): token = request.headers.get("X-Integration-Token") if not token: header = request.headers.get("Authorization", "") if header.startswith("Bearer "): token = header[7:].strip() if not token: return None expected = getattr(settings, "INTEGRATION_API_TOKEN", "") if not expected or not hmac.compare_digest(token, expected): raise AuthenticationFailed("Invalid integration token") request.integration_authenticated = True return (None, None) def authenticate_header(self, request): return "Bearer" class IsIntegrationClient(BasePermission): """Allows access only to requests authenticated with the integration token.""" def has_permission(self, request, view): return bool(getattr(request, "integration_authenticated", False))