in between state for mcp implementation

This commit is contained in:
Joren de Graaf
2026-10-07 15:49:38 +02:00
parent 4f8c3272aa
commit c825cd474e
17 changed files with 735 additions and 5 deletions
+18 -5
View File
@@ -3,6 +3,7 @@ import hashlib
import hmac
import json
import secrets
from django.conf import settings
from decimal import Decimal
from functools import wraps
from uuid import UUID
@@ -80,7 +81,7 @@ def api_view(scope, methods):
if failure:
return failure
required_scope = scope.get(request.method) if isinstance(scope, dict) else scope
if required_scope not in token.scopes:
if required_scope and required_scope not in token.scopes:
return error('insufficient_scope', f'Missing {required_scope} scope.', 403)
request.api_token = token
request.api_user = token.user
@@ -197,13 +198,13 @@ def _inventory_data(item):
'added_at': item.added_at.isoformat(), 'updated_at': item.updated_at.isoformat()}
def _idempotent(request, payload, action):
def _idempotent(request, payload, action, digest_override=None):
key = request.headers.get('Idempotency-Key')
if not key:
return action()
if len(key) > 128 or not key.isascii() or any(ord(ch) < 33 or ord(ch) > 126 for ch in key):
return error('invalid_idempotency_key', 'Invalid Idempotency-Key.')
digest = hashlib.sha256(request.path.encode() + b'\0' + request.body).hexdigest()
digest = digest_override or hashlib.sha256(request.path.encode() + b'\0' + request.body).hexdigest()
with transaction.atomic():
# Lock the token row so concurrent retries serialize on databases with row locking.
PersonalAccessToken.objects.select_for_update().get(pk=request.api_token.pk)
@@ -233,6 +234,13 @@ def today(request):
return JsonResponse({'date': day.isoformat(), 'meals': meals, 'totals': totals, 'goals': goal_data})
@api_view(None, ('GET',))
def whoami(request):
subject = hashlib.sha256(f'{request.api_user.pk}:{settings.SECRET_KEY}'.encode()).hexdigest()[:24]
return JsonResponse({'subject': subject, 'scopes': request.api_token.scopes,
'expires_at': request.api_token.expires_at.isoformat() if request.api_token.expires_at else None})
@api_view('food:read', ('GET',))
def products(request):
query = request.GET.get('search', '').strip()[:100]
@@ -439,8 +447,13 @@ def attachment_create(request, identifier):
content_type=content_types[image_format], file_size=upload.size,
caption=request.POST.get('caption', '')[:255])
attachment.image.name = f'{secrets.token_hex(16)}.{extension}'
attachment.save()
return JsonResponse(_attachment_data(attachment), status=201)
def create():
attachment.save()
return JsonResponse(_attachment_data(attachment), status=201)
digest = hashlib.sha256(str(entry.api_id).encode() + b'\0' + upload.read() +
b'\0' + attachment.caption.encode()).hexdigest()
upload.seek(0)
return _idempotent(request, None, create, digest_override=digest)
@api_view('food:read', ('GET',))