mirror of
https://github.com/deunix-educ/PyQuest.git
synced 2026-11-25 08:19:44 +01:00
Online documentation at /docs/ for authors and administrators: built into dist, nginx auth_request (check-docs), editor and admin links, Docker/server_update integration
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
+3
-1
@@ -6,7 +6,9 @@ dist
|
|||||||
vendor
|
vendor
|
||||||
site
|
site
|
||||||
tests
|
tests
|
||||||
docs
|
docs/design
|
||||||
|
docs/ci
|
||||||
|
docs/MAINTAINERS.md
|
||||||
backend/db.sqlite3
|
backend/db.sqlite3
|
||||||
backend/staticfiles
|
backend/staticfiles
|
||||||
**/__pycache__
|
**/__pycache__
|
||||||
|
|||||||
@@ -43,6 +43,13 @@ vrai navigateur (Chromium) avec 4 niveaux jouables.
|
|||||||
| Accès éditeur | `backend/authors/` (login, `check` pour nginx `auth_request`, administration `/api/admin/` : groupe « Auteurs » / permission `use_editor`, `create_author`, anti force brute) ; nginx `pyquest.conf.example` ; prod = MariaDB |
|
| Accès éditeur | `backend/authors/` (login, `check` pour nginx `auth_request`, administration `/api/admin/` : groupe « Auteurs » / permission `use_editor`, `create_author`, anti force brute) ; nginx `pyquest.conf.example` ; prod = MariaDB |
|
||||||
| Synchronisation | `core/SyncClient.js` + section Réglages ; export/import fichier ; voir `docs/design/09-sync.md` ; `make dev-sync` |
|
| Synchronisation | `core/SyncClient.js` + section Réglages ; export/import fichier ; voir `docs/design/09-sync.md` ; `make dev-sync` |
|
||||||
|
|
||||||
|
## Documentation en ligne (/docs/)
|
||||||
|
|
||||||
|
mkdocs construit dans `dist/docs/` (`make build` dépend de `make docs` ; `server_update.sh` et l'image Docker aussi),
|
||||||
|
protégée par nginx `auth_request` → `/api/auth/check-docs/` : auteurs **et** comptes `is_staff`. Hors précache du service
|
||||||
|
worker (`is_author_tool`, `isAuthorTool`). Liens : bouton « Documentation » de l'éditeur (affiché si `/docs/` existe) et
|
||||||
|
gabarit `backend/authors/templates/admin/base_site.html` (`authors` est avant `admin` dans INSTALLED_APPS).
|
||||||
|
|
||||||
## Déploiement sur le VPS — état et reprise (mis à jour 2026-10-17)
|
## Déploiement sur le VPS — état et reprise (mis à jour 2026-10-17)
|
||||||
|
|
||||||
**État : rien n'est déployé.** Tout est préparé et testé sans serveur. **Flux retenu par l'utilisateur : il est root sur le
|
**État : rien n'est déployé.** Tout est préparé et testé sans serveur. **Flux retenu par l'utilisateur : il est root sur le
|
||||||
|
|||||||
@@ -70,8 +70,8 @@ dev-author: $(VENV)/.installed ## Compte local direct : NAME=x, RESET=--reset (m
|
|||||||
validate-levels: $(VENV)/.installed ## Valide les niveaux (schéma, manifeste, traductions)
|
validate-levels: $(VENV)/.installed ## Valide les niveaux (schéma, manifeste, traductions)
|
||||||
$(VENV_PY) scripts/validate_levels.py
|
$(VENV_PY) scripts/validate_levels.py
|
||||||
|
|
||||||
build: $(VENV)/.installed ## Construit dist/ pour la production
|
build: $(VENV)/.installed docs ## Construit dist/ pour la production (avec la documentation, servie sous /docs/)
|
||||||
$(VENV_PY) scripts/build.py
|
$(VENV_PY) scripts/build.py --docs site
|
||||||
|
|
||||||
test: test-js test-python test-backend test-deploy validate-levels check-voice ## Lance tous les tests
|
test: test-js test-python test-backend test-deploy validate-levels check-voice ## Lance tous les tests
|
||||||
|
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ export class AuthorApp {
|
|||||||
#store;
|
#store;
|
||||||
#catalogs;
|
#catalogs;
|
||||||
#root;
|
#root;
|
||||||
|
#hasDocs = false; // documentation en ligne publiée par le serveur (/docs/)
|
||||||
#account = null; // { username, csrf } si l'éditeur est protégé par une connexion (backend Django), sinon null
|
#account = null; // { username, csrf } si l'éditeur est protégé par une connexion (backend Django), sinon null
|
||||||
#knownIds = [];
|
#knownIds = [];
|
||||||
#model = emptyLevelModel();
|
#model = emptyLevelModel();
|
||||||
@@ -66,6 +67,7 @@ export class AuthorApp {
|
|||||||
|
|
||||||
async run() {
|
async run() {
|
||||||
this.#account = await this.#loadAccount();
|
this.#account = await this.#loadAccount();
|
||||||
|
await this.#detectDocs();
|
||||||
this.#knownIds = (await this.#lessons.listLevels()).map((level) => level.id);
|
this.#knownIds = (await this.#lessons.listLevels()).map((level) => level.id);
|
||||||
const draft = await this.#store.get(DRAFT_KEY).catch(() => undefined);
|
const draft = await this.#store.get(DRAFT_KEY).catch(() => undefined);
|
||||||
if (draft) {
|
if (draft) {
|
||||||
@@ -97,6 +99,23 @@ export class AuthorApp {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lien vers la documentation en ligne (/docs/), seulement si le serveur la publie : sinon (essai local sans
|
||||||
|
* documentation) pas de lien mort. La vérification est faite une fois, à l'ouverture.
|
||||||
|
*/
|
||||||
|
async #detectDocs() {
|
||||||
|
try {
|
||||||
|
const response = await fetch(new URL('docs/', document.baseURI), { method: 'HEAD', cache: 'no-store', credentials: 'same-origin', redirect: 'manual' });
|
||||||
|
this.#hasDocs = response.ok;
|
||||||
|
} catch {
|
||||||
|
this.#hasDocs = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#docsLink() {
|
||||||
|
return this.#hasDocs ? el('a', { class: 'btn', id: 'author-docs', href: 'docs/', target: '_blank', rel: 'noopener', text: this.#t('author.toolbar.docs') }) : null;
|
||||||
|
}
|
||||||
|
|
||||||
/** Formulaire de déconnexion (vrai POST protégé par CSRF : la page de connexion s'affiche ensuite). */
|
/** Formulaire de déconnexion (vrai POST protégé par CSRF : la page de connexion s'affiche ensuite). */
|
||||||
#accountControl() {
|
#accountControl() {
|
||||||
if (!this.#account) {
|
if (!this.#account) {
|
||||||
@@ -152,6 +171,7 @@ export class AuthorApp {
|
|||||||
fileInput,
|
fileInput,
|
||||||
el('button', { type: 'button', class: 'btn btn-primary', id: 'author-download', text: t('author.toolbar.download'), onclick: () => this.#download() }),
|
el('button', { type: 'button', class: 'btn btn-primary', id: 'author-download', text: t('author.toolbar.download'), onclick: () => this.#download() }),
|
||||||
languages,
|
languages,
|
||||||
|
this.#docsLink(),
|
||||||
el('a', { class: 'btn', href: './', text: t('author.toolbar.back') }),
|
el('a', { class: 'btn', href: './', text: t('author.toolbar.back') }),
|
||||||
),
|
),
|
||||||
this.#accountControl(),
|
this.#accountControl(),
|
||||||
|
|||||||
@@ -151,6 +151,7 @@
|
|||||||
"author.kind.drawing_colors": "Drawing: colours used",
|
"author.kind.drawing_colors": "Drawing: colours used",
|
||||||
"author.kind.drawing_colors.help": "Colours that must all appear, comma-separated: “red,blue”.",
|
"author.kind.drawing_colors.help": "Colours that must all appear, comma-separated: “red,blue”.",
|
||||||
"lint.drawing_value_invalid": "Malformed drawing test value (see the test type help; colours: black, red, green, blue, orange, purple, gray).",
|
"lint.drawing_value_invalid": "Malformed drawing test value (see the test type help; colours: black, red, green, blue, orange, purple, gray).",
|
||||||
|
"author.toolbar.docs": "Documentation (new tab)",
|
||||||
"author.account.label": "Account",
|
"author.account.label": "Account",
|
||||||
"author.account.signed_in": "Signed in: {name}",
|
"author.account.signed_in": "Signed in: {name}",
|
||||||
"author.account.logout": "Sign out"
|
"author.account.logout": "Sign out"
|
||||||
|
|||||||
@@ -151,6 +151,7 @@
|
|||||||
"author.kind.drawing_colors": "Dessin : couleurs utilisées",
|
"author.kind.drawing_colors": "Dessin : couleurs utilisées",
|
||||||
"author.kind.drawing_colors.help": "Couleurs qui doivent toutes apparaître, séparées par des virgules : « red,blue ».",
|
"author.kind.drawing_colors.help": "Couleurs qui doivent toutes apparaître, séparées par des virgules : « red,blue ».",
|
||||||
"lint.drawing_value_invalid": "Valeur de test de dessin mal formée (voir l'aide du type de test ; couleurs : black, red, green, blue, orange, purple, gray).",
|
"lint.drawing_value_invalid": "Valeur de test de dessin mal formée (voir l'aide du type de test ; couleurs : black, red, green, blue, orange, purple, gray).",
|
||||||
|
"author.toolbar.docs": "Documentation (nouvel onglet)",
|
||||||
"author.account.label": "Compte",
|
"author.account.label": "Compte",
|
||||||
"author.account.signed_in": "Connecté : {name}",
|
"author.account.signed_in": "Connecté : {name}",
|
||||||
"author.account.logout": "Se déconnecter"
|
"author.account.logout": "Se déconnecter"
|
||||||
|
|||||||
@@ -55,7 +55,8 @@ function isNarration(pathname) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function isAuthorTool(pathname) {
|
function isAuthorTool(pathname) {
|
||||||
return pathname === '/author.html' || pathname === '/css/author.css' || pathname.startsWith('/js/author/') || /^\/js\/i18n\/author\.[a-z]+\.json$/.test(pathname);
|
// /docs/ : documentation en ligne, éventuellement protégée par connexion, hors application (jamais mise en cache).
|
||||||
|
return pathname.startsWith('/docs/') || pathname === '/docs' || pathname === '/author.html' || pathname === '/css/author.css' || pathname.startsWith('/js/author/') || /^\/js\/i18n\/author\.[a-z]+\.json$/.test(pathname);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function fromCache(request, cacheName) {
|
async function fromCache(request, cacheName) {
|
||||||
|
|||||||
@@ -13,6 +13,11 @@ def is_author(user: object) -> bool:
|
|||||||
return isinstance(user, User) and user.is_active and user.has_perm(EDITOR_PERMISSION)
|
return isinstance(user, User) and user.is_active and user.has_perm(EDITOR_PERMISSION)
|
||||||
|
|
||||||
|
|
||||||
|
def can_read_docs(user: object) -> bool:
|
||||||
|
"""Documentation en ligne (/docs/) : auteurs et administrateurs (comptes `is_staff`) actifs."""
|
||||||
|
return isinstance(user, User) and user.is_active and (user.is_staff or is_author(user))
|
||||||
|
|
||||||
|
|
||||||
def authors_group() -> Group:
|
def authors_group() -> Group:
|
||||||
"""Groupe « Auteurs », créé au besoin avec la permission de l'éditeur."""
|
"""Groupe « Auteurs », créé au besoin avec la permission de l'éditeur."""
|
||||||
group, _created = Group.objects.get_or_create(name=GROUP_NAME)
|
group, _created = Group.objects.get_or_create(name=GROUP_NAME)
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
{% extends "admin/base_site.html" %}
|
||||||
|
|
||||||
|
{# Documentation en ligne (réservée aux auteurs et administrateurs : /docs/). #}
|
||||||
|
{% block userlinks %}<a href="/docs/">Documentation</a> / {{ block.super }}{% endblock %}
|
||||||
@@ -136,6 +136,36 @@ class CheckAndLogoutTest(TestCase):
|
|||||||
self.assertEqual(response.status_code, 204)
|
self.assertEqual(response.status_code, 204)
|
||||||
self.assertIn("no-store", response.headers["Cache-Control"])
|
self.assertIn("no-store", response.headers["Cache-Control"])
|
||||||
|
|
||||||
|
def test_docs_check_admits_authors_and_administrators_only(self) -> None:
|
||||||
|
url = "/api/auth/check-docs/"
|
||||||
|
self.assertEqual(self.client.get(url).status_code, 401)
|
||||||
|
make_user("lea", staff=False)
|
||||||
|
self.client.login(username="lea", password=PASSWORD)
|
||||||
|
self.assertEqual(self.client.get(url).status_code, 401)
|
||||||
|
make_user("ada")
|
||||||
|
self.client.login(username="ada", password=PASSWORD)
|
||||||
|
response = self.client.get(url)
|
||||||
|
self.assertEqual(response.status_code, 204)
|
||||||
|
self.assertIn("no-store", response.headers["Cache-Control"])
|
||||||
|
admin = make_user("root", staff=False)
|
||||||
|
admin.is_staff = True
|
||||||
|
admin.save()
|
||||||
|
self.client.login(username="root", password=PASSWORD)
|
||||||
|
self.assertEqual(self.client.get(url).status_code, 204)
|
||||||
|
# L'éditeur, lui, reste réservé à la permission d'auteur.
|
||||||
|
self.assertEqual(self.client.get(CHECK).status_code, 401)
|
||||||
|
admin.is_active = False
|
||||||
|
admin.save()
|
||||||
|
self.assertEqual(self.client.get(url).status_code, 401)
|
||||||
|
self.assertEqual(self.client.post(url).status_code, 405)
|
||||||
|
|
||||||
|
def test_admin_pages_link_to_the_documentation(self) -> None:
|
||||||
|
admin = make_user("root", staff=False)
|
||||||
|
admin.is_staff = admin.is_superuser = True
|
||||||
|
admin.save()
|
||||||
|
self.client.login(username="root", password=PASSWORD)
|
||||||
|
self.assertContains(self.client.get("/api/admin/"), 'href="/docs/"')
|
||||||
|
|
||||||
def test_check_refuses_other_methods(self) -> None:
|
def test_check_refuses_other_methods(self) -> None:
|
||||||
self.assertEqual(self.client.post(CHECK).status_code, 405)
|
self.assertEqual(self.client.post(CHECK).status_code, 405)
|
||||||
|
|
||||||
|
|||||||
@@ -6,5 +6,6 @@ urlpatterns = [
|
|||||||
path("login/", views.login_view, name="login"),
|
path("login/", views.login_view, name="login"),
|
||||||
path("logout/", views.logout_view, name="logout"),
|
path("logout/", views.logout_view, name="logout"),
|
||||||
path("check/", views.check_view, name="check"),
|
path("check/", views.check_view, name="check"),
|
||||||
|
path("check-docs/", views.check_docs_view, name="check_docs"),
|
||||||
path("me/", views.me_view, name="me"),
|
path("me/", views.me_view, name="me"),
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ from django.utils.http import url_has_allowed_host_and_scheme
|
|||||||
from django.views.decorators.cache import never_cache
|
from django.views.decorators.cache import never_cache
|
||||||
from django.views.decorators.http import require_GET, require_http_methods, require_POST
|
from django.views.decorators.http import require_GET, require_http_methods, require_POST
|
||||||
|
|
||||||
from .access import is_author
|
from .access import can_read_docs, is_author
|
||||||
from .throttle import client_ip, is_locked, record_failure, record_success
|
from .throttle import client_ip, is_locked, record_failure, record_success
|
||||||
|
|
||||||
DEFAULT_NEXT = "/author.html"
|
DEFAULT_NEXT = "/author.html"
|
||||||
@@ -113,6 +113,13 @@ def check_view(request: HttpRequest) -> HttpResponse:
|
|||||||
return HttpResponse(status=204 if is_author(request.user) else 401)
|
return HttpResponse(status=204 if is_author(request.user) else 401)
|
||||||
|
|
||||||
|
|
||||||
|
@never_cache
|
||||||
|
@require_GET
|
||||||
|
def check_docs_view(request: HttpRequest) -> HttpResponse:
|
||||||
|
"""Appelé par nginx (auth_request) pour /docs/ : 204 pour un auteur ou un administrateur, sinon 401."""
|
||||||
|
return HttpResponse(status=204 if can_read_docs(request.user) else 401)
|
||||||
|
|
||||||
|
|
||||||
@never_cache
|
@never_cache
|
||||||
@require_GET
|
@require_GET
|
||||||
def me_view(request: HttpRequest) -> HttpResponse:
|
def me_view(request: HttpRequest) -> HttpResponse:
|
||||||
|
|||||||
@@ -11,9 +11,9 @@ INSTALLED_APPS = [
|
|||||||
"django.contrib.sessions",
|
"django.contrib.sessions",
|
||||||
"django.contrib.messages",
|
"django.contrib.messages",
|
||||||
"django.contrib.staticfiles",
|
"django.contrib.staticfiles",
|
||||||
|
"authors.apps.AuthorsConfig", # avant l'administration : ses gabarits (lien vers la documentation) la surchargent
|
||||||
"django.contrib.admin",
|
"django.contrib.admin",
|
||||||
"sync",
|
"sync",
|
||||||
"authors.apps.AuthorsConfig",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
MIDDLEWARE = [
|
MIDDLEWARE = [
|
||||||
|
|||||||
+11
-1
@@ -2,6 +2,15 @@
|
|||||||
# Contexte de construction : la racine du dépôt (voir docker/compose.*.yaml).
|
# Contexte de construction : la racine du dépôt (voir docker/compose.*.yaml).
|
||||||
# syntax=docker/dockerfile:1
|
# syntax=docker/dockerfile:1
|
||||||
|
|
||||||
|
# ---- Documentation en ligne (mkdocs) : servie sous /docs/ pour les auteurs et les administrateurs -----------------------
|
||||||
|
FROM python:3.12-slim-bookworm AS docs
|
||||||
|
WORKDIR /src
|
||||||
|
COPY requirements-docs.txt .
|
||||||
|
RUN pip install --no-cache-dir -r requirements-docs.txt
|
||||||
|
COPY mkdocs.yml .
|
||||||
|
COPY docs/site docs/site
|
||||||
|
RUN mkdocs build --quiet --site-dir /site
|
||||||
|
|
||||||
# ---- Site statique : moteur Python (Pyodide, version épinglée et vérifiée) puis construction de dist/ -------------------
|
# ---- Site statique : moteur Python (Pyodide, version épinglée et vérifiée) puis construction de dist/ -------------------
|
||||||
FROM python:3.12-slim-bookworm AS site
|
FROM python:3.12-slim-bookworm AS site
|
||||||
RUN apt-get update && apt-get install -y --no-install-recommends curl bzip2 ca-certificates \
|
RUN apt-get update && apt-get install -y --no-install-recommends curl bzip2 ca-certificates \
|
||||||
@@ -12,7 +21,8 @@ RUN ./scripts/vendor_pyodide.sh
|
|||||||
COPY app app
|
COPY app app
|
||||||
COPY levels levels
|
COPY levels levels
|
||||||
COPY scripts/build.py scripts/
|
COPY scripts/build.py scripts/
|
||||||
RUN python scripts/build.py
|
COPY --from=docs /site site
|
||||||
|
RUN python scripts/build.py --docs site
|
||||||
|
|
||||||
# ---- Serveur web : nginx (>= 1.25.1 pour http2 on) ---------------------------------------------------------------------
|
# ---- Serveur web : nginx (>= 1.25.1 pour http2 on) ---------------------------------------------------------------------
|
||||||
FROM nginx:1.27-alpine AS web
|
FROM nginx:1.27-alpine AS web
|
||||||
|
|||||||
@@ -52,6 +52,20 @@ cd /opt/PyQuest
|
|||||||
The whole procedure (MariaDB database, starting the service, first administrator, publishing, backups, rollback,
|
The whole procedure (MariaDB database, starting the service, first administrator, publishing, backups, rollback,
|
||||||
troubleshooting) is in [Going live and operations](operations.md).
|
troubleshooting) is in [Going live and operations](operations.md).
|
||||||
|
|
||||||
|
## Online documentation (`/docs/`)
|
||||||
|
|
||||||
|
The site publishes its own documentation under `https://your-domain/docs/` (French and English). It is **restricted to
|
||||||
|
signed-in accounts**: **authors** (editor permission) and **administrators** (`is_staff` accounts). Without a session,
|
||||||
|
nginx redirects to the sign-in page, which then returns to the documentation. Links are in the level editor
|
||||||
|
(**Documentation** button) and in the Django administration (top right).
|
||||||
|
|
||||||
|
- It is built with the site: `make build` (and `./scripts/server_update.sh`, or the Docker image) generate `dist/docs/`.
|
||||||
|
`./scripts/server_update.sh --no-docs` publishes without it.
|
||||||
|
- An administrator who is **not** an author signs in on `/api/admin/` first: the session is the same.
|
||||||
|
- The documentation holds no secret: to make it **public**, remove `auth_request` and `error_page` from the
|
||||||
|
`location ^~ /docs/` block in `nginx/pyquest-locations.conf.example`.
|
||||||
|
- Pages are never kept by the service worker (outside the application, always online).
|
||||||
|
|
||||||
## Testing locally before deploying
|
## Testing locally before deploying
|
||||||
|
|
||||||
Three levels of testing, from the simplest to the most faithful to production:
|
Three levels of testing, from the simplest to the most faithful to production:
|
||||||
|
|||||||
@@ -53,6 +53,20 @@ cd /opt/PyQuest
|
|||||||
Toute la marche à suivre (base MariaDB, démarrage du service, premier administrateur, publication, sauvegardes,
|
Toute la marche à suivre (base MariaDB, démarrage du service, premier administrateur, publication, sauvegardes,
|
||||||
retour arrière, dépannage) est dans [Mise en service et exploitation](operations.md).
|
retour arrière, dépannage) est dans [Mise en service et exploitation](operations.md).
|
||||||
|
|
||||||
|
## La documentation en ligne (`/docs/`)
|
||||||
|
|
||||||
|
Le site publie sa propre documentation sous `https://ton-domaine/docs/` (français et anglais). Elle est **réservée aux
|
||||||
|
comptes connectés** : les **auteurs** (permission de l'éditeur) et les **administrateurs** (comptes `is_staff`). Sans
|
||||||
|
session, nginx renvoie vers la page de connexion, qui ramène ensuite sur la documentation. Les liens se trouvent dans
|
||||||
|
l'éditeur de niveaux (bouton **Documentation**) et dans l'administration Django (en haut à droite).
|
||||||
|
|
||||||
|
- Elle est construite avec le site : `make build` (et `./scripts/server_update.sh`, ou l'image Docker) génèrent
|
||||||
|
`dist/docs/`. `./scripts/server_update.sh --no-docs` publie sans elle.
|
||||||
|
- Un administrateur qui n'est **pas** auteur s'identifie d'abord sur `/api/admin/` : la session est la même.
|
||||||
|
- La documentation n'a rien de secret : pour la **rendre publique**, supprimer `auth_request` et `error_page` du bloc
|
||||||
|
`location ^~ /docs/` dans `nginx/pyquest-locations.conf.example`.
|
||||||
|
- Les pages ne sont jamais conservées par le service worker (hors de l'application, toujours en ligne).
|
||||||
|
|
||||||
## Tester en local avant de déployer
|
## Tester en local avant de déployer
|
||||||
|
|
||||||
Trois niveaux d'essai, du plus simple au plus fidèle à la production :
|
Trois niveaux d'essai, du plus simple au plus fidèle à la production :
|
||||||
|
|||||||
@@ -76,6 +76,16 @@
|
|||||||
proxy_set_header X-Forwarded-Proto $scheme;
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Idem pour la documentation en ligne : auteurs ET administrateurs (comptes is_staff) y accèdent.
|
||||||
|
location = /_docs_check {
|
||||||
|
internal;
|
||||||
|
proxy_pass http://127.0.0.1:8001/api/auth/check-docs/;
|
||||||
|
proxy_pass_request_body off;
|
||||||
|
proxy_set_header Content-Length "";
|
||||||
|
proxy_set_header Host $http_host;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
# Non connecté : page de connexion, qui ramène ensuite sur l'éditeur.
|
# Non connecté : page de connexion, qui ramène ensuite sur l'éditeur.
|
||||||
location @author_login {
|
location @author_login {
|
||||||
return 302 /api/auth/login/?next=$request_uri;
|
return 302 /api/auth/login/?next=$request_uri;
|
||||||
@@ -103,6 +113,14 @@
|
|||||||
include snippets/pyquest-author-headers.conf;
|
include snippets/pyquest-author-headers.conf;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Documentation en ligne (mkdocs, copiée dans dist/docs/ par make build) : réservée aux comptes connectés.
|
||||||
|
# Pour la rendre publique, supprimer les deux lignes auth_request et error_page de ce bloc.
|
||||||
|
location ^~ /docs/ {
|
||||||
|
auth_request /_docs_check;
|
||||||
|
error_page 401 = @author_login;
|
||||||
|
include snippets/pyquest-author-headers.conf;
|
||||||
|
}
|
||||||
|
|
||||||
# ---- Backend Django ------------------------------------------------------------------------------------
|
# ---- Backend Django ------------------------------------------------------------------------------------
|
||||||
|
|
||||||
# Connexion : peu d'essais autorisés (Django bloque aussi après 5 échecs par compte pendant 15 minutes).
|
# Connexion : peu d'essais autorisés (Django bloque aussi après 5 échecs par compte pendant 15 minutes).
|
||||||
@@ -140,6 +158,9 @@
|
|||||||
location = /api/auth/check/ {
|
location = /api/auth/check/ {
|
||||||
return 404;
|
return 404;
|
||||||
}
|
}
|
||||||
|
location = /api/auth/check-docs/ {
|
||||||
|
return 404;
|
||||||
|
}
|
||||||
location /api/ {
|
location /api/ {
|
||||||
limit_req zone=pyquest_sync burst=20 nodelay;
|
limit_req zone=pyquest_sync burst=20 nodelay;
|
||||||
client_max_body_size 300k;
|
client_max_body_size 300k;
|
||||||
|
|||||||
+14
-3
@@ -17,10 +17,11 @@ NOT_PRECACHED = {"service-worker.js"}
|
|||||||
|
|
||||||
|
|
||||||
def is_author_tool(relative: str) -> bool:
|
def is_author_tool(relative: str) -> bool:
|
||||||
"""Fichiers propres à l'éditeur de niveaux : sur un serveur ils peuvent être protégés par authentification,
|
"""Fichiers propres à l'éditeur de niveaux et documentation en ligne (/docs/) : sur un serveur ils peuvent être
|
||||||
donc jamais pré-cachés (le service worker les récupérerait sans session et mettrait une page de connexion en cache)."""
|
protégés par authentification, donc jamais pré-cachés (le service worker les récupérerait sans session et mettrait une page de connexion en cache)."""
|
||||||
return (
|
return (
|
||||||
relative == "author.html"
|
relative.startswith("docs/")
|
||||||
|
or relative == "author.html"
|
||||||
or relative == "css/author.css"
|
or relative == "css/author.css"
|
||||||
or relative.startswith("js/author/")
|
or relative.startswith("js/author/")
|
||||||
or (relative.startswith("js/i18n/author.") and relative.endswith(".json"))
|
or (relative.startswith("js/i18n/author.") and relative.endswith(".json"))
|
||||||
@@ -54,6 +55,14 @@ def content_hash(paths: list[str]) -> str:
|
|||||||
|
|
||||||
|
|
||||||
def main() -> int:
|
def main() -> int:
|
||||||
|
# --docs DOSSIER : documentation déjà générée (mkdocs build), copiée dans dist/docs/ (non pré-cachée).
|
||||||
|
docs: Path | None = None
|
||||||
|
if "--docs" in sys.argv:
|
||||||
|
index = sys.argv.index("--docs")
|
||||||
|
docs = Path(sys.argv[index + 1]) if index + 1 < len(sys.argv) else None
|
||||||
|
if docs is None or not (docs / "index.html").is_file():
|
||||||
|
print("--docs : dossier de documentation générée introuvable (make docs).", file=sys.stderr)
|
||||||
|
return 1
|
||||||
pyodide = ROOT / "vendor" / "pyodide"
|
pyodide = ROOT / "vendor" / "pyodide"
|
||||||
if not pyodide.exists():
|
if not pyodide.exists():
|
||||||
print("vendor/pyodide absent : lancez `make vendor-pyodide` d'abord.", file=sys.stderr)
|
print("vendor/pyodide absent : lancez `make vendor-pyodide` d'abord.", file=sys.stderr)
|
||||||
@@ -64,6 +73,8 @@ def main() -> int:
|
|||||||
copy_tree(ROOT / "app", DIST)
|
copy_tree(ROOT / "app", DIST)
|
||||||
copy_tree(ROOT / "levels", DIST / "levels")
|
copy_tree(ROOT / "levels", DIST / "levels")
|
||||||
shutil.copytree(pyodide, DIST / "vendor" / "pyodide")
|
shutil.copytree(pyodide, DIST / "vendor" / "pyodide")
|
||||||
|
if docs is not None:
|
||||||
|
shutil.copytree(docs, DIST / "docs")
|
||||||
|
|
||||||
precache = shell_files()
|
precache = shell_files()
|
||||||
worker = DIST / "service-worker.js"
|
worker = DIST / "service-worker.js"
|
||||||
|
|||||||
@@ -62,6 +62,16 @@ else
|
|||||||
ko "author.html : 200 (public) ou 302 vers la connexion attendus, reçu ${author_code}"
|
ko "author.html : 200 (public) ou 302 vers la connexion attendus, reçu ${author_code}"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
# Documentation en ligne : réservée aux comptes connectés derrière le backend (302 vers la connexion) ; sinon publique.
|
||||||
|
docs_code="$(status "${BASE}/docs/")"
|
||||||
|
if [[ "${author_code}" == 302 ]]; then
|
||||||
|
docs_location="$(header "${BASE}/docs/" Location)"
|
||||||
|
if [[ "${docs_code}" == 302 && "${docs_location}" == *"/api/auth/login/?next=/docs/"* ]]; then ok "documentation protégée par connexion (/docs/)"; else ko "/docs/ : 302 vers la connexion attendu, reçu ${docs_code}"; fi
|
||||||
|
expect_status "${BASE}/api/auth/check-docs/" 404
|
||||||
|
else
|
||||||
|
echo " info /docs/ répond ${docs_code} (200 = documentation publiée, 404 = absente)"
|
||||||
|
fi
|
||||||
|
|
||||||
if [[ "${BASE}" == https://* ]]; then
|
if [[ "${BASE}" == https://* ]]; then
|
||||||
redirect="$(curl -s -o /dev/null -w '%{http_code}' --max-time 20 "http://${BASE#https://}/")"
|
redirect="$(curl -s -o /dev/null -w '%{http_code}' --max-time 20 "http://${BASE#https://}/")"
|
||||||
if [[ "${redirect}" == 301 || "${redirect}" == 308 ]]; then ok "HTTP redirige vers HTTPS (${redirect})"; else ko "HTTP devrait rediriger vers HTTPS, code ${redirect}"; fi
|
if [[ "${redirect}" == 301 || "${redirect}" == 308 ]]; then ok "HTTP redirige vers HTTPS (${redirect})"; else ko "HTTP devrait rediriger vers HTTPS, code ${redirect}"; fi
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
#
|
#
|
||||||
# ./scripts/server_update.sh # tout
|
# ./scripts/server_update.sh # tout
|
||||||
# ./scripts/server_update.sh --rollback # revient à la version précédente du site
|
# ./scripts/server_update.sh --rollback # revient à la version précédente du site
|
||||||
# Options : --no-pull --no-build --no-restart --no-check --dry-run
|
# Options : --no-pull --no-build --no-docs --no-restart --no-check --dry-run
|
||||||
#
|
#
|
||||||
# Variables : PYQUEST_WEB_ROOT (défaut /var/www/pyquest), PYQUEST_KEEP (versions conservées, défaut 3),
|
# Variables : PYQUEST_WEB_ROOT (défaut /var/www/pyquest), PYQUEST_KEEP (versions conservées, défaut 3),
|
||||||
# PYQUEST_ENV_FILE (défaut /etc/pyquest/env), PYQUEST_SERVICE (défaut pyquest).
|
# PYQUEST_ENV_FILE (défaut /etc/pyquest/env), PYQUEST_SERVICE (défaut pyquest).
|
||||||
@@ -17,12 +17,13 @@ KEEP="${PYQUEST_KEEP:-3}"
|
|||||||
ENV_FILE="${PYQUEST_ENV_FILE:-/etc/pyquest/env}"
|
ENV_FILE="${PYQUEST_ENV_FILE:-/etc/pyquest/env}"
|
||||||
SERVICE="${PYQUEST_SERVICE:-pyquest}"
|
SERVICE="${PYQUEST_SERVICE:-pyquest}"
|
||||||
VENV="${REPO}/.venv-prod"
|
VENV="${REPO}/.venv-prod"
|
||||||
PULL=1; BUILD=1; RESTART=1; CHECK=1; DRY_RUN=0; ROLLBACK=0
|
PULL=1; BUILD=1; DOCS=1; RESTART=1; CHECK=1; DRY_RUN=0; ROLLBACK=0
|
||||||
|
|
||||||
for arg in "$@"; do
|
for arg in "$@"; do
|
||||||
case "${arg}" in
|
case "${arg}" in
|
||||||
--no-pull) PULL=0 ;;
|
--no-pull) PULL=0 ;;
|
||||||
--no-build) BUILD=0 ;;
|
--no-build) BUILD=0 ;;
|
||||||
|
--no-docs) DOCS=0 ;;
|
||||||
--no-restart) RESTART=0 ;;
|
--no-restart) RESTART=0 ;;
|
||||||
--no-check) CHECK=0 ;;
|
--no-check) CHECK=0 ;;
|
||||||
--dry-run) DRY_RUN=1 ;;
|
--dry-run) DRY_RUN=1 ;;
|
||||||
@@ -69,7 +70,21 @@ COMMIT="$(git -C "${REPO}" rev-parse --short HEAD 2>/dev/null || echo nogit)"
|
|||||||
if [[ "${BUILD}" == 1 ]]; then
|
if [[ "${BUILD}" == 1 ]]; then
|
||||||
step "Moteur Python (Pyodide) et construction du site"
|
step "Moteur Python (Pyodide) et construction du site"
|
||||||
run "${REPO}/scripts/vendor_pyodide.sh"
|
run "${REPO}/scripts/vendor_pyodide.sh"
|
||||||
run python3 "${REPO}/scripts/build.py"
|
BUILD_ARGS=()
|
||||||
|
if [[ "${DOCS}" == 1 ]]; then
|
||||||
|
# Documentation en ligne (/docs/, réservée aux comptes connectés) : un échec ne bloque pas la mise à jour du site.
|
||||||
|
DOCS_VENV="${REPO}/.venv-docs"
|
||||||
|
if [[ "${DRY_RUN}" == 1 ]]; then
|
||||||
|
echo "[dry-run] mkdocs build (documentation, ${DOCS_VENV})"
|
||||||
|
BUILD_ARGS=(--docs "${REPO}/site")
|
||||||
|
elif { [[ -x "${DOCS_VENV}/bin/mkdocs" ]] || { python3 -m venv "${DOCS_VENV}" && "${DOCS_VENV}/bin/pip" install --quiet -r "${REPO}/requirements-docs.txt"; }; } \
|
||||||
|
&& (cd "${REPO}" && "${DOCS_VENV}/bin/mkdocs" build --quiet 2>/dev/null); then
|
||||||
|
BUILD_ARGS=(--docs "${REPO}/site")
|
||||||
|
else
|
||||||
|
echo "ATTENTION : la documentation n'a pas pu être construite (paquet python3-venv, accès à PyPI ?) : le site est publié sans elle." >&2
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
run python3 "${REPO}/scripts/build.py" "${BUILD_ARGS[@]}"
|
||||||
fi
|
fi
|
||||||
[[ "${DRY_RUN}" == 1 || -f "${REPO}/dist/index.html" ]] || { echo "dist/ est absent : relancer sans --no-build." >&2; exit 1; }
|
[[ "${DRY_RUN}" == 1 || -f "${REPO}/dist/index.html" ]] || { echo "dist/ est absent : relancer sans --no-build." >&2; exit 1; }
|
||||||
[[ "${DRY_RUN}" == 1 || -f "${REPO}/dist/vendor/pyodide/pyodide.asm.wasm" ]] || { echo "Pyodide manque dans dist/." >&2; exit 1; }
|
[[ "${DRY_RUN}" == 1 || -f "${REPO}/dist/vendor/pyodide/pyodide.asm.wasm" ]] || { echo "Pyodide manque dans dist/." >&2; exit 1; }
|
||||||
|
|||||||
@@ -44,6 +44,9 @@ check_stack() { # nom curl-args... : vérifications communes une fois la pile d
|
|||||||
[[ "$(c -I "${base}/vendor/pyodide/pyodide.asm.wasm" | tr -d '\r' | grep -ci 'content-type: application/wasm')" == 1 ]] || fail "${name} : type MIME wasm"
|
[[ "$(c -I "${base}/vendor/pyodide/pyodide.asm.wasm" | tr -d '\r' | grep -ci 'content-type: application/wasm')" == 1 ]] || fail "${name} : type MIME wasm"
|
||||||
code_loc="$(c -o /dev/null -w '%{http_code} %{redirect_url}' "${base}/author.html")"
|
code_loc="$(c -o /dev/null -w '%{http_code} %{redirect_url}' "${base}/author.html")"
|
||||||
[[ "${code_loc}" == "302 "*"/api/auth/login/?next=/author.html" ]] || fail "${name} : author.html doit renvoyer vers la connexion (reçu : ${code_loc})"
|
[[ "${code_loc}" == "302 "*"/api/auth/login/?next=/author.html" ]] || fail "${name} : author.html doit renvoyer vers la connexion (reçu : ${code_loc})"
|
||||||
|
docs_loc="$(c -o /dev/null -w '%{http_code} %{redirect_url}' "${base}/docs/")"
|
||||||
|
[[ "${docs_loc}" == "302 "*"/api/auth/login/?next=/docs/" ]] || fail "${name} : /docs/ doit exiger une connexion (reçu : ${docs_loc})"
|
||||||
|
[[ "$(c -o /dev/null -w '%{http_code}' "${base}/api/auth/check-docs/")" == 404 ]] || fail "${name} : /api/auth/check-docs/ doit rester interne"
|
||||||
[[ "$(c -o /dev/null -w '%{http_code}' "${base}/api/auth/login/")" == 200 ]] || fail "${name} : page de connexion"
|
[[ "$(c -o /dev/null -w '%{http_code}' "${base}/api/auth/login/")" == 200 ]] || fail "${name} : page de connexion"
|
||||||
[[ "$(c -o /dev/null -w '%{http_code}' "${base}/api/auth/check/")" == 404 ]] || fail "${name} : /api/auth/check/ doit rester interne"
|
[[ "$(c -o /dev/null -w '%{http_code}' "${base}/api/auth/check/")" == 404 ]] || fail "${name} : /api/auth/check/ doit rester interne"
|
||||||
[[ "$(c -o /dev/null -w '%{http_code}' "${base}/api/static/admin/css/base.css")" == 200 ]] || fail "${name} : fichiers statiques de l'administration (volume partagé)"
|
[[ "$(c -o /dev/null -w '%{http_code}' "${base}/api/static/admin/css/base.css")" == 200 ]] || fail "${name} : fichiers statiques de l'administration (volume partagé)"
|
||||||
|
|||||||
@@ -83,8 +83,15 @@ test('nginx : l\'éditeur exige une connexion, puis fonctionne isolé ; déconne
|
|||||||
assert.equal(response.status, 302, path);
|
assert.equal(response.status, 302, path);
|
||||||
assert.match(response.headers.get('location'), /\/api\/auth\/login\/\?next=\//, path);
|
assert.match(response.headers.get('location'), /\/api\/auth\/login\/\?next=\//, path);
|
||||||
}
|
}
|
||||||
|
// La documentation en ligne exige elle aussi une connexion (aucune page servie).
|
||||||
|
for (const path of ['docs/', 'docs/fr/', 'docs/assets/stylesheets/main.css']) {
|
||||||
|
const response = await fetch(`${base}${path}`, { redirect: 'manual' });
|
||||||
|
assert.equal(response.status, 302, path);
|
||||||
|
assert.match(response.headers.get('location'), /\/api\/auth\/login\/\?next=\/docs\//, path);
|
||||||
|
}
|
||||||
// Le contrôle interne n'est pas joignable de l'extérieur.
|
// Le contrôle interne n'est pas joignable de l'extérieur.
|
||||||
assert.equal((await fetch(`${base}api/auth/check/`)).status, 404);
|
assert.equal((await fetch(`${base}api/auth/check/`)).status, 404);
|
||||||
|
assert.equal((await fetch(`${base}api/auth/check-docs/`)).status, 404);
|
||||||
|
|
||||||
const context = await browser.newContext({ locale: 'fr-FR' });
|
const context = await browser.newContext({ locale: 'fr-FR' });
|
||||||
const page = await context.newPage();
|
const page = await context.newPage();
|
||||||
@@ -111,6 +118,13 @@ test('nginx : l\'éditeur exige une connexion, puis fonctionne isolé ; déconne
|
|||||||
assert.deepEqual(errors, []);
|
assert.deepEqual(errors, []);
|
||||||
assert.equal((await context.request.get(`${base}js/author/main.js`)).status(), 200);
|
assert.equal((await context.request.get(`${base}js/author/main.js`)).status(), 200);
|
||||||
|
|
||||||
|
// La documentation est lisible avec la session, isolée comme le reste, et l'éditeur y renvoie par un lien.
|
||||||
|
await page.locator('#author-docs').waitFor();
|
||||||
|
const docs = await context.request.get(`${base}docs/`);
|
||||||
|
assert.equal(docs.status(), 200);
|
||||||
|
assert.match(await docs.text(), /PyQuest/);
|
||||||
|
assert.equal(docs.headers()['cross-origin-opener-policy'], 'same-origin');
|
||||||
|
|
||||||
// Déconnexion depuis l'éditeur lui-même : nom affiché, bouton, retour à la page de connexion.
|
// Déconnexion depuis l'éditeur lui-même : nom affiché, bouton, retour à la page de connexion.
|
||||||
await page.getByText('Connecté : ada').waitFor();
|
await page.getByText('Connecté : ada').waitFor();
|
||||||
await page.getByRole('button', { name: 'Se déconnecter' }).click();
|
await page.getByRole('button', { name: 'Se déconnecter' }).click();
|
||||||
@@ -118,6 +132,7 @@ test('nginx : l\'éditeur exige une connexion, puis fonctionne isolé ; déconne
|
|||||||
await page.getByRole('button', { name: 'Se connecter' }).waitFor();
|
await page.getByRole('button', { name: 'Se connecter' }).waitFor();
|
||||||
const after = await context.request.get(`${base}author.html`, { maxRedirects: 0 });
|
const after = await context.request.get(`${base}author.html`, { maxRedirects: 0 });
|
||||||
assert.equal(after.status(), 302);
|
assert.equal(after.status(), 302);
|
||||||
|
assert.equal((await context.request.get(`${base}docs/`, { maxRedirects: 0 })).status(), 302, 'la documentation se referme avec la session');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('nginx : l\'application apprenant est isolée, exécute Python et synchronise par le proxy', { skip, timeout: 120000 }, async () => {
|
test('nginx : l\'application apprenant est isolée, exécute Python et synchronise par le proxy', { skip, timeout: 120000 }, async () => {
|
||||||
@@ -156,6 +171,9 @@ test('nginx : l\'administrateur autorise un compte à utiliser l\'éditeur depui
|
|||||||
await admin.getByLabel('Mot de passe :').fill(PASSWORD);
|
await admin.getByLabel('Mot de passe :').fill(PASSWORD);
|
||||||
await admin.getByRole('button', { name: 'Connexion' }).click();
|
await admin.getByRole('button', { name: 'Connexion' }).click();
|
||||||
await admin.getByText('PyQuest — administration').first().waitFor();
|
await admin.getByText('PyQuest — administration').first().waitFor();
|
||||||
|
// Le lien « Documentation » de l'administration mène à la documentation, ouverte à l'administrateur.
|
||||||
|
await admin.getByRole('link', { name: 'Documentation' }).waitFor();
|
||||||
|
assert.equal((await admin.context().request.get(`${base}docs/`)).status(), 200);
|
||||||
await admin.goto(`${base}api/admin/auth/user/`);
|
await admin.goto(`${base}api/admin/auth/user/`);
|
||||||
await admin.locator('tr', { hasText: 'lea' }).locator('input[type=checkbox]').check();
|
await admin.locator('tr', { hasText: 'lea' }).locator('input[type=checkbox]').check();
|
||||||
await admin.locator('select[name=action]').selectOption('grant_editor');
|
await admin.locator('select[name=action]').selectOption('grant_editor');
|
||||||
|
|||||||
Reference in New Issue
Block a user