|
|
|
|
|
import hashlib |
|
|
import hmac |
|
|
from django.http import JsonResponse |
|
|
from ai_api.models import APIClient |
|
|
|
|
|
class HMACAuthMiddleware: |
|
|
def __init__(self, get_response): |
|
|
self.get_response = get_response |
|
|
|
|
|
def __call__(self, request): |
|
|
|
|
|
|
|
|
if not request.path.startswith('/api/'): |
|
|
return self.get_response(request) |
|
|
|
|
|
client_id = request.headers.get('X-Client-ID') |
|
|
signature = request.headers.get('X-Signature') |
|
|
|
|
|
if not client_id or not signature: |
|
|
return JsonResponse({'error': 'Missing credentials'}, status=401) |
|
|
|
|
|
from ai_api.models import APIClient |
|
|
try: |
|
|
client = APIClient.objects.get(client_id=client_id) |
|
|
except APIClient.DoesNotExist: |
|
|
return JsonResponse({'error': 'Invalid client ID'}, status=401) |
|
|
|
|
|
expected_signature = hmac.new( |
|
|
client.secret_key.encode(), |
|
|
request.body, |
|
|
hashlib.sha256 |
|
|
).hexdigest() |
|
|
|
|
|
if not hmac.compare_digest(expected_signature, signature): |
|
|
return JsonResponse({'error': 'Invalid signature'}, status=401) |
|
|
|
|
|
request.api_client = client |
|
|
return self.get_response(request) |
|
|
|
|
|
|