mirror of
https://github.com/deunix-educ/PyQuest.git
synced 2026-11-25 08:19:44 +01:00
Add optional Django sync backend skeleton with token-based API
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
initial = True
|
||||
|
||||
dependencies = []
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name="SyncProfile",
|
||||
fields=[
|
||||
("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
|
||||
("token_hash", models.CharField(max_length=64, unique=True)),
|
||||
("payload", models.JSONField()),
|
||||
("updated_at", models.DateTimeField(auto_now=True)),
|
||||
],
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,12 @@
|
||||
from django.db import models
|
||||
|
||||
|
||||
class SyncProfile(models.Model):
|
||||
"""Progression synchronisée d'un apprenant, identifiée par un jeton secret (jamais stocké en clair)."""
|
||||
|
||||
token_hash = models.CharField(max_length=64, unique=True)
|
||||
payload = models.JSONField()
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"SyncProfile({self.token_hash[:8]}…)"
|
||||
@@ -0,0 +1,48 @@
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from django.test import TestCase
|
||||
|
||||
# Réponse du client de test Django (HttpResponse enrichi) : type exact non exposé par les stubs.
|
||||
_Response = Any
|
||||
|
||||
TOKEN = "a" * 40
|
||||
URL = "/api/sync/"
|
||||
PAYLOAD = {"version": 1, "completedLevels": {}, "badges": {}, "streak": {"current": 0, "best": 0, "lastDay": None}}
|
||||
|
||||
|
||||
def bearer(token: str) -> dict[str, str]:
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
|
||||
|
||||
class SyncApiTest(TestCase):
|
||||
def put(self, body: object, token: str = TOKEN) -> _Response:
|
||||
return self.client.put(URL, data=json.dumps(body), content_type="application/json", headers=bearer(token))
|
||||
|
||||
def test_requires_token(self) -> None:
|
||||
self.assertEqual(self.client.get(URL).status_code, 401)
|
||||
self.assertEqual(self.client.get(URL, headers=bearer("short")).status_code, 401)
|
||||
|
||||
def test_unknown_token_is_404(self) -> None:
|
||||
self.assertEqual(self.client.get(URL, headers=bearer(TOKEN)).status_code, 404)
|
||||
|
||||
def test_roundtrip_and_overwrite(self) -> None:
|
||||
self.assertEqual(self.put({"payload": PAYLOAD}).status_code, 200)
|
||||
newer = {**PAYLOAD, "badges": {"first_level": "2026-10-14T10:00:00Z"}}
|
||||
self.assertEqual(self.put({"payload": newer}).status_code, 200)
|
||||
response = self.client.get(URL, headers=bearer(TOKEN))
|
||||
self.assertEqual(response.json()["payload"], newer)
|
||||
|
||||
def test_tokens_are_isolated(self) -> None:
|
||||
self.put({"payload": PAYLOAD})
|
||||
self.assertEqual(self.client.get(URL, headers=bearer("b" * 40)).status_code, 404)
|
||||
|
||||
def test_rejects_bad_payloads(self) -> None:
|
||||
self.assertEqual(self.put({"payload": {"no": "version"}}).status_code, 400)
|
||||
self.assertEqual(self.put([1, 2]).status_code, 400)
|
||||
response = self.client.put(URL, data="nope", content_type="application/json", headers=bearer(TOKEN))
|
||||
self.assertEqual(response.status_code, 400)
|
||||
|
||||
def test_rejects_oversized_payload(self) -> None:
|
||||
big = {"payload": {"version": 1, "blob": "x" * (300 * 1024)}}
|
||||
self.assertEqual(self.put(big).status_code, 400)
|
||||
@@ -0,0 +1,7 @@
|
||||
from django.urls import path
|
||||
|
||||
from . import views
|
||||
|
||||
urlpatterns = [
|
||||
path("", views.progress, name="progress"),
|
||||
]
|
||||
@@ -0,0 +1,69 @@
|
||||
"""API de synchronisation : GET/PUT de la progression, authentifiée par un jeton Bearer.
|
||||
|
||||
Le serveur ne fait que stocker le dernier JSON exporté par `ProgressStore` ; la fusion entre
|
||||
appareils reste côté client (ProgressStore.import, mode `merge`).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from django.conf import settings
|
||||
from django.http import HttpRequest, JsonResponse
|
||||
from django.utils.translation import gettext as _
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
from django.views.decorators.http import require_http_methods
|
||||
|
||||
from .models import SyncProfile
|
||||
|
||||
# Jeton généré par le client (32 à 128 caractères URL-safe) : ~190 bits d'entropie au minimum.
|
||||
TOKEN_PATTERN = re.compile(r"^[A-Za-z0-9_-]{32,128}$")
|
||||
|
||||
|
||||
def _error(message: str, status: int) -> JsonResponse:
|
||||
return JsonResponse({"error": message}, status=status)
|
||||
|
||||
|
||||
def _token_hash(request: HttpRequest) -> str | None:
|
||||
header = request.headers.get("Authorization", "")
|
||||
scheme, _sep, token = header.partition(" ")
|
||||
if scheme.lower() != "bearer" or not TOKEN_PATTERN.match(token):
|
||||
return None
|
||||
return hashlib.sha256(token.encode("ascii")).hexdigest()
|
||||
|
||||
|
||||
def _parse_payload(request: HttpRequest) -> tuple[dict[str, Any] | None, str | None]:
|
||||
if len(request.body) > settings.SYNC_MAX_PAYLOAD_BYTES:
|
||||
return None, _("Payload too large.")
|
||||
try:
|
||||
data = json.loads(request.body)
|
||||
except json.JSONDecodeError:
|
||||
return None, _("Invalid JSON.")
|
||||
payload = data.get("payload") if isinstance(data, dict) else None
|
||||
if not isinstance(payload, dict) or not isinstance(payload.get("version"), int):
|
||||
return None, _("Invalid progress payload.")
|
||||
return payload, None
|
||||
|
||||
|
||||
# Pas de cookie ni de session : l'authentification est le jeton Bearer, donc pas de CSRF.
|
||||
@csrf_exempt
|
||||
@require_http_methods(["GET", "PUT"])
|
||||
def progress(request: HttpRequest) -> JsonResponse:
|
||||
token_hash = _token_hash(request)
|
||||
if token_hash is None:
|
||||
return _error(_("Missing or malformed token."), 401)
|
||||
|
||||
if request.method == "GET":
|
||||
profile = SyncProfile.objects.filter(token_hash=token_hash).first()
|
||||
if profile is None:
|
||||
return _error(_("No progress stored for this token."), 404)
|
||||
return JsonResponse({"payload": profile.payload, "updated_at": profile.updated_at.isoformat()})
|
||||
|
||||
payload, problem = _parse_payload(request)
|
||||
if payload is None:
|
||||
return _error(problem or _("Invalid request."), 400)
|
||||
profile, _created = SyncProfile.objects.update_or_create(token_hash=token_hash, defaults={"payload": payload})
|
||||
return JsonResponse({"updated_at": profile.updated_at.isoformat()})
|
||||
Reference in New Issue
Block a user