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:
@@ -12,6 +12,7 @@ secrets.*
|
|||||||
backend/**/__pycache__/
|
backend/**/__pycache__/
|
||||||
backend/**/*.pyc
|
backend/**/*.pyc
|
||||||
backend/db.sqlite3
|
backend/db.sqlite3
|
||||||
|
backend/**/*.mo
|
||||||
backend/staticfiles/
|
backend/staticfiles/
|
||||||
backend/.venv/
|
backend/.venv/
|
||||||
backend/venv/
|
backend/venv/
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ VENV := .venv
|
|||||||
VENV_PY := $(VENV)/bin/python
|
VENV_PY := $(VENV)/bin/python
|
||||||
PORT ?= 8000
|
PORT ?= 8000
|
||||||
|
|
||||||
.PHONY: help install vendor-pyodide dev validate-levels build test test-js test-python typecheck clean
|
.PHONY: help install vendor-pyodide dev validate-levels build test test-js test-python test-backend typecheck clean
|
||||||
|
|
||||||
help: ## Affiche cette aide
|
help: ## Affiche cette aide
|
||||||
@grep -E '^[a-z-]+:.*##' $(MAKEFILE_LIST) | awk -F':.*## ' '{printf " %-16s %s\n", $$1, $$2}'
|
@grep -E '^[a-z-]+:.*##' $(MAKEFILE_LIST) | awk -F':.*## ' '{printf " %-16s %s\n", $$1, $$2}'
|
||||||
@@ -29,7 +29,7 @@ validate-levels: $(VENV)/.installed ## Valide les niveaux (schéma, manifeste, t
|
|||||||
build: $(VENV)/.installed ## Construit dist/ pour la production
|
build: $(VENV)/.installed ## Construit dist/ pour la production
|
||||||
$(VENV_PY) scripts/build.py
|
$(VENV_PY) scripts/build.py
|
||||||
|
|
||||||
test: test-js test-python validate-levels ## Lance tous les tests
|
test: test-js test-python test-backend validate-levels ## Lance tous les tests
|
||||||
|
|
||||||
test-js: ## Tests JavaScript (node:test, aucune dépendance)
|
test-js: ## Tests JavaScript (node:test, aucune dépendance)
|
||||||
node --test tests/js/*.test.mjs
|
node --test tests/js/*.test.mjs
|
||||||
@@ -37,6 +37,10 @@ test-js: ## Tests JavaScript (node:test, aucune dépendance)
|
|||||||
test-python: ## Tests Python du runner
|
test-python: ## Tests Python du runner
|
||||||
$(PYTHON) -m unittest discover -s tests/python -v
|
$(PYTHON) -m unittest discover -s tests/python -v
|
||||||
|
|
||||||
|
test-backend: $(VENV)/.installed ## Tests du backend Django (nécessite Django dans .venv)
|
||||||
|
$(VENV)/bin/pip install --quiet -r backend/requirements.txt
|
||||||
|
cd backend && ../$(VENV_PY) manage.py test
|
||||||
|
|
||||||
typecheck: $(VENV)/.installed ## Vérifie les types Python avec pyright
|
typecheck: $(VENV)/.installed ## Vérifie les types Python avec pyright
|
||||||
$(VENV)/bin/pyright
|
$(VENV)/bin/pyright
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# PyQuest sync API messages (en).
|
||||||
|
msgid ""
|
||||||
|
msgstr ""
|
||||||
|
"Content-Type: text/plain; charset=UTF-8\n"
|
||||||
|
"Language: en\n"
|
||||||
|
|
||||||
|
#: sync/views.py
|
||||||
|
msgid "Payload too large."
|
||||||
|
msgstr ""
|
||||||
|
|
||||||
|
#: sync/views.py
|
||||||
|
msgid "Invalid JSON."
|
||||||
|
msgstr ""
|
||||||
|
|
||||||
|
#: sync/views.py
|
||||||
|
msgid "Invalid progress payload."
|
||||||
|
msgstr ""
|
||||||
|
|
||||||
|
#: sync/views.py
|
||||||
|
msgid "Missing or malformed token."
|
||||||
|
msgstr ""
|
||||||
|
|
||||||
|
#: sync/views.py
|
||||||
|
msgid "No progress stored for this token."
|
||||||
|
msgstr ""
|
||||||
|
|
||||||
|
#: sync/views.py
|
||||||
|
msgid "Invalid request."
|
||||||
|
msgstr ""
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# PyQuest sync API messages (fr).
|
||||||
|
msgid ""
|
||||||
|
msgstr ""
|
||||||
|
"Content-Type: text/plain; charset=UTF-8\n"
|
||||||
|
"Language: fr\n"
|
||||||
|
|
||||||
|
#: sync/views.py
|
||||||
|
msgid "Payload too large."
|
||||||
|
msgstr "Données trop volumineuses."
|
||||||
|
|
||||||
|
#: sync/views.py
|
||||||
|
msgid "Invalid JSON."
|
||||||
|
msgstr "JSON invalide."
|
||||||
|
|
||||||
|
#: sync/views.py
|
||||||
|
msgid "Invalid progress payload."
|
||||||
|
msgstr "Progression invalide."
|
||||||
|
|
||||||
|
#: sync/views.py
|
||||||
|
msgid "Missing or malformed token."
|
||||||
|
msgstr "Jeton absent ou mal formé."
|
||||||
|
|
||||||
|
#: sync/views.py
|
||||||
|
msgid "No progress stored for this token."
|
||||||
|
msgstr "Aucune progression enregistrée pour ce jeton."
|
||||||
|
|
||||||
|
#: sync/views.py
|
||||||
|
msgid "Invalid request."
|
||||||
|
msgstr "Requête invalide."
|
||||||
Executable
+16
@@ -0,0 +1,16 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Point d'entrée des commandes Django."""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pyquest_api.settings.dev")
|
||||||
|
from django.core.management import execute_from_command_line
|
||||||
|
|
||||||
|
execute_from_command_line(sys.argv)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
"""Réglages communs. Le backend ne sert qu'à synchroniser la progression entre appareils."""
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
BASE_DIR = Path(__file__).resolve().parent.parent.parent
|
||||||
|
|
||||||
|
INSTALLED_APPS = ["sync"]
|
||||||
|
|
||||||
|
MIDDLEWARE = [
|
||||||
|
"django.middleware.security.SecurityMiddleware",
|
||||||
|
"django.middleware.locale.LocaleMiddleware",
|
||||||
|
"django.middleware.common.CommonMiddleware",
|
||||||
|
]
|
||||||
|
|
||||||
|
ROOT_URLCONF = "pyquest_api.urls"
|
||||||
|
WSGI_APPLICATION = "pyquest_api.wsgi.application"
|
||||||
|
|
||||||
|
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
|
||||||
|
|
||||||
|
LANGUAGE_CODE = "fr"
|
||||||
|
LANGUAGES = [("fr", "Français"), ("en", "English")]
|
||||||
|
LOCALE_PATHS = [BASE_DIR / "locale"]
|
||||||
|
USE_I18N = True
|
||||||
|
USE_TZ = True
|
||||||
|
TIME_ZONE = "UTC"
|
||||||
|
|
||||||
|
# Taille maximale d'une progression synchronisée (octets).
|
||||||
|
SYNC_MAX_PAYLOAD_BYTES = 256 * 1024
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
"""Réglages de développement : SQLite locale, DEBUG actif, clé non secrète."""
|
||||||
|
|
||||||
|
from .base import * # noqa: F401,F403
|
||||||
|
from .base import BASE_DIR
|
||||||
|
|
||||||
|
DEBUG = True
|
||||||
|
SECRET_KEY = "dev-only-not-a-secret" # noqa: S105 - jamais utilisée en production
|
||||||
|
ALLOWED_HOSTS = ["127.0.0.1", "localhost"]
|
||||||
|
|
||||||
|
DATABASES = {
|
||||||
|
"default": {
|
||||||
|
"ENGINE": "django.db.backends.sqlite3",
|
||||||
|
"NAME": BASE_DIR / "db.sqlite3",
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
"""Réglages de production : tout secret vient de l'environnement, rien n'est commité."""
|
||||||
|
|
||||||
|
import os
|
||||||
|
|
||||||
|
from .base import * # noqa: F401,F403
|
||||||
|
|
||||||
|
|
||||||
|
def _required(name: str) -> str:
|
||||||
|
value = os.environ.get(name)
|
||||||
|
if not value:
|
||||||
|
raise RuntimeError(f"Missing required environment variable: {name}")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
DEBUG = False
|
||||||
|
SECRET_KEY = _required("PYQUEST_SECRET_KEY")
|
||||||
|
ALLOWED_HOSTS = _required("PYQUEST_ALLOWED_HOSTS").split(",")
|
||||||
|
|
||||||
|
DATABASES = {
|
||||||
|
"default": {
|
||||||
|
"ENGINE": "django.db.backends.postgresql",
|
||||||
|
"NAME": _required("PYQUEST_DB_NAME"),
|
||||||
|
"USER": _required("PYQUEST_DB_USER"),
|
||||||
|
"PASSWORD": _required("PYQUEST_DB_PASSWORD"),
|
||||||
|
"HOST": os.environ.get("PYQUEST_DB_HOST", "127.0.0.1"),
|
||||||
|
"PORT": os.environ.get("PYQUEST_DB_PORT", "5432"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Derrière nginx en HTTPS.
|
||||||
|
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
|
||||||
|
SECURE_SSL_REDIRECT = True
|
||||||
|
SECURE_HSTS_SECONDS = 31536000
|
||||||
|
SECURE_CONTENT_TYPE_NOSNIFF = True
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
from django.urls import include, path
|
||||||
|
|
||||||
|
urlpatterns = [
|
||||||
|
path("api/sync/", include("sync.urls")),
|
||||||
|
]
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import os
|
||||||
|
|
||||||
|
from django.core.wsgi import get_wsgi_application
|
||||||
|
|
||||||
|
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pyquest_api.settings.production")
|
||||||
|
|
||||||
|
application = get_wsgi_application()
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
# Backend de synchronisation (optionnel). Django LTS.
|
||||||
|
Django>=5.2,<5.3
|
||||||
|
gunicorn>=22.0 # production uniquement
|
||||||
@@ -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()})
|
||||||
@@ -2,3 +2,4 @@
|
|||||||
PyYAML>=6.0
|
PyYAML>=6.0
|
||||||
jsonschema>=4.21
|
jsonschema>=4.21
|
||||||
pyright>=1.1.380
|
pyright>=1.1.380
|
||||||
|
django-stubs>=5.1 # types pour pyright (backend)
|
||||||
|
|||||||
Reference in New Issue
Block a user