import os from django.contrib.auth.models import AnonymousUser from rest_framework.authentication import BaseAuthentication from rest_framework.exceptions import AuthenticationFailed from rest_framework.permissions import BasePermission class TokenEnvAuthentication(BaseAuthentication): def authenticate(self, request): token = os.environ.get("API_TOKEN", "") if not token: raise AuthenticationFailed("API token not configured.") auth_header = request.headers.get("Authorization", "") if not auth_header.startswith("Bearer "): return None provided_token = auth_header[7:] if provided_token != token: raise AuthenticationFailed("Invalid token.") return (AnonymousUser(), token) class HasValidToken(BasePermission): def has_permission(self, request, view): return request.auth is not None