Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e196c92590 | ||
|
|
d30737a5da | ||
|
|
982b556c48 | ||
|
|
ec729d604f | ||
|
|
0617fa8dc4 | ||
|
|
d2da878dbd | ||
|
|
26153caeaf | ||
|
|
7f29cec2a2 | ||
|
|
7d441b11c2 |
No files matched your search
@@ -2,6 +2,8 @@
|
|||||||
SECRET_KEY=changer-moi
|
SECRET_KEY=changer-moi
|
||||||
DEBUG=true
|
DEBUG=true
|
||||||
ALLOWED_HOSTS=localhost,127.0.0.1
|
ALLOWED_HOSTS=localhost,127.0.0.1
|
||||||
|
# Origine du serveur Vite (front en développement)
|
||||||
|
CSRF_TRUSTED_ORIGINS=http://localhost:5173
|
||||||
DATABASE_URL=postgres://prism:prism@db:5432/prism
|
DATABASE_URL=postgres://prism:prism@db:5432/prism
|
||||||
EMAIL_URL=smtp://mailpit:1025
|
EMAIL_URL=smtp://mailpit:1025
|
||||||
DEFAULT_FROM_EMAIL=no-reply@prism.localhost
|
DEFAULT_FROM_EMAIL=no-reply@prism.localhost
|
||||||
@@ -11,3 +13,11 @@ DEFAULT_FROM_EMAIL=no-reply@prism.localhost
|
|||||||
# NOMINATIM_URL=https://nominatim.openstreetmap.org/search
|
# NOMINATIM_URL=https://nominatim.openstreetmap.org/search
|
||||||
# IRCELINE_WMS_URL=https://geo.irceline.be/rio/wms
|
# IRCELINE_WMS_URL=https://geo.irceline.be/rio/wms
|
||||||
# PRISM_HTTP_TIMEOUT=5
|
# PRISM_HTTP_TIMEOUT=5
|
||||||
|
|
||||||
|
# Comptes
|
||||||
|
FRONTEND_URL=http://localhost:5173
|
||||||
|
BACKEND_URL=http://localhost:8000
|
||||||
|
# Adresses de la cellule SSMG prévenues des nouvelles demandes (séparées par des virgules)
|
||||||
|
SSMG_NOTIFY_EMAILS=cellule-environnement@prism.localhost
|
||||||
|
# L'admin Django exige la 2FA (vrai par défaut hors DEBUG)
|
||||||
|
# ADMIN_REQUIRE_OTP=false
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
name: Build and release
|
||||||
|
run-name: Build and release ${{ github.ref_name }} (by ${{ gitea.actor }})
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- "*"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
docker:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: https://gitea.com/actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||||
|
- name: Log in to Docker Registry
|
||||||
|
uses: https://gitea.com/docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4
|
||||||
|
with:
|
||||||
|
registry: h3m6q87t.gra7.container-registry.ovh.net
|
||||||
|
username: ${{ vars.OVH_REGISTRY_USERNAME }}
|
||||||
|
password: ${{ secrets.OVH_REGISTRY_PASSWORD }}
|
||||||
|
- name: Set up Docker Buildx
|
||||||
|
uses: https://gitea.com/docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4
|
||||||
|
- name: Build and push backend
|
||||||
|
uses: https://gitea.com/docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7
|
||||||
|
with:
|
||||||
|
context: backend
|
||||||
|
pull: true
|
||||||
|
push: true
|
||||||
|
tags: h3m6q87t.gra7.container-registry.ovh.net/prism/backend:${{ github.ref_name }}
|
||||||
|
|
||||||
|
- name: Build and push frontend
|
||||||
|
uses: https://gitea.com/docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7
|
||||||
|
with:
|
||||||
|
context: frontend
|
||||||
|
pull: true
|
||||||
|
push: true
|
||||||
|
tags: h3m6q87t.gra7.container-registry.ovh.net/prism/frontend:${{ github.ref_name }}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
name: Test build
|
||||||
|
run-name: Build ${{ github.ref_name }} (by ${{ gitea.actor }})
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
types:
|
||||||
|
- auto_merge_enabled
|
||||||
|
- opened
|
||||||
|
- synchronize
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
docker:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: https://gitea.com/actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||||
|
- name: Set up Docker Buildx
|
||||||
|
uses: https://gitea.com/docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4
|
||||||
|
- name: Build backend
|
||||||
|
uses: https://gitea.com/docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7
|
||||||
|
with:
|
||||||
|
context: backend
|
||||||
|
pull: true
|
||||||
|
push: false
|
||||||
|
|
||||||
|
- name: Build frontend
|
||||||
|
uses: https://gitea.com/docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7
|
||||||
|
with:
|
||||||
|
context: frontend
|
||||||
|
pull: true
|
||||||
|
push: false
|
||||||
|
|
||||||
|
backend-tests:
|
||||||
|
name: Back-end (qualité et tests)
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
services:
|
||||||
|
# Base des tests, joignable sous le nom « db ».
|
||||||
|
db:
|
||||||
|
image: postgres:17
|
||||||
|
env:
|
||||||
|
POSTGRES_DB: prism
|
||||||
|
POSTGRES_USER: prism
|
||||||
|
POSTGRES_PASSWORD: prism
|
||||||
|
options: >-
|
||||||
|
--health-cmd "pg_isready -U prism -d prism"
|
||||||
|
--health-interval 5s
|
||||||
|
--health-timeout 5s
|
||||||
|
--health-retries 10
|
||||||
|
env:
|
||||||
|
SECRET_KEY: ci-uniquement-pas-un-secret
|
||||||
|
DEBUG: "true"
|
||||||
|
ALLOWED_HOSTS: localhost
|
||||||
|
CSRF_TRUSTED_ORIGINS: http://localhost
|
||||||
|
DATABASE_URL: postgres://prism:prism@db:5432/prism
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: backend
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: https://gitea.com/actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||||
|
- name: Set up Python
|
||||||
|
uses: https://gitea.com/actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
|
||||||
|
with:
|
||||||
|
python-version: "3.12"
|
||||||
|
- name: Install uv
|
||||||
|
run: python -m pip install "uv~=0.9"
|
||||||
|
- name: Install dependencies
|
||||||
|
run: uv sync --locked
|
||||||
|
- name: Wait for PostgreSQL
|
||||||
|
run: >-
|
||||||
|
uv run python -c "import socket,time,sys;
|
||||||
|
[(sys.exit(0) if socket.socket().connect_ex(('db',5432))==0 else time.sleep(1)) for _ in range(30)]"
|
||||||
|
- name: Ruff (lint)
|
||||||
|
run: uv run ruff check .
|
||||||
|
- name: Ruff (format)
|
||||||
|
run: uv run ruff format --check .
|
||||||
|
- name: Check migrations are up to date
|
||||||
|
run: uv run python manage.py makemigrations --check --dry-run
|
||||||
|
- name: Tests
|
||||||
|
run: uv run pytest
|
||||||
|
|
||||||
|
frontend-tests:
|
||||||
|
name: Front-end (qualité, tests et build)
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: frontend
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: https://gitea.com/actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||||
|
- name: Set up Node
|
||||||
|
uses: https://gitea.com/actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||||
|
with:
|
||||||
|
node-version: 24
|
||||||
|
- name: Install dependencies
|
||||||
|
run: npm ci
|
||||||
|
- name: Lint
|
||||||
|
run: |
|
||||||
|
npx oxlint .
|
||||||
|
npx eslint .
|
||||||
|
- name: Type check
|
||||||
|
run: npm run type-check
|
||||||
|
- name: Tests
|
||||||
|
run: npm run test:unit -- --run
|
||||||
|
- name: Build
|
||||||
|
run: npm run build-only
|
||||||
@@ -14,22 +14,41 @@ docker compose exec web python manage.py createsuperuser
|
|||||||
docker compose exec web pytest # tests (HTTP mocké avec respx)
|
docker compose exec web pytest # tests (HTTP mocké avec respx)
|
||||||
docker compose exec web sh -c 'ruff check . && ruff format --check .'
|
docker compose exec web sh -c 'ruff check . && ruff format --check .'
|
||||||
docker compose exec web python manage.py makemigrations --check --dry-run
|
docker compose exec web python manage.py makemigrations --check --dry-run
|
||||||
|
docker compose exec web python manage.py purge_pending_accounts # tâche périodique (cron)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
E-mails en développement : capturés par Mailpit (`http://localhost:8025`).
|
||||||
|
|
||||||
Dépendances : `backend/pyproject.toml` + `uv.lock` (uv). Après modification : `uv lock` (dans un conteneur Python 3.12), puis `docker compose build web`.
|
Dépendances : `backend/pyproject.toml` + `uv.lock` (uv). Après modification : `uv lock` (dans un conteneur Python 3.12), puis `docker compose build web`.
|
||||||
|
|
||||||
URL en dev : API `http://localhost:8000/api/v1/`, doc OpenAPI `/api/docs/`, admin `/admin/`, Mailpit `http://localhost:8025`.
|
Front (`frontend/`, Node 24, hors Docker) :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm --prefix frontend install
|
||||||
|
npm --prefix frontend run dev # http://localhost:5173, /api relayé vers Django
|
||||||
|
npm --prefix frontend run test:unit -- --run
|
||||||
|
npm --prefix frontend run type-check && npm --prefix frontend run lint
|
||||||
|
```
|
||||||
|
|
||||||
|
URL en dev : front `http://localhost:5173`, API `http://localhost:8000/api/v1/`, doc OpenAPI `/api/docs/`, admin `/admin/`, Mailpit `http://localhost:8025`.
|
||||||
|
|
||||||
## Architecture (`backend/`)
|
## Architecture (`backend/`)
|
||||||
|
|
||||||
- `config/` : settings (tout par variables d'environnement via django-environ). URL et couches des sources externes dans `PRISM_SOURCES`.
|
- `config/` : settings (tout par variables d'environnement via django-environ). URL et couches des sources externes dans `PRISM_SOURCES`.
|
||||||
- `accounts/` : `User` (e-mail = identifiant, `status` ; seul `active` peut se connecter), `MailEvent`. Rôles = Groups « Médecin », « Cellule SSMG », « Admin » (migration `0002_roles`). django-otp installé, endpoints d'auth pas encore écrits.
|
- `accounts/` : `User` (e-mail = identifiant, `status` ; seul `active` peut se connecter), `MailEvent`, `RecoveryCode` (codes de secours hachés). Rôles = Groups « Médecin », « Cellule SSMG », « Admin » (migration `0002_roles`).
|
||||||
|
- Routes `/api/v1/auth/` : `login` (étape 1, renvoie `mfa_required`), `2fa/verify` (étape 2 : TOTP ou code de secours), `logout`, `me` (dépose le cookie CSRF), `register`, `verify-email`, `verify-email/resend`, `password/change`, `password-reset` (+ `validate`, `confirm`), `2fa/setup|enable|disable|recovery-codes`.
|
||||||
|
- `services.py` : inscription, validation/refus (actions de l'admin), 2FA (django-otp `TOTPDevice`). `tokens.py` : jetons des liens e-mail (confirmation : signés, usage unique déduit du statut ; réinitialisation : jeton de Django `uid.jeton`, 1 h, invalidé par le changement de mot de passe). `emails.py` + `templates/accounts/emails/` : les 8 e-mails, envoyés après commit et tracés dans `MailEvent`.
|
||||||
|
- L'admin Django exige la 2FA si `ADMIN_REQUIRE_OTP` (vrai hors DEBUG). Commande `purge_pending_accounts` : supprime les demandes non confirmées après 7 jours.
|
||||||
- `factors/` : `Factor`, `DataSource`, `ThresholdClass` (valeur source → niveau 1–4 + couleur, par région ; `BE` = repli national), `ContentBlock` (textes, statut brouillon/validé, historique), `Reference` + `ContentReference` (notes numérotées).
|
- `factors/` : `Factor`, `DataSource`, `ThresholdClass` (valeur source → niveau 1–4 + couleur, par région ; `BE` = repli national), `ContentBlock` (textes, statut brouillon/validé, historique), `Reference` + `ContentReference` (notes numérotées).
|
||||||
- `assessments/` :
|
- `assessments/` :
|
||||||
- `geocoding/` : chaîne Best Address (désactivée tant que `BEST_ADDRESS_URL` est vide, format à confirmer) → Nominatim. Région déduite du code postal.
|
- `geocoding/` : chaîne Best Address (désactivée tant que `BEST_ADDRESS_URL` est vide, format à confirmer) → Nominatim. Région déduite du code postal.
|
||||||
- `providers/` : un module par facteur (`FactorProvider.fetch(client, location) -> RawResult`), inscrit dans `registry.py`. Un module lève une exception si sa source ne répond pas ; le service la convertit en `status: unavailable`.
|
- `providers/` : un module par facteur (`FactorProvider.fetch(client, location) -> RawResult`), inscrit dans `registry.py`. Un module lève une exception si sa source ne répond pas ; le service la convertit en `status: unavailable`.
|
||||||
- `services.py` : géocode, appelle les modules en parallèle (httpx async), mappe `RawResult.source_value` sur `ThresholdClass.source_value`, joint le `ContentBlock` validé.
|
- `services.py` : géocode, appelle les modules en parallèle (httpx async), mappe `RawResult.source_value` sur `ThresholdClass.source_value`, joint le `ContentBlock` validé.
|
||||||
|
|
||||||
|
## Front (`frontend/`)
|
||||||
|
|
||||||
|
Vue 3 + TS (favicon de la SSMG dans `public/`), sans bibliothèque de composants : composants maison stylés avec Bootstrap (CSS seul) et les variables de `src/styles/main.css`, reprises des maquettes Penpot (fichier « PRISM », page « PRISM – Mockups »). Textes dans `src/locales/fr.json`. Pages : `/login` (avec étape 2FA), `/inscription`, `/inscription/statut`, `/mot-de-passe-oublie`, `/reinitialisation/:jeton` (liens des e-mails : le jeton est retiré de l'URL à l'arrivée), `/compte` (mot de passe, 2FA), `/`, `/403`, `/404`. MapLibre : l'URL du worker est fixée explicitement (`ResultMap.vue`), sinon les couches raster ne se chargent pas avec Vite. Le front appelle l'API en même origine via le proxy Vite ; tests Vitest dans `src/__tests__/` (MapLibre mocké, pas de WebGL dans jsdom).
|
||||||
|
|
||||||
État des sources : bruit et inondation Wallonie via WalOnMap (ArcGIS REST `query`), air via irCELine (WMS `GetFeatureInfo`, moyennes annuelles). Bruxelles (bruit, inondation) et radon (AFCN) ne sont pas raccordés : ils renvoient `unavailable`. Pas de PostGIS pour l'instant (aucune donnée géographique stockée).
|
État des sources : bruit et inondation Wallonie via WalOnMap (ArcGIS REST `query`), air via irCELine (WMS `GetFeatureInfo`, moyennes annuelles). Bruxelles (bruit, inondation) et radon (AFCN) ne sont pas raccordés : ils renvoient `unavailable`. Pas de PostGIS pour l'instant (aucune donnée géographique stockée).
|
||||||
|
|
||||||
## Règles
|
## Règles
|
||||||
@@ -37,4 +56,5 @@ URL en dev : API `http://localhost:8000/api/v1/`, doc OpenAPI `/api/docs/`, admi
|
|||||||
- **Aucune adresse ni coordonnée de patient** stockée ou journalisée. Ne jamais journaliser une URL de requête sortante ni le message d'une exception httpx (ils contiennent les coordonnées) : seulement le code du facteur et le type d'erreur. Les loggers `httpx`/`httpcore` restent en WARNING. Un test (`test_address_is_not_logged`) le vérifie.
|
- **Aucune adresse ni coordonnée de patient** stockée ou journalisée. Ne jamais journaliser une URL de requête sortante ni le message d'une exception httpx (ils contiennent les coordonnées) : seulement le code du facteur et le type d'erreur. Les loggers `httpx`/`httpcore` restent en WARNING. Un test (`test_address_is_not_logged`) le vérifie.
|
||||||
- Seuils, couleurs et textes médicaux sont en base (Django admin), jamais dans le code. Exception : les valeurs guides OMS servant à compter les dépassements (`providers/air.py`).
|
- Seuils, couleurs et textes médicaux sont en base (Django admin), jamais dans le code. Exception : les valeurs guides OMS servant à compter les dépassements (`providers/air.py`).
|
||||||
- Ajouter un facteur = un module dans `providers/` + inscription dans `registry.py` + classes et contenus dans l'admin.
|
- Ajouter un facteur = un module dans `providers/` + inscription dans `registry.py` + classes et contenus dans l'admin.
|
||||||
|
- Côté front, l'adresse du patient reste en mémoire du composant : jamais dans l'URL, le stockage du navigateur ni les journaux.
|
||||||
- Code, commentaires, libellés et messages en français. Licence GPL v3.
|
- Code, commentaires, libellés et messages en français. Licence GPL v3.
|
||||||
@@ -49,9 +49,16 @@ docker compose exec web python manage.py seed_factors
|
|||||||
docker compose exec web python manage.py createsuperuser
|
docker compose exec web python manage.py createsuperuser
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Front (Node 24) :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm --prefix frontend install
|
||||||
|
npm --prefix frontend run dev # http://localhost:5173
|
||||||
|
```
|
||||||
|
|
||||||
API : <http://localhost:8000/api/v1/> · documentation OpenAPI : <http://localhost:8000/api/docs/> · admin : <http://localhost:8000/admin/> · e-mails de test (Mailpit) : <http://localhost:8025/>.
|
API : <http://localhost:8000/api/v1/> · documentation OpenAPI : <http://localhost:8000/api/docs/> · admin : <http://localhost:8000/admin/> · e-mails de test (Mailpit) : <http://localhost:8025/>.
|
||||||
|
|
||||||
Tests et qualité : `docker compose exec web pytest` et `docker compose exec web ruff check .`
|
Tests et qualité : `docker compose exec web pytest`, `docker compose exec web ruff check .` et `npm --prefix frontend run test:unit`.
|
||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
|
|
||||||
@@ -63,7 +70,7 @@ Tests et qualité : `docker compose exec web pytest` et `docker compose exec web
|
|||||||
## État du projet
|
## État du projet
|
||||||
|
|
||||||
- Spécifications et maquettes : en cours de validation.
|
- Spécifications et maquettes : en cours de validation.
|
||||||
- Code : back-end initialisé (modèles, raccordement des API WalOnMap et irCELine, API REST). Restent : Bruxelles, radon, Best Address, endpoints d'authentification, front Vue.
|
- Code : back-end (modèles, raccordement des API WalOnMap et irCELine, API REST, comptes : inscription avec validation par la cellule SSMG, double authentification TOTP, mot de passe oublié, e-mails) et front Vue (connexion, inscription, mot de passe oublié, évaluation avec carte MapLibre, « Mon compte », pages d'erreur). Restent : Bruxelles, radon, Best Address.
|
||||||
- Échéance de la Phase 1 : livraison avant le 31 décembre 2026.
|
- Échéance de la Phase 1 : livraison avant le 31 décembre 2026.
|
||||||
|
|
||||||
## Licence
|
## Licence
|
||||||
|
|||||||
@@ -1,16 +1,33 @@
|
|||||||
from django.contrib import admin
|
from django.contrib import admin, messages
|
||||||
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
|
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
|
||||||
|
from django_otp.plugins.otp_totp.models import TOTPDevice
|
||||||
|
|
||||||
from .models import MailEvent, User
|
from . import services
|
||||||
|
from .models import MailEvent, RecoveryCode, User
|
||||||
|
|
||||||
|
|
||||||
@admin.register(User)
|
@admin.register(User)
|
||||||
class UserAdmin(BaseUserAdmin):
|
class UserAdmin(BaseUserAdmin):
|
||||||
ordering = ["last_name", "first_name"]
|
ordering = ["last_name", "first_name"]
|
||||||
list_display = ["email", "last_name", "first_name", "inami_number", "status", "date_joined"]
|
list_display = [
|
||||||
|
"email",
|
||||||
|
"last_name",
|
||||||
|
"first_name",
|
||||||
|
"inami_number",
|
||||||
|
"status",
|
||||||
|
"mfa",
|
||||||
|
"date_joined",
|
||||||
|
]
|
||||||
list_filter = ["status", "is_staff", "groups"]
|
list_filter = ["status", "is_staff", "groups"]
|
||||||
search_fields = ["email", "last_name", "first_name", "inami_number"]
|
search_fields = ["email", "last_name", "first_name", "inami_number"]
|
||||||
readonly_fields = ["date_joined", "last_login", "email_verified_at", "approved_at"]
|
readonly_fields = [
|
||||||
|
"date_joined",
|
||||||
|
"last_login",
|
||||||
|
"email_verified_at",
|
||||||
|
"approved_at",
|
||||||
|
"approved_by",
|
||||||
|
]
|
||||||
|
actions = ["approve", "refuse", "reset_mfa"]
|
||||||
fieldsets = [
|
fieldsets = [
|
||||||
(None, {"fields": ["email", "password"]}),
|
(None, {"fields": ["email", "password"]}),
|
||||||
("Identité", {"fields": ["first_name", "last_name", "inami_number"]}),
|
("Identité", {"fields": ["first_name", "last_name", "inami_number"]}),
|
||||||
@@ -23,7 +40,10 @@ class UserAdmin(BaseUserAdmin):
|
|||||||
"approved_at",
|
"approved_at",
|
||||||
"approved_by",
|
"approved_by",
|
||||||
"refusal_reason",
|
"refusal_reason",
|
||||||
]
|
],
|
||||||
|
"description": "Pour valider ou refuser une demande (avec envoi de l'e-mail), "
|
||||||
|
"utilisez les actions de la liste des utilisateurs. Le motif du refus "
|
||||||
|
"saisi ici est repris dans l'e-mail.",
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
("Droits", {"fields": ["is_staff", "is_superuser", "groups", "user_permissions"]}),
|
("Droits", {"fields": ["is_staff", "is_superuser", "groups", "user_permissions"]}),
|
||||||
@@ -39,6 +59,45 @@ class UserAdmin(BaseUserAdmin):
|
|||||||
),
|
),
|
||||||
]
|
]
|
||||||
|
|
||||||
|
@admin.display(boolean=True, description="2FA")
|
||||||
|
def mfa(self, user):
|
||||||
|
return services.mfa_enabled(user)
|
||||||
|
|
||||||
|
@admin.action(description="Valider les demandes sélectionnées (envoie l'e-mail)")
|
||||||
|
def approve(self, request, queryset):
|
||||||
|
pending = queryset.filter(status=User.Status.APPROVAL_PENDING)
|
||||||
|
for user in pending:
|
||||||
|
services.approve(user, by=request.user)
|
||||||
|
self._report(request, queryset, pending.count(), "validée(s)")
|
||||||
|
|
||||||
|
@admin.action(description="Refuser les demandes sélectionnées (envoie l'e-mail)")
|
||||||
|
def refuse(self, request, queryset):
|
||||||
|
pending = list(queryset.filter(status=User.Status.APPROVAL_PENDING))
|
||||||
|
for user in pending:
|
||||||
|
services.refuse(user, by=request.user, reason=user.refusal_reason)
|
||||||
|
self._report(request, queryset, len(pending), "refusée(s)")
|
||||||
|
|
||||||
|
@admin.action(description="Réinitialiser la double authentification")
|
||||||
|
def reset_mfa(self, request, queryset):
|
||||||
|
TOTPDevice.objects.filter(user__in=queryset).delete()
|
||||||
|
RecoveryCode.objects.filter(user__in=queryset).delete()
|
||||||
|
self.message_user(
|
||||||
|
request,
|
||||||
|
f"Double authentification réinitialisée pour {queryset.count()} compte(s).",
|
||||||
|
messages.SUCCESS,
|
||||||
|
)
|
||||||
|
|
||||||
|
def _report(self, request, queryset, done, verb):
|
||||||
|
skipped = queryset.count() - done
|
||||||
|
self.message_user(request, f"{done} demande(s) {verb}.", messages.SUCCESS)
|
||||||
|
if skipped:
|
||||||
|
self.message_user(
|
||||||
|
request,
|
||||||
|
f"{skipped} compte(s) ignoré(s) : seules les demandes « Validation en attente » "
|
||||||
|
"sont traitées.",
|
||||||
|
messages.WARNING,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@admin.register(MailEvent)
|
@admin.register(MailEvent)
|
||||||
class MailEventAdmin(admin.ModelAdmin):
|
class MailEventAdmin(admin.ModelAdmin):
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
"""E-mails transactionnels (specs §8 bis).
|
||||||
|
|
||||||
|
Chaque envoi est tracé dans `MailEvent` (type et statut, sans corps ni lien). Les messages
|
||||||
|
ne contiennent aucune donnée patient. L'envoi a lieu après validation de la transaction.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from django.conf import settings
|
||||||
|
from django.core.mail import EmailMultiAlternatives
|
||||||
|
from django.db import transaction
|
||||||
|
from django.template.loader import render_to_string
|
||||||
|
|
||||||
|
from .models import MailEvent, User
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
SUBJECTS = {
|
||||||
|
MailEvent.Type.CONFIRM_EMAIL: "Confirmez votre adresse e-mail",
|
||||||
|
MailEvent.Type.NEW_REQUEST: "Nouvelle demande de compte à valider",
|
||||||
|
MailEvent.Type.ACCOUNT_APPROVED: "Votre compte PRISM est activé",
|
||||||
|
MailEvent.Type.ACCOUNT_REFUSED: "Votre demande de compte PRISM",
|
||||||
|
MailEvent.Type.PASSWORD_RESET: "Réinitialisez votre mot de passe",
|
||||||
|
MailEvent.Type.PASSWORD_CHANGED: "Votre mot de passe a été modifié",
|
||||||
|
MailEvent.Type.MFA_CHANGED: "Double authentification modifiée",
|
||||||
|
MailEvent.Type.DUPLICATE_SIGNUP: "Tentative d'inscription avec votre adresse",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def frontend_url(path: str) -> str:
|
||||||
|
return f"{settings.FRONTEND_URL.rstrip('/')}{path}"
|
||||||
|
|
||||||
|
|
||||||
|
def send(
|
||||||
|
kind: MailEvent.Type,
|
||||||
|
user: User,
|
||||||
|
context: dict | None = None,
|
||||||
|
to: list[str] | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""Programme l'envoi après la transaction en cours."""
|
||||||
|
recipients = to or [user.email]
|
||||||
|
context = {"user": user, "login_url": frontend_url("/login"), **(context or {})}
|
||||||
|
transaction.on_commit(lambda: _deliver(kind, user, recipients, context))
|
||||||
|
|
||||||
|
|
||||||
|
def _deliver(kind: MailEvent.Type, user: User, recipients: list[str], context: dict) -> None:
|
||||||
|
subject = f"[PRISM] {SUBJECTS[kind]}"
|
||||||
|
text = render_to_string(f"accounts/emails/{kind}.txt", context)
|
||||||
|
html = render_to_string(
|
||||||
|
"accounts/emails/base.html",
|
||||||
|
{"subject": SUBJECTS[kind], "body": text, **context},
|
||||||
|
)
|
||||||
|
message = EmailMultiAlternatives(subject, text, settings.DEFAULT_FROM_EMAIL, recipients)
|
||||||
|
message.attach_alternative(html, "text/html")
|
||||||
|
try:
|
||||||
|
message.send()
|
||||||
|
except Exception as exc:
|
||||||
|
# Ni le message ni les liens ne sont journalisés (ils contiennent des jetons).
|
||||||
|
logger.error("Échec d'envoi de l'e-mail %s (%s)", kind, type(exc).__name__)
|
||||||
|
MailEvent.objects.create(
|
||||||
|
user=user, type=kind, status=MailEvent.Status.FAILED, error=type(exc).__name__
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
MailEvent.objects.create(user=user, type=kind, status=MailEvent.Status.SENT)
|
||||||
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,14 @@
|
|||||||
|
from django.core.management.base import BaseCommand
|
||||||
|
|
||||||
|
from accounts.services import purge_unconfirmed
|
||||||
|
|
||||||
|
|
||||||
|
class Command(BaseCommand):
|
||||||
|
help = "Supprime les demandes de compte dont l'adresse n'est pas confirmée après N jours."
|
||||||
|
|
||||||
|
def add_arguments(self, parser):
|
||||||
|
parser.add_argument("--days", type=int, default=7)
|
||||||
|
|
||||||
|
def handle(self, *args, days, **options):
|
||||||
|
deleted = purge_unconfirmed(days)
|
||||||
|
self.stdout.write(f"{deleted} demande(s) supprimée(s).")
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
# Generated by Django 5.2.19 on 2026-11-24 11:02
|
||||||
|
|
||||||
|
import django.db.models.deletion
|
||||||
|
from django.conf import settings
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('accounts', '0002_roles'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.CreateModel(
|
||||||
|
name='RecoveryCode',
|
||||||
|
fields=[
|
||||||
|
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||||
|
('code_hash', models.CharField(max_length=64, unique=True, verbose_name='empreinte')),
|
||||||
|
('used_at', models.DateTimeField(blank=True, null=True, verbose_name='utilisé le')),
|
||||||
|
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='recovery_codes', to=settings.AUTH_USER_MODEL, verbose_name='utilisateur')),
|
||||||
|
],
|
||||||
|
options={
|
||||||
|
'verbose_name': 'code de secours',
|
||||||
|
'verbose_name_plural': 'codes de secours',
|
||||||
|
},
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -123,3 +123,20 @@ class MailEvent(models.Model):
|
|||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return f"{self.get_type_display()} ({self.get_status_display()})"
|
return f"{self.get_type_display()} ({self.get_status_display()})"
|
||||||
|
|
||||||
|
|
||||||
|
class RecoveryCode(models.Model):
|
||||||
|
"""Code de secours de la 2FA, à usage unique, stocké haché (specs §4)."""
|
||||||
|
|
||||||
|
user = models.ForeignKey(
|
||||||
|
User, verbose_name="utilisateur", on_delete=models.CASCADE, related_name="recovery_codes"
|
||||||
|
)
|
||||||
|
code_hash = models.CharField("empreinte", max_length=64, unique=True)
|
||||||
|
used_at = models.DateTimeField("utilisé le", null=True, blank=True)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
verbose_name = "code de secours"
|
||||||
|
verbose_name_plural = "codes de secours"
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return f"Code de secours de {self.user.email}"
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
from django.contrib.auth.password_validation import validate_password
|
||||||
|
from rest_framework import serializers
|
||||||
|
|
||||||
|
from . import services
|
||||||
|
from .models import User
|
||||||
|
|
||||||
|
|
||||||
|
class LoginSerializer(serializers.Serializer):
|
||||||
|
email = serializers.EmailField()
|
||||||
|
password = serializers.CharField(trim_whitespace=False, style={"input_type": "password"})
|
||||||
|
|
||||||
|
|
||||||
|
class UserSerializer(serializers.ModelSerializer):
|
||||||
|
roles = serializers.SlugRelatedField(
|
||||||
|
source="groups", many=True, read_only=True, slug_field="name"
|
||||||
|
)
|
||||||
|
mfa_enabled = serializers.SerializerMethodField()
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = User
|
||||||
|
fields = ["email", "first_name", "last_name", "roles", "is_staff", "mfa_enabled"]
|
||||||
|
read_only_fields = fields
|
||||||
|
|
||||||
|
def get_mfa_enabled(self, user) -> bool:
|
||||||
|
return services.mfa_enabled(user)
|
||||||
|
|
||||||
|
|
||||||
|
class LoginResponseSerializer(serializers.Serializer):
|
||||||
|
mfa_required = serializers.BooleanField()
|
||||||
|
user = UserSerializer(allow_null=True)
|
||||||
|
|
||||||
|
|
||||||
|
class DetailSerializer(serializers.Serializer):
|
||||||
|
detail = serializers.CharField()
|
||||||
|
code = serializers.CharField(required=False)
|
||||||
|
|
||||||
|
|
||||||
|
class RegisterSerializer(serializers.Serializer):
|
||||||
|
first_name = serializers.CharField(max_length=150)
|
||||||
|
last_name = serializers.CharField(max_length=150)
|
||||||
|
email = serializers.EmailField()
|
||||||
|
inami_number = serializers.CharField(max_length=20, required=False, allow_blank=True)
|
||||||
|
password = serializers.CharField(trim_whitespace=False, style={"input_type": "password"})
|
||||||
|
accept_terms = serializers.BooleanField()
|
||||||
|
|
||||||
|
def validate_accept_terms(self, value):
|
||||||
|
if not value:
|
||||||
|
raise serializers.ValidationError(
|
||||||
|
"Vous devez accepter les conditions d'utilisation et la politique de "
|
||||||
|
"confidentialité."
|
||||||
|
)
|
||||||
|
return value
|
||||||
|
|
||||||
|
def validate(self, attrs):
|
||||||
|
candidate = User(
|
||||||
|
email=attrs["email"], first_name=attrs["first_name"], last_name=attrs["last_name"]
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
validate_password(attrs["password"], candidate)
|
||||||
|
except Exception as exc:
|
||||||
|
raise serializers.ValidationError({"password": list(exc.messages)}) from exc
|
||||||
|
return attrs
|
||||||
|
|
||||||
|
|
||||||
|
class TokenSerializer(serializers.Serializer):
|
||||||
|
token = serializers.CharField()
|
||||||
|
|
||||||
|
|
||||||
|
class ResendSerializer(serializers.Serializer):
|
||||||
|
email = serializers.EmailField(required=False)
|
||||||
|
token = serializers.CharField(required=False)
|
||||||
|
|
||||||
|
def validate(self, attrs):
|
||||||
|
if not attrs.get("email") and not attrs.get("token"):
|
||||||
|
raise serializers.ValidationError("Indiquez l'adresse e-mail.")
|
||||||
|
return attrs
|
||||||
|
|
||||||
|
|
||||||
|
class AccountStatusSerializer(serializers.Serializer):
|
||||||
|
status = serializers.ChoiceField(choices=User.Status.choices)
|
||||||
|
|
||||||
|
|
||||||
|
class CodeSerializer(serializers.Serializer):
|
||||||
|
code = serializers.CharField(max_length=20)
|
||||||
|
|
||||||
|
|
||||||
|
class DisableMfaSerializer(serializers.Serializer):
|
||||||
|
password = serializers.CharField(trim_whitespace=False)
|
||||||
|
code = serializers.CharField(max_length=20)
|
||||||
|
|
||||||
|
|
||||||
|
class TotpSetupSerializer(serializers.Serializer):
|
||||||
|
secret = serializers.CharField()
|
||||||
|
otpauth_url = serializers.CharField()
|
||||||
|
qr_code = serializers.CharField(help_text="Image SVG en data URI")
|
||||||
|
|
||||||
|
|
||||||
|
class RecoveryCodesSerializer(serializers.Serializer):
|
||||||
|
recovery_codes = serializers.ListField(child=serializers.CharField())
|
||||||
|
|
||||||
|
|
||||||
|
class PasswordChangeSerializer(serializers.Serializer):
|
||||||
|
current_password = serializers.CharField(trim_whitespace=False)
|
||||||
|
new_password = serializers.CharField(trim_whitespace=False)
|
||||||
|
|
||||||
|
def validate(self, attrs):
|
||||||
|
user = self.context["request"].user
|
||||||
|
if not user.check_password(attrs["current_password"]):
|
||||||
|
raise serializers.ValidationError(
|
||||||
|
{"current_password": ["Mot de passe actuel incorrect."]}
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
validate_password(attrs["new_password"], user)
|
||||||
|
except Exception as exc:
|
||||||
|
raise serializers.ValidationError({"new_password": list(exc.messages)}) from exc
|
||||||
|
return attrs
|
||||||
|
|
||||||
|
|
||||||
|
class PasswordResetRequestSerializer(serializers.Serializer):
|
||||||
|
email = serializers.EmailField()
|
||||||
|
|
||||||
|
|
||||||
|
class PasswordResetConfirmSerializer(serializers.Serializer):
|
||||||
|
token = serializers.CharField()
|
||||||
|
new_password = serializers.CharField(trim_whitespace=False)
|
||||||
@@ -0,0 +1,209 @@
|
|||||||
|
"""Cycle de vie des comptes et double authentification (specs §8, §8 bis)."""
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import secrets
|
||||||
|
from io import BytesIO
|
||||||
|
|
||||||
|
import qrcode
|
||||||
|
import qrcode.image.svg
|
||||||
|
from django.conf import settings
|
||||||
|
from django.db import transaction
|
||||||
|
from django.urls import reverse
|
||||||
|
from django.utils import timezone
|
||||||
|
from django_otp.plugins.otp_totp.models import TOTPDevice
|
||||||
|
|
||||||
|
from . import emails
|
||||||
|
from .models import MailEvent, RecoveryCode, User
|
||||||
|
from .tokens import make_email_token, make_reset_token
|
||||||
|
|
||||||
|
RECOVERY_CODE_COUNT = 8
|
||||||
|
# Alphabet sans caractères ambigus (0/O, 1/I/L).
|
||||||
|
RECOVERY_ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789"
|
||||||
|
|
||||||
|
|
||||||
|
# Inscription -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
@transaction.atomic
|
||||||
|
def register(*, email: str, password: str, first_name: str, last_name: str, inami_number=""):
|
||||||
|
"""Crée une demande de compte. Si l'adresse existe déjà, prévient son titulaire sans
|
||||||
|
rien révéler au demandeur (même réponse dans les deux cas)."""
|
||||||
|
email = email.lower()
|
||||||
|
existing = User.objects.filter(email=email).first()
|
||||||
|
if existing:
|
||||||
|
emails.send(MailEvent.Type.DUPLICATE_SIGNUP, existing)
|
||||||
|
return None
|
||||||
|
user = User.objects.create_user(
|
||||||
|
email,
|
||||||
|
password,
|
||||||
|
first_name=first_name,
|
||||||
|
last_name=last_name,
|
||||||
|
inami_number=inami_number,
|
||||||
|
)
|
||||||
|
send_confirmation(user)
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def send_confirmation(user: User) -> None:
|
||||||
|
link = emails.frontend_url(f"/inscription/statut?jeton={make_email_token(user)}")
|
||||||
|
emails.send(MailEvent.Type.CONFIRM_EMAIL, user, {"link": link})
|
||||||
|
|
||||||
|
|
||||||
|
@transaction.atomic
|
||||||
|
def confirm_email(user: User) -> None:
|
||||||
|
user.status = User.Status.APPROVAL_PENDING
|
||||||
|
user.email_verified_at = timezone.now()
|
||||||
|
user.save(update_fields=["status", "email_verified_at"])
|
||||||
|
recipients = settings.SSMG_NOTIFY_EMAILS
|
||||||
|
if recipients:
|
||||||
|
admin_url = settings.BACKEND_URL.rstrip("/") + reverse(
|
||||||
|
"admin:accounts_user_change", args=[user.pk]
|
||||||
|
)
|
||||||
|
emails.send(MailEvent.Type.NEW_REQUEST, user, {"admin_url": admin_url}, to=recipients)
|
||||||
|
|
||||||
|
|
||||||
|
@transaction.atomic
|
||||||
|
def approve(user: User, by: User) -> None:
|
||||||
|
user.status = User.Status.ACTIVE
|
||||||
|
user.approved_at = timezone.now()
|
||||||
|
user.approved_by = by
|
||||||
|
user.refusal_reason = ""
|
||||||
|
user.save(update_fields=["status", "approved_at", "approved_by", "refusal_reason"])
|
||||||
|
emails.send(MailEvent.Type.ACCOUNT_APPROVED, user)
|
||||||
|
|
||||||
|
|
||||||
|
@transaction.atomic
|
||||||
|
def refuse(user: User, by: User, reason: str = "") -> None:
|
||||||
|
user.status = User.Status.REFUSED
|
||||||
|
user.approved_by = by
|
||||||
|
user.refusal_reason = reason
|
||||||
|
user.save(update_fields=["status", "approved_by", "refusal_reason"])
|
||||||
|
emails.send(MailEvent.Type.ACCOUNT_REFUSED, user)
|
||||||
|
|
||||||
|
|
||||||
|
def purge_unconfirmed(days: int = 7) -> int:
|
||||||
|
"""Supprime les demandes dont l'adresse n'a pas été confirmée (specs §8 bis)."""
|
||||||
|
limit = timezone.now() - timezone.timedelta(days=days)
|
||||||
|
deleted, _ = User.objects.filter(
|
||||||
|
status=User.Status.EMAIL_PENDING, date_joined__lt=limit
|
||||||
|
).delete()
|
||||||
|
return deleted
|
||||||
|
|
||||||
|
|
||||||
|
def request_password_reset(email: str) -> None:
|
||||||
|
"""Envoie le lien de réinitialisation si un compte actif existe (rien sinon)."""
|
||||||
|
user = User.objects.filter(email=email.lower(), status=User.Status.ACTIVE).first()
|
||||||
|
if user is None:
|
||||||
|
return
|
||||||
|
link = emails.frontend_url(f"/reinitialisation/{make_reset_token(user)}")
|
||||||
|
emails.send(MailEvent.Type.PASSWORD_RESET, user, {"link": link})
|
||||||
|
|
||||||
|
|
||||||
|
@transaction.atomic
|
||||||
|
def change_password(user: User, new_password: str) -> None:
|
||||||
|
user.set_password(new_password)
|
||||||
|
user.save(update_fields=["password"])
|
||||||
|
emails.send(MailEvent.Type.PASSWORD_CHANGED, user)
|
||||||
|
|
||||||
|
|
||||||
|
# Double authentification --------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def confirmed_device(user: User) -> TOTPDevice | None:
|
||||||
|
return TOTPDevice.objects.filter(user=user, confirmed=True).first()
|
||||||
|
|
||||||
|
|
||||||
|
def mfa_enabled(user: User) -> bool:
|
||||||
|
return TOTPDevice.objects.filter(user=user, confirmed=True).exists()
|
||||||
|
|
||||||
|
|
||||||
|
def start_totp_setup(user: User) -> dict:
|
||||||
|
"""Crée un appareil TOTP non confirmé (remplace une tentative précédente)."""
|
||||||
|
TOTPDevice.objects.filter(user=user, confirmed=False).delete()
|
||||||
|
device = TOTPDevice.objects.create(user=user, name="Application", confirmed=False)
|
||||||
|
secret = base64.b32encode(device.bin_key).decode().rstrip("=")
|
||||||
|
return {
|
||||||
|
"secret": " ".join(secret[i : i + 4] for i in range(0, len(secret), 4)),
|
||||||
|
"otpauth_url": device.config_url,
|
||||||
|
"qr_code": qr_data_uri(device.config_url),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def qr_data_uri(data: str) -> str:
|
||||||
|
image = qrcode.make(data, image_factory=qrcode.image.svg.SvgPathImage, box_size=10)
|
||||||
|
buffer = BytesIO()
|
||||||
|
image.save(buffer)
|
||||||
|
return "data:image/svg+xml;base64," + base64.b64encode(buffer.getvalue()).decode()
|
||||||
|
|
||||||
|
|
||||||
|
@transaction.atomic
|
||||||
|
def enable_totp(user: User, code: str) -> list[str] | None:
|
||||||
|
"""Confirme l'appareil avec un premier code ; renvoie les codes de secours."""
|
||||||
|
device = TOTPDevice.objects.filter(user=user, confirmed=False).first()
|
||||||
|
if device is None or not device.verify_token(normalize_code(code)):
|
||||||
|
return None
|
||||||
|
device.confirmed = True
|
||||||
|
device.save(update_fields=["confirmed"])
|
||||||
|
codes = _new_recovery_codes(user)
|
||||||
|
emails.send(
|
||||||
|
MailEvent.Type.MFA_CHANGED,
|
||||||
|
user,
|
||||||
|
{"change": "La double authentification a été activée sur votre compte PRISM."},
|
||||||
|
)
|
||||||
|
return codes
|
||||||
|
|
||||||
|
|
||||||
|
@transaction.atomic
|
||||||
|
def disable_totp(user: User) -> None:
|
||||||
|
TOTPDevice.objects.filter(user=user).delete()
|
||||||
|
RecoveryCode.objects.filter(user=user).delete()
|
||||||
|
emails.send(
|
||||||
|
MailEvent.Type.MFA_CHANGED,
|
||||||
|
user,
|
||||||
|
{"change": "La double authentification a été désactivée sur votre compte PRISM."},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@transaction.atomic
|
||||||
|
def regenerate_recovery_codes(user: User) -> list[str]:
|
||||||
|
codes = _new_recovery_codes(user)
|
||||||
|
emails.send(
|
||||||
|
MailEvent.Type.MFA_CHANGED,
|
||||||
|
user,
|
||||||
|
{"change": "De nouveaux codes de secours ont été générés ; les anciens ne valent plus."},
|
||||||
|
)
|
||||||
|
return codes
|
||||||
|
|
||||||
|
|
||||||
|
def verify_second_factor(user: User, code: str) -> TOTPDevice | None:
|
||||||
|
"""Vérifie un code TOTP ou un code de secours (consommé). Renvoie l'appareil TOTP."""
|
||||||
|
device = confirmed_device(user)
|
||||||
|
if device is None:
|
||||||
|
return None
|
||||||
|
code = normalize_code(code)
|
||||||
|
if code.isdigit() and len(code) == 6:
|
||||||
|
return device if device.verify_token(code) else None
|
||||||
|
used = RecoveryCode.objects.filter(
|
||||||
|
user=user, code_hash=_hash(code), used_at__isnull=True
|
||||||
|
).update(used_at=timezone.now())
|
||||||
|
return device if used else None
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_code(code: str) -> str:
|
||||||
|
return code.replace(" ", "").replace("-", "").upper()
|
||||||
|
|
||||||
|
|
||||||
|
def _new_recovery_codes(user: User) -> list[str]:
|
||||||
|
RecoveryCode.objects.filter(user=user).delete()
|
||||||
|
codes = []
|
||||||
|
for _ in range(RECOVERY_CODE_COUNT):
|
||||||
|
raw = "".join(secrets.choice(RECOVERY_ALPHABET) for _ in range(8))
|
||||||
|
codes.append(f"{raw[:4]}-{raw[4:]}")
|
||||||
|
RecoveryCode.objects.create(user=user, code_hash=_hash(raw))
|
||||||
|
return codes
|
||||||
|
|
||||||
|
|
||||||
|
def _hash(code: str) -> str:
|
||||||
|
# Codes aléatoires de 40 bits : un SHA-256 suffit (pas d'attaque par dictionnaire).
|
||||||
|
return hashlib.sha256(normalize_code(code).encode()).hexdigest()
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{% autoescape off %}Bonjour {{ user.first_name }},
|
||||||
|
|
||||||
|
Votre compte PRISM a été validé par la cellule Environnement de la SSMG. Vous pouvez vous connecter :
|
||||||
|
|
||||||
|
{{ login_url }}
|
||||||
|
|
||||||
|
Nous vous recommandons d'activer la double authentification depuis la page « Mon compte ».
|
||||||
|
{% endautoescape %}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{% autoescape off %}Bonjour {{ user.first_name }},
|
||||||
|
|
||||||
|
Votre demande de compte PRISM n'a pas pu être acceptée par la cellule Environnement de la SSMG.{% if user.refusal_reason %}
|
||||||
|
|
||||||
|
Motif : {{ user.refusal_reason }}{% endif %}
|
||||||
|
|
||||||
|
Pour toute question, contactez la SSMG.
|
||||||
|
{% endautoescape %}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="fr">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<title>{{ subject }}</title>
|
||||||
|
</head>
|
||||||
|
<body style="margin:0;padding:0;background:#f6f4f2;font-family:Roboto,Arial,sans-serif;color:#464d5f;">
|
||||||
|
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f6f4f2;padding:32px 16px;">
|
||||||
|
<tr>
|
||||||
|
<td align="center">
|
||||||
|
<table role="presentation" width="560" cellpadding="0" cellspacing="0" style="max-width:560px;background:#ffffff;border:1px solid #d9d4d0;border-top:4px solid #e85b25;border-radius:12px;">
|
||||||
|
<tr>
|
||||||
|
<td style="padding:28px 32px;">
|
||||||
|
<p style="margin:0 0 4px;font-size:20px;font-weight:700;color:#092933;">PRISM</p>
|
||||||
|
<p style="margin:0 0 24px;font-size:12px;color:#6b7280;">Environnement et santé</p>
|
||||||
|
<h1 style="margin:0 0 16px;font-size:18px;color:#092933;">{{ subject }}</h1>
|
||||||
|
<div style="font-size:14px;line-height:1.5;">{{ body|urlize|linebreaksbr }}</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td style="padding:16px 32px;background:#092933;border-radius:0 0 12px 12px;color:#ffffff;font-size:12px;">
|
||||||
|
Outil complémentaire d'aide à la consultation : il ne remplace pas un diagnostic.<br />
|
||||||
|
<span style="color:#74c5da;">© SSMG – Société Scientifique de Médecine Générale</span>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
{% autoescape off %}Bonjour {{ user.first_name }},
|
||||||
|
|
||||||
|
Merci pour votre demande de compte PRISM. Pour confirmer votre adresse e-mail, ouvrez ce lien (valable 24 heures) :
|
||||||
|
|
||||||
|
{{ link }}
|
||||||
|
|
||||||
|
Votre demande sera ensuite examinée par la cellule Environnement de la SSMG.
|
||||||
|
|
||||||
|
Si vous n'êtes pas à l'origine de cette demande, ignorez ce message.
|
||||||
|
{% endautoescape %}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
{% autoescape off %}Bonjour {{ user.first_name }},
|
||||||
|
|
||||||
|
Quelqu'un a tenté de créer un compte PRISM avec votre adresse e-mail, qui est déjà associée à un compte.
|
||||||
|
|
||||||
|
Si c'était vous, connectez-vous ici (ou utilisez « Mot de passe oublié ») :
|
||||||
|
{{ login_url }}
|
||||||
|
|
||||||
|
Sinon, vous pouvez ignorer ce message.
|
||||||
|
{% endautoescape %}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
{% autoescape off %}Bonjour {{ user.first_name }},
|
||||||
|
|
||||||
|
{{ change }}
|
||||||
|
|
||||||
|
Si vous n'êtes pas à l'origine de cette modification, contactez la SSMG sans attendre.
|
||||||
|
{% endautoescape %}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
{% autoescape off %}Une nouvelle demande de compte PRISM attend votre validation.
|
||||||
|
|
||||||
|
Nom : {{ user.first_name }} {{ user.last_name }}
|
||||||
|
E-mail : {{ user.email }}
|
||||||
|
N° INAMI : {{ user.inami_number|default:"non renseigné" }}
|
||||||
|
|
||||||
|
Valider ou refuser la demande :
|
||||||
|
{{ admin_url }}
|
||||||
|
{% endautoescape %}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
{% autoescape off %}Bonjour {{ user.first_name }},
|
||||||
|
|
||||||
|
Le mot de passe de votre compte PRISM vient d'être modifié.
|
||||||
|
|
||||||
|
Si vous n'êtes pas à l'origine de ce changement, contactez la SSMG sans attendre.
|
||||||
|
{% endautoescape %}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{% autoescape off %}Bonjour {{ user.first_name }},
|
||||||
|
|
||||||
|
Pour choisir un nouveau mot de passe PRISM, ouvrez ce lien (valable 1 heure, utilisable une seule fois) :
|
||||||
|
|
||||||
|
{{ link }}
|
||||||
|
|
||||||
|
Si vous n'avez rien demandé, ignorez ce message : votre mot de passe reste inchangé.
|
||||||
|
{% endautoescape %}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
"""Jetons signés envoyés par e-mail (specs §8 bis).
|
||||||
|
|
||||||
|
Les jetons ne sont jamais stockés ni journalisés. L'usage unique découle de l'état du compte :
|
||||||
|
un jeton de confirmation n'est accepté que si l'adresse est encore « en attente », un jeton
|
||||||
|
de réinitialisation que si le mot de passe n'a pas changé depuis son émission.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from django.conf import settings
|
||||||
|
from django.contrib.auth.tokens import default_token_generator
|
||||||
|
from django.core import signing
|
||||||
|
from django.utils.encoding import force_bytes
|
||||||
|
from django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode
|
||||||
|
|
||||||
|
from .models import User
|
||||||
|
|
||||||
|
EMAIL_SALT = "prism.accounts.verify-email"
|
||||||
|
|
||||||
|
|
||||||
|
class InvalidToken(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class ExpiredToken(Exception):
|
||||||
|
def __init__(self, user: User | None):
|
||||||
|
super().__init__("Jeton expiré")
|
||||||
|
self.user = user
|
||||||
|
|
||||||
|
|
||||||
|
def make_email_token(user: User) -> str:
|
||||||
|
return signing.dumps({"u": user.pk, "e": user.email}, salt=EMAIL_SALT)
|
||||||
|
|
||||||
|
|
||||||
|
def read_email_token(token: str) -> User:
|
||||||
|
"""Renvoie l'utilisateur du jeton ; lève `ExpiredToken` ou `InvalidToken`."""
|
||||||
|
try:
|
||||||
|
data = signing.loads(token, salt=EMAIL_SALT, max_age=settings.EMAIL_TOKEN_MAX_AGE)
|
||||||
|
except signing.SignatureExpired as exc:
|
||||||
|
# La signature est valide : on retrouve le compte pour pouvoir renvoyer l'e-mail.
|
||||||
|
data = signing.loads(token, salt=EMAIL_SALT)
|
||||||
|
raise ExpiredToken(_user(data)) from exc
|
||||||
|
except signing.BadSignature as exc:
|
||||||
|
raise InvalidToken from exc
|
||||||
|
user = _user(data)
|
||||||
|
if user is None:
|
||||||
|
raise InvalidToken
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def _user(data: dict) -> User | None:
|
||||||
|
return User.objects.filter(pk=data.get("u"), email=data.get("e")).first()
|
||||||
|
|
||||||
|
|
||||||
|
# Réinitialisation du mot de passe ------------------------------------------------------
|
||||||
|
#
|
||||||
|
# Jeton de Django (`PasswordResetTokenGenerator`) : il expire après PASSWORD_RESET_TIMEOUT et
|
||||||
|
# devient invalide dès que le mot de passe change, ce qui le rend à usage unique.
|
||||||
|
|
||||||
|
|
||||||
|
def make_reset_token(user: User) -> str:
|
||||||
|
uid = urlsafe_base64_encode(force_bytes(user.pk))
|
||||||
|
return f"{uid}.{default_token_generator.make_token(user)}"
|
||||||
|
|
||||||
|
|
||||||
|
def read_reset_token(token: str) -> User:
|
||||||
|
"""Renvoie l'utilisateur actif du jeton ; lève `InvalidToken` (expiré, utilisé ou faux)."""
|
||||||
|
uid, _, value = token.partition(".")
|
||||||
|
try:
|
||||||
|
pk = urlsafe_base64_decode(uid).decode()
|
||||||
|
user = User.objects.get(pk=pk, status=User.Status.ACTIVE)
|
||||||
|
except (ValueError, TypeError, OverflowError, User.DoesNotExist) as exc:
|
||||||
|
raise InvalidToken from exc
|
||||||
|
if not default_token_generator.check_token(user, value):
|
||||||
|
raise InvalidToken
|
||||||
|
return user
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
from django.urls import path
|
||||||
|
|
||||||
|
from . import views
|
||||||
|
|
||||||
|
urlpatterns = [
|
||||||
|
path("login/", views.LoginView.as_view(), name="login"),
|
||||||
|
path("2fa/verify/", views.MfaVerifyView.as_view(), name="mfa-verify"),
|
||||||
|
path("logout/", views.LogoutView.as_view(), name="logout"),
|
||||||
|
path("me/", views.MeView.as_view(), name="me"),
|
||||||
|
path("register/", views.RegisterView.as_view(), name="register"),
|
||||||
|
path("verify-email/", views.VerifyEmailView.as_view(), name="verify-email"),
|
||||||
|
path("verify-email/resend/", views.ResendVerificationView.as_view(), name="verify-resend"),
|
||||||
|
path("password/change/", views.PasswordChangeView.as_view(), name="password-change"),
|
||||||
|
path("password-reset/", views.PasswordResetView.as_view(), name="password-reset"),
|
||||||
|
path(
|
||||||
|
"password-reset/validate/",
|
||||||
|
views.PasswordResetValidateView.as_view(),
|
||||||
|
name="password-reset-validate",
|
||||||
|
),
|
||||||
|
path(
|
||||||
|
"password-reset/confirm/",
|
||||||
|
views.PasswordResetConfirmView.as_view(),
|
||||||
|
name="password-reset-confirm",
|
||||||
|
),
|
||||||
|
path("2fa/setup/", views.TotpSetupView.as_view(), name="mfa-setup"),
|
||||||
|
path("2fa/enable/", views.TotpEnableView.as_view(), name="mfa-enable"),
|
||||||
|
path("2fa/disable/", views.TotpDisableView.as_view(), name="mfa-disable"),
|
||||||
|
path("2fa/recovery-codes/", views.RecoveryCodesView.as_view(), name="mfa-recovery-codes"),
|
||||||
|
]
|
||||||
@@ -0,0 +1,382 @@
|
|||||||
|
"""Routes d'authentification (specs §5, §8, §8 bis)."""
|
||||||
|
|
||||||
|
import time
|
||||||
|
|
||||||
|
from django.conf import settings
|
||||||
|
from django.contrib.auth import authenticate, login, logout, update_session_auth_hash
|
||||||
|
from django.contrib.auth.password_validation import validate_password
|
||||||
|
from django.core.exceptions import ValidationError
|
||||||
|
from django.utils.decorators import method_decorator
|
||||||
|
from django.views.decorators.csrf import csrf_protect, ensure_csrf_cookie
|
||||||
|
from django_otp import login as otp_login
|
||||||
|
from drf_spectacular.utils import OpenApiResponse, extend_schema
|
||||||
|
from rest_framework import status
|
||||||
|
from rest_framework.permissions import AllowAny
|
||||||
|
from rest_framework.response import Response
|
||||||
|
from rest_framework.throttling import ScopedRateThrottle
|
||||||
|
from rest_framework.views import APIView
|
||||||
|
|
||||||
|
from . import services
|
||||||
|
from .models import User
|
||||||
|
from .serializers import (
|
||||||
|
AccountStatusSerializer,
|
||||||
|
CodeSerializer,
|
||||||
|
DetailSerializer,
|
||||||
|
DisableMfaSerializer,
|
||||||
|
LoginResponseSerializer,
|
||||||
|
LoginSerializer,
|
||||||
|
PasswordChangeSerializer,
|
||||||
|
PasswordResetConfirmSerializer,
|
||||||
|
PasswordResetRequestSerializer,
|
||||||
|
RecoveryCodesSerializer,
|
||||||
|
RegisterSerializer,
|
||||||
|
ResendSerializer,
|
||||||
|
TokenSerializer,
|
||||||
|
TotpSetupSerializer,
|
||||||
|
UserSerializer,
|
||||||
|
)
|
||||||
|
from .tokens import ExpiredToken, InvalidToken, read_email_token, read_reset_token
|
||||||
|
|
||||||
|
# Messages identiques quel que soit le motif : pas d'indication sur l'existence d'un compte.
|
||||||
|
INVALID_CREDENTIALS = "E-mail ou mot de passe incorrect."
|
||||||
|
INVALID_CODE = "Code incorrect ou expiré."
|
||||||
|
|
||||||
|
# Clés de session de la connexion en deux étapes.
|
||||||
|
MFA_USER = "prism_mfa_user"
|
||||||
|
MFA_STARTED = "prism_mfa_started"
|
||||||
|
|
||||||
|
|
||||||
|
def error(detail: str, code: str | None = None, http_status=status.HTTP_400_BAD_REQUEST):
|
||||||
|
body = {"detail": detail}
|
||||||
|
if code:
|
||||||
|
body["code"] = code
|
||||||
|
return Response(body, status=http_status)
|
||||||
|
|
||||||
|
|
||||||
|
class PublicView(APIView):
|
||||||
|
"""Route publique, protégée par CSRF et limitée en débit."""
|
||||||
|
|
||||||
|
permission_classes = [AllowAny]
|
||||||
|
authentication_classes = []
|
||||||
|
throttle_classes = [ScopedRateThrottle]
|
||||||
|
|
||||||
|
@method_decorator(csrf_protect)
|
||||||
|
def dispatch(self, *args, **kwargs):
|
||||||
|
return super().dispatch(*args, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
# Connexion ----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
class LoginView(PublicView):
|
||||||
|
throttle_scope = "login"
|
||||||
|
|
||||||
|
@extend_schema(
|
||||||
|
request=LoginSerializer,
|
||||||
|
responses={
|
||||||
|
200: LoginResponseSerializer,
|
||||||
|
400: OpenApiResponse(DetailSerializer, description="Identifiants invalides"),
|
||||||
|
},
|
||||||
|
summary="Connexion (étape 1)",
|
||||||
|
description="Si la 2FA est active, renvoie `mfa_required: true` sans ouvrir de session.",
|
||||||
|
)
|
||||||
|
def post(self, request):
|
||||||
|
serializer = LoginSerializer(data=request.data)
|
||||||
|
serializer.is_valid(raise_exception=True)
|
||||||
|
user = authenticate(
|
||||||
|
request,
|
||||||
|
email=serializer.validated_data["email"].lower(),
|
||||||
|
password=serializer.validated_data["password"],
|
||||||
|
)
|
||||||
|
if user is None:
|
||||||
|
return error(INVALID_CREDENTIALS)
|
||||||
|
if services.mfa_enabled(user):
|
||||||
|
request.session.cycle_key()
|
||||||
|
request.session[MFA_USER] = user.pk
|
||||||
|
request.session[MFA_STARTED] = int(time.time())
|
||||||
|
return Response({"mfa_required": True, "user": None})
|
||||||
|
login(request, user)
|
||||||
|
return Response({"mfa_required": False, "user": UserSerializer(user).data})
|
||||||
|
|
||||||
|
|
||||||
|
class MfaVerifyView(PublicView):
|
||||||
|
throttle_scope = "mfa"
|
||||||
|
|
||||||
|
@extend_schema(
|
||||||
|
request=CodeSerializer,
|
||||||
|
responses={
|
||||||
|
200: LoginResponseSerializer,
|
||||||
|
400: OpenApiResponse(DetailSerializer, description="Code invalide ou étape expirée"),
|
||||||
|
},
|
||||||
|
summary="Connexion (étape 2) : code TOTP ou code de secours",
|
||||||
|
)
|
||||||
|
def post(self, request):
|
||||||
|
serializer = CodeSerializer(data=request.data)
|
||||||
|
serializer.is_valid(raise_exception=True)
|
||||||
|
user_id = request.session.get(MFA_USER)
|
||||||
|
started = request.session.get(MFA_STARTED, 0)
|
||||||
|
if not user_id or time.time() - started > settings.MFA_STEP_MAX_AGE:
|
||||||
|
return error("Recommencez la connexion.", "mfa_expired")
|
||||||
|
user = User.objects.filter(pk=user_id, status=User.Status.ACTIVE).first()
|
||||||
|
device = user and services.verify_second_factor(user, serializer.validated_data["code"])
|
||||||
|
if not device:
|
||||||
|
return error(INVALID_CODE, "invalid_code")
|
||||||
|
for key in (MFA_USER, MFA_STARTED):
|
||||||
|
request.session.pop(key, None)
|
||||||
|
login(request, user, backend="django.contrib.auth.backends.ModelBackend")
|
||||||
|
otp_login(request, device)
|
||||||
|
return Response({"mfa_required": False, "user": UserSerializer(user).data})
|
||||||
|
|
||||||
|
|
||||||
|
class LogoutView(APIView):
|
||||||
|
@extend_schema(request=None, responses={204: None}, summary="Déconnexion")
|
||||||
|
def post(self, request):
|
||||||
|
logout(request)
|
||||||
|
return Response(status=status.HTTP_204_NO_CONTENT)
|
||||||
|
|
||||||
|
|
||||||
|
@method_decorator(ensure_csrf_cookie, name="dispatch")
|
||||||
|
class MeView(APIView):
|
||||||
|
"""Utilisateur courant. Dépose aussi le cookie CSRF dont le front a besoin."""
|
||||||
|
|
||||||
|
@extend_schema(responses=UserSerializer, summary="Utilisateur courant")
|
||||||
|
def get(self, request):
|
||||||
|
return Response(UserSerializer(request.user).data)
|
||||||
|
|
||||||
|
|
||||||
|
# Inscription --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
class RegisterView(PublicView):
|
||||||
|
throttle_scope = "register"
|
||||||
|
|
||||||
|
@extend_schema(
|
||||||
|
request=RegisterSerializer,
|
||||||
|
responses={201: None},
|
||||||
|
summary="Demande de compte",
|
||||||
|
description="Réponse identique si l'adresse est déjà utilisée (son titulaire est "
|
||||||
|
"prévenu par e-mail).",
|
||||||
|
)
|
||||||
|
def post(self, request):
|
||||||
|
serializer = RegisterSerializer(data=request.data)
|
||||||
|
serializer.is_valid(raise_exception=True)
|
||||||
|
data = serializer.validated_data
|
||||||
|
services.register(
|
||||||
|
email=data["email"],
|
||||||
|
password=data["password"],
|
||||||
|
first_name=data["first_name"],
|
||||||
|
last_name=data["last_name"],
|
||||||
|
inami_number=data.get("inami_number", ""),
|
||||||
|
)
|
||||||
|
return Response(status=status.HTTP_201_CREATED)
|
||||||
|
|
||||||
|
|
||||||
|
class VerifyEmailView(PublicView):
|
||||||
|
throttle_scope = "register"
|
||||||
|
|
||||||
|
@extend_schema(
|
||||||
|
request=TokenSerializer,
|
||||||
|
responses={
|
||||||
|
200: AccountStatusSerializer,
|
||||||
|
400: OpenApiResponse(
|
||||||
|
DetailSerializer, description="`invalid_token`, `expired_token` ou `used_token`"
|
||||||
|
),
|
||||||
|
},
|
||||||
|
summary="Confirmer l'adresse e-mail",
|
||||||
|
)
|
||||||
|
def post(self, request):
|
||||||
|
serializer = TokenSerializer(data=request.data)
|
||||||
|
serializer.is_valid(raise_exception=True)
|
||||||
|
try:
|
||||||
|
user = read_email_token(serializer.validated_data["token"])
|
||||||
|
except ExpiredToken:
|
||||||
|
return error("Ce lien a expiré.", "expired_token")
|
||||||
|
except InvalidToken:
|
||||||
|
return error("Ce lien n'est pas valide.", "invalid_token")
|
||||||
|
if user.status != User.Status.EMAIL_PENDING:
|
||||||
|
return error("Ce lien a déjà été utilisé.", "used_token")
|
||||||
|
services.confirm_email(user)
|
||||||
|
return Response({"status": user.status})
|
||||||
|
|
||||||
|
|
||||||
|
class ResendVerificationView(PublicView):
|
||||||
|
throttle_scope = "register"
|
||||||
|
|
||||||
|
@extend_schema(
|
||||||
|
request=ResendSerializer,
|
||||||
|
responses={202: None},
|
||||||
|
summary="Renvoyer l'e-mail de confirmation",
|
||||||
|
description="Par adresse e-mail ou par un lien expiré. Réponse toujours identique.",
|
||||||
|
)
|
||||||
|
def post(self, request):
|
||||||
|
serializer = ResendSerializer(data=request.data)
|
||||||
|
serializer.is_valid(raise_exception=True)
|
||||||
|
user = None
|
||||||
|
if token := serializer.validated_data.get("token"):
|
||||||
|
try:
|
||||||
|
user = read_email_token(token)
|
||||||
|
except ExpiredToken as exc:
|
||||||
|
user = exc.user
|
||||||
|
except InvalidToken:
|
||||||
|
user = None
|
||||||
|
else:
|
||||||
|
user = User.objects.filter(email=serializer.validated_data["email"].lower()).first()
|
||||||
|
if user and user.status == User.Status.EMAIL_PENDING:
|
||||||
|
services.send_confirmation(user)
|
||||||
|
return Response(status=status.HTTP_202_ACCEPTED)
|
||||||
|
|
||||||
|
|
||||||
|
# Compte -------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
class PasswordChangeView(APIView):
|
||||||
|
@extend_schema(
|
||||||
|
request=PasswordChangeSerializer, responses={204: None}, summary="Changer son mot de passe"
|
||||||
|
)
|
||||||
|
def post(self, request):
|
||||||
|
serializer = PasswordChangeSerializer(data=request.data, context={"request": request})
|
||||||
|
serializer.is_valid(raise_exception=True)
|
||||||
|
services.change_password(request.user, serializer.validated_data["new_password"])
|
||||||
|
update_session_auth_hash(request, request.user)
|
||||||
|
return Response(status=status.HTTP_204_NO_CONTENT)
|
||||||
|
|
||||||
|
|
||||||
|
class TotpSetupView(APIView):
|
||||||
|
@extend_schema(request=None, responses=TotpSetupSerializer, summary="Démarrer l'activation 2FA")
|
||||||
|
def post(self, request):
|
||||||
|
if services.mfa_enabled(request.user):
|
||||||
|
return error("La double authentification est déjà active.", "mfa_enabled")
|
||||||
|
return Response(services.start_totp_setup(request.user))
|
||||||
|
|
||||||
|
|
||||||
|
class TotpEnableView(APIView):
|
||||||
|
throttle_classes = [ScopedRateThrottle]
|
||||||
|
throttle_scope = "mfa"
|
||||||
|
|
||||||
|
@extend_schema(
|
||||||
|
request=CodeSerializer,
|
||||||
|
responses={200: RecoveryCodesSerializer, 400: DetailSerializer},
|
||||||
|
summary="Confirmer l'activation 2FA ; renvoie les codes de secours (une seule fois)",
|
||||||
|
)
|
||||||
|
def post(self, request):
|
||||||
|
serializer = CodeSerializer(data=request.data)
|
||||||
|
serializer.is_valid(raise_exception=True)
|
||||||
|
codes = services.enable_totp(request.user, serializer.validated_data["code"])
|
||||||
|
if codes is None:
|
||||||
|
return error(INVALID_CODE, "invalid_code")
|
||||||
|
otp_login(request, services.confirmed_device(request.user))
|
||||||
|
return Response({"recovery_codes": codes})
|
||||||
|
|
||||||
|
|
||||||
|
class TotpDisableView(APIView):
|
||||||
|
throttle_classes = [ScopedRateThrottle]
|
||||||
|
throttle_scope = "mfa"
|
||||||
|
|
||||||
|
@extend_schema(
|
||||||
|
request=DisableMfaSerializer,
|
||||||
|
responses={204: None, 400: DetailSerializer},
|
||||||
|
summary="Désactiver la 2FA (mot de passe et code requis)",
|
||||||
|
)
|
||||||
|
def post(self, request):
|
||||||
|
serializer = DisableMfaSerializer(data=request.data)
|
||||||
|
serializer.is_valid(raise_exception=True)
|
||||||
|
user = request.user
|
||||||
|
if user.is_staff:
|
||||||
|
return error(
|
||||||
|
"La double authentification est obligatoire pour ce compte.", "mfa_mandatory"
|
||||||
|
)
|
||||||
|
if not user.check_password(serializer.validated_data["password"]):
|
||||||
|
return error(INVALID_CREDENTIALS, "invalid_password")
|
||||||
|
if not services.verify_second_factor(user, serializer.validated_data["code"]):
|
||||||
|
return error(INVALID_CODE, "invalid_code")
|
||||||
|
services.disable_totp(user)
|
||||||
|
return Response(status=status.HTTP_204_NO_CONTENT)
|
||||||
|
|
||||||
|
|
||||||
|
class RecoveryCodesView(APIView):
|
||||||
|
throttle_classes = [ScopedRateThrottle]
|
||||||
|
throttle_scope = "mfa"
|
||||||
|
|
||||||
|
@extend_schema(
|
||||||
|
request=CodeSerializer,
|
||||||
|
responses={200: RecoveryCodesSerializer, 400: DetailSerializer},
|
||||||
|
summary="Régénérer les codes de secours (code TOTP requis)",
|
||||||
|
)
|
||||||
|
def post(self, request):
|
||||||
|
serializer = CodeSerializer(data=request.data)
|
||||||
|
serializer.is_valid(raise_exception=True)
|
||||||
|
code = services.normalize_code(serializer.validated_data["code"])
|
||||||
|
device = services.confirmed_device(request.user)
|
||||||
|
if device is None or not (code.isdigit() and device.verify_token(code)):
|
||||||
|
return error(INVALID_CODE, "invalid_code")
|
||||||
|
return Response({"recovery_codes": services.regenerate_recovery_codes(request.user)})
|
||||||
|
|
||||||
|
|
||||||
|
# Mot de passe oublié -------------------------------------------------------------------
|
||||||
|
|
||||||
|
INVALID_RESET_LINK = "Ce lien de réinitialisation n'est plus valable."
|
||||||
|
|
||||||
|
|
||||||
|
class PasswordResetView(PublicView):
|
||||||
|
throttle_scope = "password_reset"
|
||||||
|
|
||||||
|
@extend_schema(
|
||||||
|
request=PasswordResetRequestSerializer,
|
||||||
|
responses={202: None},
|
||||||
|
summary="Demander un lien de réinitialisation",
|
||||||
|
description="Réponse identique que l'adresse corresponde ou non à un compte actif.",
|
||||||
|
)
|
||||||
|
def post(self, request):
|
||||||
|
serializer = PasswordResetRequestSerializer(data=request.data)
|
||||||
|
serializer.is_valid(raise_exception=True)
|
||||||
|
services.request_password_reset(serializer.validated_data["email"])
|
||||||
|
return Response(status=status.HTTP_202_ACCEPTED)
|
||||||
|
|
||||||
|
|
||||||
|
class PasswordResetValidateView(PublicView):
|
||||||
|
throttle_scope = "password_reset"
|
||||||
|
|
||||||
|
@extend_schema(
|
||||||
|
request=TokenSerializer,
|
||||||
|
responses={
|
||||||
|
204: None,
|
||||||
|
400: OpenApiResponse(DetailSerializer, description="`invalid_token`"),
|
||||||
|
},
|
||||||
|
summary="Vérifier un lien de réinitialisation avant d'afficher le formulaire",
|
||||||
|
)
|
||||||
|
def post(self, request):
|
||||||
|
serializer = TokenSerializer(data=request.data)
|
||||||
|
serializer.is_valid(raise_exception=True)
|
||||||
|
try:
|
||||||
|
read_reset_token(serializer.validated_data["token"])
|
||||||
|
except InvalidToken:
|
||||||
|
return error(INVALID_RESET_LINK, "invalid_token")
|
||||||
|
return Response(status=status.HTTP_204_NO_CONTENT)
|
||||||
|
|
||||||
|
|
||||||
|
class PasswordResetConfirmView(PublicView):
|
||||||
|
throttle_scope = "password_reset"
|
||||||
|
|
||||||
|
@extend_schema(
|
||||||
|
request=PasswordResetConfirmSerializer,
|
||||||
|
responses={204: None, 400: DetailSerializer},
|
||||||
|
summary="Définir un nouveau mot de passe avec le lien reçu",
|
||||||
|
description="Le lien ne sert qu'une fois ; les autres sessions sont fermées.",
|
||||||
|
)
|
||||||
|
def post(self, request):
|
||||||
|
serializer = PasswordResetConfirmSerializer(data=request.data)
|
||||||
|
serializer.is_valid(raise_exception=True)
|
||||||
|
try:
|
||||||
|
user = read_reset_token(serializer.validated_data["token"])
|
||||||
|
except InvalidToken:
|
||||||
|
return error(INVALID_RESET_LINK, "invalid_token")
|
||||||
|
password = serializer.validated_data["new_password"]
|
||||||
|
try:
|
||||||
|
validate_password(password, user)
|
||||||
|
except ValidationError as exc:
|
||||||
|
return Response(
|
||||||
|
{"new_password": list(exc.messages)}, status=status.HTTP_400_BAD_REQUEST
|
||||||
|
)
|
||||||
|
# Changer le mot de passe invalide les sessions existantes (empreinte de session).
|
||||||
|
services.change_password(user, password)
|
||||||
|
return Response(status=status.HTTP_204_NO_CONTENT)
|
||||||
@@ -14,8 +14,8 @@ POLLUTANTS = [
|
|||||||
# (couche irCELine, libellé, valeur guide OMS)
|
# (couche irCELine, libellé, valeur guide OMS)
|
||||||
("pm25_anmean_be", "PM2,5", 5.0),
|
("pm25_anmean_be", "PM2,5", 5.0),
|
||||||
("pm10_anmean_be", "PM10", 15.0),
|
("pm10_anmean_be", "PM10", 15.0),
|
||||||
("no2_anmean_be", "NO2", 10.0),
|
("no2_anmean_be", "NO₂", 10.0),
|
||||||
("o3_anmean_be", "O3", None),
|
("o3_anmean_be", "O₃", None),
|
||||||
]
|
]
|
||||||
|
|
||||||
# Demi-côté (en degrés) de l'emprise de la requête GetFeatureInfo autour du point.
|
# Demi-côté (en degrés) de l'emprise de la requête GetFeatureInfo autour du point.
|
||||||
@@ -45,13 +45,18 @@ class AirProvider:
|
|||||||
details.append({"label": label, "value": "donnée absente"})
|
details.append({"label": label, "value": "donnée absente"})
|
||||||
continue
|
continue
|
||||||
text = f"{value:.1f} µg/m³".replace(".", ",")
|
text = f"{value:.1f} µg/m³".replace(".", ",")
|
||||||
|
detail = {"label": label, "value": text}
|
||||||
if guideline is not None:
|
if guideline is not None:
|
||||||
exceeded = value > guideline
|
exceeded = value > guideline
|
||||||
exceedances += exceeded
|
exceedances += exceeded
|
||||||
text += f" (valeur guide OMS {guideline:g} : {'dépassée' if exceeded else 'ok'})"
|
detail["value"] += f" (seuil {guideline:g})"
|
||||||
details.append({"label": label, "value": text})
|
detail["status"] = "exceeded" if exceeded else "ok"
|
||||||
|
details.append(detail)
|
||||||
|
|
||||||
summary = f"{exceedances} dépassement{'s' if exceedances > 1 else ''} des valeurs OMS"
|
plural = "s" if exceedances > 1 else ""
|
||||||
|
summary = (
|
||||||
|
f"{exceedances} dépassement{plural} des valeurs guides OMS 2021 (moyennes annuelles)"
|
||||||
|
)
|
||||||
return RawResult(self.code, "ok", str(exceedances), summary, details)
|
return RawResult(self.code, "ok", str(exceedances), summary, details)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ class RawResult:
|
|||||||
# Valeur comparée à `ThresholdClass.source_value` (ex. « 65-69 », « Aléa élevé »).
|
# Valeur comparée à `ThresholdClass.source_value` (ex. « 65-69 », « Aléa élevé »).
|
||||||
source_value: str | None = None
|
source_value: str | None = None
|
||||||
summary: str = ""
|
summary: str = ""
|
||||||
|
# Lignes { label, value } ; `status` facultatif (« ok » ou « exceeded ») pour la pastille.
|
||||||
details: list[dict[str, str]] = field(default_factory=list)
|
details: list[dict[str, str]] = field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ class LocationSerializer(serializers.Serializer):
|
|||||||
class DetailSerializer(serializers.Serializer):
|
class DetailSerializer(serializers.Serializer):
|
||||||
label = serializers.CharField()
|
label = serializers.CharField()
|
||||||
value = serializers.CharField()
|
value = serializers.CharField()
|
||||||
|
status = serializers.ChoiceField(choices=["ok", "exceeded"], required=False)
|
||||||
|
|
||||||
|
|
||||||
class ScaleItemSerializer(serializers.Serializer):
|
class ScaleItemSerializer(serializers.Serializer):
|
||||||
|
|||||||
@@ -32,7 +32,6 @@ INSTALLED_APPS = [
|
|||||||
"drf_spectacular",
|
"drf_spectacular",
|
||||||
"django_otp",
|
"django_otp",
|
||||||
"django_otp.plugins.otp_totp",
|
"django_otp.plugins.otp_totp",
|
||||||
"django_otp.plugins.otp_static",
|
|
||||||
"simple_history",
|
"simple_history",
|
||||||
"accounts",
|
"accounts",
|
||||||
"factors",
|
"factors",
|
||||||
@@ -96,9 +95,26 @@ SESSION_SAVE_EVERY_REQUEST = True
|
|||||||
SESSION_COOKIE_HTTPONLY = True
|
SESSION_COOKIE_HTTPONLY = True
|
||||||
SESSION_COOKIE_SAMESITE = "Lax"
|
SESSION_COOKIE_SAMESITE = "Lax"
|
||||||
CSRF_COOKIE_SAMESITE = "Lax"
|
CSRF_COOKIE_SAMESITE = "Lax"
|
||||||
|
# Le front lit le cookie CSRF pour le renvoyer dans l'en-tête X-CSRFToken.
|
||||||
|
CSRF_COOKIE_HTTPONLY = False
|
||||||
SESSION_COOKIE_SECURE = not DEBUG
|
SESSION_COOKIE_SECURE = not DEBUG
|
||||||
CSRF_COOKIE_SECURE = not DEBUG
|
CSRF_COOKIE_SECURE = not DEBUG
|
||||||
|
|
||||||
|
# Comptes et double authentification (specs §8, §8 bis)
|
||||||
|
|
||||||
|
FRONTEND_URL = env("FRONTEND_URL", default="http://localhost:5173")
|
||||||
|
BACKEND_URL = env("BACKEND_URL", default="http://localhost:8000")
|
||||||
|
# Destinataires des notifications de nouvelle demande de compte (cellule SSMG).
|
||||||
|
SSMG_NOTIFY_EMAILS = env.list("SSMG_NOTIFY_EMAILS", default=[])
|
||||||
|
EMAIL_TOKEN_MAX_AGE = env.int("EMAIL_TOKEN_MAX_AGE", default=24 * 3600)
|
||||||
|
# Lien « mot de passe oublié » : 1 heure (specs §8 bis, e-mail 4).
|
||||||
|
PASSWORD_RESET_TIMEOUT = env.int("PASSWORD_RESET_TIMEOUT", default=3600)
|
||||||
|
# Délai pour saisir le code TOTP après le mot de passe.
|
||||||
|
MFA_STEP_MAX_AGE = env.int("MFA_STEP_MAX_AGE", default=5 * 60)
|
||||||
|
OTP_TOTP_ISSUER = "PRISM"
|
||||||
|
# L'admin Django (cellule SSMG, admin) exige la 2FA ; désactivable en développement.
|
||||||
|
ADMIN_REQUIRE_OTP = env.bool("ADMIN_REQUIRE_OTP", default=not DEBUG)
|
||||||
|
|
||||||
# Internationalisation -------------------------------------------------------
|
# Internationalisation -------------------------------------------------------
|
||||||
|
|
||||||
LANGUAGE_CODE = "fr-be"
|
LANGUAGE_CODE = "fr-be"
|
||||||
@@ -127,6 +143,10 @@ REST_FRAMEWORK = {
|
|||||||
"DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema",
|
"DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema",
|
||||||
"DEFAULT_THROTTLE_RATES": {
|
"DEFAULT_THROTTLE_RATES": {
|
||||||
"assessments": env("THROTTLE_ASSESSMENTS", default="60/hour"),
|
"assessments": env("THROTTLE_ASSESSMENTS", default="60/hour"),
|
||||||
|
"login": env("THROTTLE_LOGIN", default="10/minute"),
|
||||||
|
"mfa": env("THROTTLE_MFA", default="10/minute"),
|
||||||
|
"register": env("THROTTLE_REGISTER", default="10/hour"),
|
||||||
|
"password_reset": env("THROTTLE_PASSWORD_RESET", default="10/hour"),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,16 @@
|
|||||||
|
from django.conf import settings
|
||||||
from django.contrib import admin
|
from django.contrib import admin
|
||||||
from django.urls import include, path
|
from django.urls import include, path
|
||||||
|
from django_otp.admin import OTPAdminSite
|
||||||
from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView
|
from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView
|
||||||
|
|
||||||
|
if settings.ADMIN_REQUIRE_OTP:
|
||||||
|
# Seuls les comptes connectés avec un second facteur accèdent à l'admin (specs §8).
|
||||||
|
admin.site.__class__ = OTPAdminSite
|
||||||
|
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
path("admin/", admin.site.urls),
|
path("admin/", admin.site.urls),
|
||||||
|
path("api/v1/auth/", include("accounts.urls")),
|
||||||
path("api/v1/", include("assessments.urls")),
|
path("api/v1/", include("assessments.urls")),
|
||||||
path("api/schema/", SpectacularAPIView.as_view(), name="schema"),
|
path("api/schema/", SpectacularAPIView.as_view(), name="schema"),
|
||||||
path("api/docs/", SpectacularSwaggerView.as_view(url_name="schema"), name="api-docs"),
|
path("api/docs/", SpectacularSwaggerView.as_view(url_name="schema"), name="api-docs"),
|
||||||
|
|||||||
@@ -0,0 +1,141 @@
|
|||||||
|
"""POST /api/v1/auth/login/, POST /api/v1/auth/logout/, GET /api/v1/auth/me/"""
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from django.contrib.auth.models import Group
|
||||||
|
from rest_framework.test import APIClient
|
||||||
|
from rest_framework.throttling import ScopedRateThrottle
|
||||||
|
|
||||||
|
from accounts.models import User
|
||||||
|
|
||||||
|
LOGIN, LOGOUT, ME = "/api/v1/auth/login/", "/api/v1/auth/logout/", "/api/v1/auth/me/"
|
||||||
|
PASSWORD = "un-mot-de-passe-solide"
|
||||||
|
|
||||||
|
pytestmark = pytest.mark.django_db
|
||||||
|
|
||||||
|
|
||||||
|
def login(client, email="medecin@exemple.be", password=PASSWORD):
|
||||||
|
return client.post(LOGIN, {"email": email, "password": password}, format="json")
|
||||||
|
|
||||||
|
|
||||||
|
# Connexion ------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_login_opens_a_session(user):
|
||||||
|
client = APIClient()
|
||||||
|
response = login(client)
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json() == {
|
||||||
|
"mfa_required": False,
|
||||||
|
"user": {
|
||||||
|
"email": "medecin@exemple.be",
|
||||||
|
"first_name": "Jean",
|
||||||
|
"last_name": "Dupont",
|
||||||
|
"roles": [],
|
||||||
|
"is_staff": False,
|
||||||
|
"mfa_enabled": False,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
assert client.get(ME).status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
def test_login_is_case_insensitive_on_email(user):
|
||||||
|
assert login(APIClient(), email="Medecin@Exemple.BE").status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("email", "password"),
|
||||||
|
[("medecin@exemple.be", "mauvais-mot-de-passe"), ("inconnu@exemple.be", PASSWORD)],
|
||||||
|
ids=["mauvais-mot-de-passe", "compte-inconnu"],
|
||||||
|
)
|
||||||
|
def test_invalid_credentials_give_generic_message(user, email, password):
|
||||||
|
response = login(APIClient(), email, password)
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert response.json() == {"detail": "E-mail ou mot de passe incorrect."}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"status",
|
||||||
|
[
|
||||||
|
User.Status.EMAIL_PENDING,
|
||||||
|
User.Status.APPROVAL_PENDING,
|
||||||
|
User.Status.REFUSED,
|
||||||
|
User.Status.DISABLED,
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_inactive_account_cannot_log_in(user, status):
|
||||||
|
user.status = status
|
||||||
|
user.save()
|
||||||
|
response = login(APIClient())
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert response.json() == {"detail": "E-mail ou mot de passe incorrect."}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"payload",
|
||||||
|
[{}, {"email": "medecin@exemple.be"}, {"email": "pas-un-email", "password": PASSWORD}],
|
||||||
|
ids=["vide", "sans-mot-de-passe", "email-invalide"],
|
||||||
|
)
|
||||||
|
def test_invalid_payload(user, payload):
|
||||||
|
assert APIClient().post(LOGIN, payload, format="json").status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_login_requires_csrf_token(user):
|
||||||
|
client = APIClient(enforce_csrf_checks=True)
|
||||||
|
assert login(client).status_code == 403
|
||||||
|
|
||||||
|
client.get(ME) # dépose le cookie CSRF, même sans session
|
||||||
|
token = client.cookies["csrftoken"].value
|
||||||
|
response = client.post(
|
||||||
|
LOGIN,
|
||||||
|
{"email": "medecin@exemple.be", "password": PASSWORD},
|
||||||
|
format="json",
|
||||||
|
HTTP_X_CSRFTOKEN=token,
|
||||||
|
)
|
||||||
|
assert response.status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
def test_login_throttling(user, monkeypatch):
|
||||||
|
monkeypatch.setattr(ScopedRateThrottle, "THROTTLE_RATES", {"login": "2/minute"})
|
||||||
|
client = APIClient()
|
||||||
|
assert login(client, password="faux").status_code == 400
|
||||||
|
assert login(client, password="faux").status_code == 400
|
||||||
|
assert login(client).status_code == 429
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_login_is_not_allowed():
|
||||||
|
assert APIClient().get(LOGIN).status_code == 405
|
||||||
|
|
||||||
|
|
||||||
|
# Utilisateur courant ---------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_me_anonymous():
|
||||||
|
response = APIClient().get(ME)
|
||||||
|
assert response.status_code == 403
|
||||||
|
assert "csrftoken" in response.cookies
|
||||||
|
|
||||||
|
|
||||||
|
def test_me_returns_roles(api, user):
|
||||||
|
user.groups.add(Group.objects.get(name="Médecin"))
|
||||||
|
response = api.get(ME)
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json()["roles"] == ["Médecin"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_me_does_not_expose_sensitive_fields(api):
|
||||||
|
body = api.get(ME).json()
|
||||||
|
assert not {"password", "inami_number", "status", "id"} & set(body)
|
||||||
|
|
||||||
|
|
||||||
|
# Déconnexion ----------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_logout_closes_the_session(user):
|
||||||
|
client = APIClient()
|
||||||
|
login(client)
|
||||||
|
assert client.post(LOGOUT).status_code == 204
|
||||||
|
assert client.get(ME).status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
def test_logout_anonymous():
|
||||||
|
assert APIClient().post(LOGOUT).status_code == 403
|
||||||
@@ -0,0 +1,285 @@
|
|||||||
|
"""Double authentification : 2fa/setup, enable, verify, disable, recovery-codes ; mot de passe."""
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from django.core import mail
|
||||||
|
from django_otp.oath import TOTP
|
||||||
|
from django_otp.plugins.otp_totp.models import TOTPDevice
|
||||||
|
from rest_framework.test import APIClient
|
||||||
|
|
||||||
|
from accounts.models import RecoveryCode, User
|
||||||
|
|
||||||
|
PASSWORD = "un-mot-de-passe-solide"
|
||||||
|
AUTH = "/api/v1/auth"
|
||||||
|
|
||||||
|
pytestmark = pytest.mark.django_db
|
||||||
|
|
||||||
|
|
||||||
|
def current_code(device: TOTPDevice, offset: int = 0) -> str:
|
||||||
|
totp = TOTP(device.bin_key, device.step, device.t0, device.digits, device.drift)
|
||||||
|
totp.time = totp.time + offset * device.step
|
||||||
|
return f"{totp.token():06d}"
|
||||||
|
|
||||||
|
|
||||||
|
def login(client, email="medecin@exemple.be", password=PASSWORD):
|
||||||
|
return client.post(f"{AUTH}/login/", {"email": email, "password": password}, format="json")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def logged_in(user):
|
||||||
|
client = APIClient()
|
||||||
|
login(client)
|
||||||
|
return client
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def with_mfa(user, logged_in, django_capture_on_commit_callbacks):
|
||||||
|
"""Active la 2FA pour `user` ; renvoie (appareil, codes de secours)."""
|
||||||
|
logged_in.post(f"{AUTH}/2fa/setup/")
|
||||||
|
device = TOTPDevice.objects.get(user=user)
|
||||||
|
with django_capture_on_commit_callbacks(execute=True):
|
||||||
|
response = logged_in.post(
|
||||||
|
f"{AUTH}/2fa/enable/", {"code": current_code(device)}, format="json"
|
||||||
|
)
|
||||||
|
device.refresh_from_db()
|
||||||
|
return device, response.json()["recovery_codes"]
|
||||||
|
|
||||||
|
|
||||||
|
# Activation ------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_setup_returns_secret_and_qr_code(user, logged_in):
|
||||||
|
response = logged_in.post(f"{AUTH}/2fa/setup/")
|
||||||
|
assert response.status_code == 200
|
||||||
|
body = response.json()
|
||||||
|
assert body["otpauth_url"].startswith("otpauth://totp/")
|
||||||
|
assert "issuer=PRISM" in body["otpauth_url"]
|
||||||
|
assert body["qr_code"].startswith("data:image/svg+xml;base64,")
|
||||||
|
assert len(body["secret"].replace(" ", "")) == 32
|
||||||
|
assert not TOTPDevice.objects.get(user=user).confirmed
|
||||||
|
|
||||||
|
|
||||||
|
def test_setup_replaces_previous_attempt(user, logged_in):
|
||||||
|
logged_in.post(f"{AUTH}/2fa/setup/")
|
||||||
|
logged_in.post(f"{AUTH}/2fa/setup/")
|
||||||
|
assert TOTPDevice.objects.filter(user=user).count() == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_setup_requires_authentication():
|
||||||
|
assert APIClient().post(f"{AUTH}/2fa/setup/").status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
def test_enable_with_valid_code(user, with_mfa):
|
||||||
|
device, codes = with_mfa
|
||||||
|
assert device.confirmed
|
||||||
|
assert len(codes) == 8
|
||||||
|
assert all(len(code) == 9 and code[4] == "-" for code in codes)
|
||||||
|
assert RecoveryCode.objects.filter(user=user).count() == 8
|
||||||
|
# Les codes ne sont stockés qu'en empreinte.
|
||||||
|
stored = set(RecoveryCode.objects.values_list("code_hash", flat=True))
|
||||||
|
assert not {c.replace("-", "") for c in codes} & stored
|
||||||
|
assert mail.outbox[-1].subject == "[PRISM] Double authentification modifiée"
|
||||||
|
assert "activée" in mail.outbox[-1].body
|
||||||
|
|
||||||
|
|
||||||
|
def test_enable_with_wrong_code(user, logged_in):
|
||||||
|
logged_in.post(f"{AUTH}/2fa/setup/")
|
||||||
|
response = logged_in.post(f"{AUTH}/2fa/enable/", {"code": "000000"}, format="json")
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert response.json()["code"] == "invalid_code"
|
||||||
|
assert not TOTPDevice.objects.get(user=user).confirmed
|
||||||
|
|
||||||
|
|
||||||
|
def test_enable_without_setup(logged_in):
|
||||||
|
response = logged_in.post(f"{AUTH}/2fa/enable/", {"code": "123456"}, format="json")
|
||||||
|
assert response.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_setup_refused_when_already_enabled(logged_in, with_mfa):
|
||||||
|
response = logged_in.post(f"{AUTH}/2fa/setup/")
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert response.json()["code"] == "mfa_enabled"
|
||||||
|
|
||||||
|
|
||||||
|
def test_me_reports_mfa(logged_in, with_mfa):
|
||||||
|
assert logged_in.get(f"{AUTH}/me/").json()["mfa_enabled"] is True
|
||||||
|
|
||||||
|
|
||||||
|
# Connexion en deux étapes ------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_login_requires_second_step(with_mfa):
|
||||||
|
client = APIClient()
|
||||||
|
response = login(client)
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json() == {"mfa_required": True, "user": None}
|
||||||
|
# Pas de session ouverte avant le second facteur.
|
||||||
|
assert client.get(f"{AUTH}/me/").status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
def test_login_with_totp_code(with_mfa):
|
||||||
|
device, _ = with_mfa
|
||||||
|
client = APIClient()
|
||||||
|
login(client)
|
||||||
|
response = client.post(
|
||||||
|
f"{AUTH}/2fa/verify/", {"code": current_code(device, offset=1)}, format="json"
|
||||||
|
)
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json()["user"]["email"] == "medecin@exemple.be"
|
||||||
|
assert client.get(f"{AUTH}/me/").status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
def test_login_with_recovery_code_works_once(with_mfa):
|
||||||
|
_, codes = with_mfa
|
||||||
|
client = APIClient()
|
||||||
|
login(client)
|
||||||
|
lowercase_without_dash = codes[0].replace("-", "").lower()
|
||||||
|
assert (
|
||||||
|
client.post(
|
||||||
|
f"{AUTH}/2fa/verify/", {"code": lowercase_without_dash}, format="json"
|
||||||
|
).status_code
|
||||||
|
== 200
|
||||||
|
)
|
||||||
|
|
||||||
|
other = APIClient()
|
||||||
|
login(other)
|
||||||
|
response = other.post(f"{AUTH}/2fa/verify/", {"code": codes[0]}, format="json")
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert response.json()["code"] == "invalid_code"
|
||||||
|
|
||||||
|
|
||||||
|
def test_wrong_code_keeps_session_closed(with_mfa):
|
||||||
|
client = APIClient()
|
||||||
|
login(client)
|
||||||
|
response = client.post(f"{AUTH}/2fa/verify/", {"code": "000000"}, format="json")
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert response.json() == {"detail": "Code incorrect ou expiré.", "code": "invalid_code"}
|
||||||
|
assert client.get(f"{AUTH}/me/").status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
def test_verify_without_first_step(with_mfa):
|
||||||
|
device, _ = with_mfa
|
||||||
|
response = APIClient().post(
|
||||||
|
f"{AUTH}/2fa/verify/", {"code": current_code(device)}, format="json"
|
||||||
|
)
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert response.json()["code"] == "mfa_expired"
|
||||||
|
|
||||||
|
|
||||||
|
def test_second_step_expires(with_mfa, settings):
|
||||||
|
device, _ = with_mfa
|
||||||
|
settings.MFA_STEP_MAX_AGE = -1
|
||||||
|
client = APIClient()
|
||||||
|
login(client)
|
||||||
|
response = client.post(f"{AUTH}/2fa/verify/", {"code": current_code(device)}, format="json")
|
||||||
|
assert response.json()["code"] == "mfa_expired"
|
||||||
|
|
||||||
|
|
||||||
|
def test_totp_code_cannot_be_replayed(with_mfa):
|
||||||
|
device, _ = with_mfa
|
||||||
|
code = current_code(device, offset=1)
|
||||||
|
first = APIClient()
|
||||||
|
login(first)
|
||||||
|
assert first.post(f"{AUTH}/2fa/verify/", {"code": code}, format="json").status_code == 200
|
||||||
|
second = APIClient()
|
||||||
|
login(second)
|
||||||
|
assert second.post(f"{AUTH}/2fa/verify/", {"code": code}, format="json").status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_second_step_throttling(with_mfa, monkeypatch):
|
||||||
|
from rest_framework.throttling import ScopedRateThrottle
|
||||||
|
|
||||||
|
monkeypatch.setattr(ScopedRateThrottle, "THROTTLE_RATES", {"mfa": "2/minute", "login": None})
|
||||||
|
client = APIClient()
|
||||||
|
login(client)
|
||||||
|
for _ in range(2):
|
||||||
|
client.post(f"{AUTH}/2fa/verify/", {"code": "000000"}, format="json")
|
||||||
|
assert client.post(f"{AUTH}/2fa/verify/", {"code": "000000"}, format="json").status_code == 429
|
||||||
|
|
||||||
|
|
||||||
|
# Désactivation et régénération -----------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_disable_requires_password_and_code(
|
||||||
|
user, logged_in, with_mfa, django_capture_on_commit_callbacks
|
||||||
|
):
|
||||||
|
device, codes = with_mfa
|
||||||
|
bad_password = logged_in.post(
|
||||||
|
f"{AUTH}/2fa/disable/", {"password": "faux", "code": codes[0]}, format="json"
|
||||||
|
)
|
||||||
|
assert bad_password.json()["code"] == "invalid_password"
|
||||||
|
bad_code = logged_in.post(
|
||||||
|
f"{AUTH}/2fa/disable/", {"password": PASSWORD, "code": "000000"}, format="json"
|
||||||
|
)
|
||||||
|
assert bad_code.json()["code"] == "invalid_code"
|
||||||
|
|
||||||
|
with django_capture_on_commit_callbacks(execute=True):
|
||||||
|
response = logged_in.post(
|
||||||
|
f"{AUTH}/2fa/disable/", {"password": PASSWORD, "code": codes[1]}, format="json"
|
||||||
|
)
|
||||||
|
assert response.status_code == 204
|
||||||
|
assert not TOTPDevice.objects.filter(user=user).exists()
|
||||||
|
assert not RecoveryCode.objects.filter(user=user).exists()
|
||||||
|
assert "désactivée" in mail.outbox[-1].body
|
||||||
|
|
||||||
|
|
||||||
|
def test_staff_cannot_disable_mfa(user, logged_in, with_mfa):
|
||||||
|
_, codes = with_mfa
|
||||||
|
User.objects.filter(pk=user.pk).update(is_staff=True)
|
||||||
|
response = logged_in.post(
|
||||||
|
f"{AUTH}/2fa/disable/", {"password": PASSWORD, "code": codes[0]}, format="json"
|
||||||
|
)
|
||||||
|
assert response.json()["code"] == "mfa_mandatory"
|
||||||
|
|
||||||
|
|
||||||
|
def test_regenerate_recovery_codes(user, logged_in, with_mfa):
|
||||||
|
device, old_codes = with_mfa
|
||||||
|
response = logged_in.post(
|
||||||
|
f"{AUTH}/2fa/recovery-codes/", {"code": current_code(device, offset=1)}, format="json"
|
||||||
|
)
|
||||||
|
assert response.status_code == 200
|
||||||
|
new_codes = response.json()["recovery_codes"]
|
||||||
|
assert len(new_codes) == 8
|
||||||
|
assert not set(new_codes) & set(old_codes)
|
||||||
|
|
||||||
|
client = APIClient()
|
||||||
|
login(client)
|
||||||
|
assert (
|
||||||
|
client.post(f"{AUTH}/2fa/verify/", {"code": old_codes[2]}, format="json").status_code == 400
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_regenerate_refuses_recovery_code(logged_in, with_mfa):
|
||||||
|
_, codes = with_mfa
|
||||||
|
response = logged_in.post(f"{AUTH}/2fa/recovery-codes/", {"code": codes[0]}, format="json")
|
||||||
|
assert response.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
# Mot de passe ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_change_password(user, logged_in, django_capture_on_commit_callbacks):
|
||||||
|
with django_capture_on_commit_callbacks(execute=True):
|
||||||
|
response = logged_in.post(
|
||||||
|
f"{AUTH}/password/change/",
|
||||||
|
{"current_password": PASSWORD, "new_password": "un-autre-mot-de-passe"},
|
||||||
|
format="json",
|
||||||
|
)
|
||||||
|
assert response.status_code == 204
|
||||||
|
# La session reste ouverte.
|
||||||
|
assert logged_in.get(f"{AUTH}/me/").status_code == 200
|
||||||
|
user.refresh_from_db()
|
||||||
|
assert user.check_password("un-autre-mot-de-passe")
|
||||||
|
assert mail.outbox[-1].subject == "[PRISM] Votre mot de passe a été modifié"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("payload", "field"),
|
||||||
|
[
|
||||||
|
({"current_password": "faux", "new_password": "un-autre-mot-de-passe"}, "current_password"),
|
||||||
|
({"current_password": PASSWORD, "new_password": "court"}, "new_password"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_change_password_validation(logged_in, payload, field):
|
||||||
|
response = logged_in.post(f"{AUTH}/password/change/", payload, format="json")
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert field in response.json()
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
"""Mot de passe oublié : password-reset/, password-reset/validate/, password-reset/confirm/."""
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from django.core import mail
|
||||||
|
from rest_framework.test import APIClient
|
||||||
|
from rest_framework.throttling import ScopedRateThrottle
|
||||||
|
|
||||||
|
from accounts.models import User
|
||||||
|
from accounts.tokens import make_reset_token
|
||||||
|
|
||||||
|
AUTH = "/api/v1/auth"
|
||||||
|
PASSWORD = "un-mot-de-passe-solide"
|
||||||
|
NEW_PASSWORD = "un-tout-nouveau-mot-de-passe"
|
||||||
|
|
||||||
|
pytestmark = pytest.mark.django_db
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def frontend(settings):
|
||||||
|
settings.FRONTEND_URL = "https://prism.test"
|
||||||
|
|
||||||
|
|
||||||
|
def request_reset(email):
|
||||||
|
return APIClient().post(f"{AUTH}/password-reset/", {"email": email}, format="json")
|
||||||
|
|
||||||
|
|
||||||
|
def confirm(token, password=NEW_PASSWORD, client=None):
|
||||||
|
return (client or APIClient()).post(
|
||||||
|
f"{AUTH}/password-reset/confirm/",
|
||||||
|
{"token": token, "new_password": password},
|
||||||
|
format="json",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def token_from_mail() -> str:
|
||||||
|
return mail.outbox[-1].body.split("/reinitialisation/")[1].split()[0]
|
||||||
|
|
||||||
|
|
||||||
|
# Demande ------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_request_sends_link_valid_one_hour(user, django_capture_on_commit_callbacks):
|
||||||
|
with django_capture_on_commit_callbacks(execute=True):
|
||||||
|
response = request_reset("Medecin@Exemple.be")
|
||||||
|
|
||||||
|
assert response.status_code == 202
|
||||||
|
message = mail.outbox[0]
|
||||||
|
assert message.to == ["medecin@exemple.be"]
|
||||||
|
assert message.subject == "[PRISM] Réinitialisez votre mot de passe"
|
||||||
|
assert "https://prism.test/reinitialisation/" in message.body
|
||||||
|
assert "1 heure" in message.body
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"status",
|
||||||
|
[
|
||||||
|
User.Status.EMAIL_PENDING,
|
||||||
|
User.Status.APPROVAL_PENDING,
|
||||||
|
User.Status.REFUSED,
|
||||||
|
User.Status.DISABLED,
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_no_email_for_inactive_account(user, status, django_capture_on_commit_callbacks):
|
||||||
|
User.objects.filter(pk=user.pk).update(status=status)
|
||||||
|
with django_capture_on_commit_callbacks(execute=True):
|
||||||
|
response = request_reset("medecin@exemple.be")
|
||||||
|
assert response.status_code == 202
|
||||||
|
assert mail.outbox == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_email_gets_same_response(django_capture_on_commit_callbacks):
|
||||||
|
with django_capture_on_commit_callbacks(execute=True):
|
||||||
|
response = request_reset("inconnu@exemple.be")
|
||||||
|
assert response.status_code == 202
|
||||||
|
assert response.content == b""
|
||||||
|
assert mail.outbox == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_invalid_email_payload():
|
||||||
|
assert request_reset("pas-un-email").status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_request_throttling(user, monkeypatch):
|
||||||
|
monkeypatch.setattr(ScopedRateThrottle, "THROTTLE_RATES", {"password_reset": "2/hour"})
|
||||||
|
request_reset("medecin@exemple.be")
|
||||||
|
request_reset("medecin@exemple.be")
|
||||||
|
assert request_reset("medecin@exemple.be").status_code == 429
|
||||||
|
|
||||||
|
|
||||||
|
# Vérification du lien -----------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_validate_good_and_bad_links(user):
|
||||||
|
client = APIClient()
|
||||||
|
good = client.post(
|
||||||
|
f"{AUTH}/password-reset/validate/", {"token": make_reset_token(user)}, format="json"
|
||||||
|
)
|
||||||
|
assert good.status_code == 204
|
||||||
|
bad = client.post(f"{AUTH}/password-reset/validate/", {"token": "faux.jeton"}, format="json")
|
||||||
|
assert bad.status_code == 400
|
||||||
|
assert bad.json()["code"] == "invalid_token"
|
||||||
|
|
||||||
|
|
||||||
|
# Nouveau mot de passe ---------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_confirm_changes_password_and_notifies(user, django_capture_on_commit_callbacks):
|
||||||
|
with django_capture_on_commit_callbacks(execute=True):
|
||||||
|
request_reset("medecin@exemple.be")
|
||||||
|
token = token_from_mail()
|
||||||
|
|
||||||
|
with django_capture_on_commit_callbacks(execute=True):
|
||||||
|
response = confirm(token)
|
||||||
|
|
||||||
|
assert response.status_code == 204
|
||||||
|
user.refresh_from_db()
|
||||||
|
assert user.check_password(NEW_PASSWORD)
|
||||||
|
assert mail.outbox[-1].subject == "[PRISM] Votre mot de passe a été modifié"
|
||||||
|
|
||||||
|
|
||||||
|
def test_link_works_only_once(user):
|
||||||
|
token = make_reset_token(user)
|
||||||
|
assert confirm(token).status_code == 204
|
||||||
|
response = confirm(token, "encore-un-autre-mot-de-passe")
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert response.json()["code"] == "invalid_token"
|
||||||
|
|
||||||
|
|
||||||
|
def test_link_expires(user, settings):
|
||||||
|
token = make_reset_token(user)
|
||||||
|
settings.PASSWORD_RESET_TIMEOUT = -1
|
||||||
|
assert confirm(token).json()["code"] == "invalid_token"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"token",
|
||||||
|
["", "sans-point", "Zm9v.abc-def", "MTIzNDU.abc-def", "!!!.abc"],
|
||||||
|
ids=["vide", "sans-point", "uid-invalide", "compte-inconnu", "base64-invalide"],
|
||||||
|
)
|
||||||
|
def test_malformed_tokens(user, token):
|
||||||
|
response = confirm(token)
|
||||||
|
assert response.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_weak_password_is_refused_and_link_stays_valid(user):
|
||||||
|
token = make_reset_token(user)
|
||||||
|
response = confirm(token, "court")
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert "new_password" in response.json()
|
||||||
|
assert confirm(token).status_code == 204
|
||||||
|
|
||||||
|
|
||||||
|
def test_reset_closes_existing_sessions(user):
|
||||||
|
other_device = APIClient()
|
||||||
|
other_device.post(f"{AUTH}/login/", {"email": user.email, "password": PASSWORD}, format="json")
|
||||||
|
assert other_device.get(f"{AUTH}/me/").status_code == 200
|
||||||
|
# La connexion a changé `last_login`, qui entre dans le jeton.
|
||||||
|
user.refresh_from_db()
|
||||||
|
|
||||||
|
assert confirm(make_reset_token(user)).status_code == 204
|
||||||
|
|
||||||
|
assert other_device.get(f"{AUTH}/me/").status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
def test_disabled_account_cannot_use_old_link(user):
|
||||||
|
token = make_reset_token(user)
|
||||||
|
User.objects.filter(pk=user.pk).update(status=User.Status.DISABLED)
|
||||||
|
assert confirm(token).json()["code"] == "invalid_token"
|
||||||
|
|
||||||
|
|
||||||
|
def test_new_password_allows_login(user):
|
||||||
|
confirm(make_reset_token(user))
|
||||||
|
response = APIClient().post(
|
||||||
|
f"{AUTH}/login/", {"email": user.email, "password": NEW_PASSWORD}, format="json"
|
||||||
|
)
|
||||||
|
assert response.status_code == 200
|
||||||
@@ -0,0 +1,313 @@
|
|||||||
|
"""Inscription : register/, verify-email/, verify-email/resend/ et validation dans l'admin."""
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from django.contrib.admin.sites import site
|
||||||
|
from django.core import mail, signing
|
||||||
|
from django.core.management import call_command
|
||||||
|
from django.test import RequestFactory
|
||||||
|
from django.utils import timezone
|
||||||
|
from rest_framework.test import APIClient
|
||||||
|
|
||||||
|
from accounts.admin import UserAdmin
|
||||||
|
from accounts.models import MailEvent, User
|
||||||
|
from accounts.tokens import EMAIL_SALT, make_email_token
|
||||||
|
|
||||||
|
REGISTER = "/api/v1/auth/register/"
|
||||||
|
VERIFY = "/api/v1/auth/verify-email/"
|
||||||
|
RESEND = "/api/v1/auth/verify-email/resend/"
|
||||||
|
|
||||||
|
PAYLOAD = {
|
||||||
|
"first_name": "Marie",
|
||||||
|
"last_name": "Curie",
|
||||||
|
"email": "Marie.Curie@Exemple.be",
|
||||||
|
"inami_number": "1-23456-78-901",
|
||||||
|
"password": "un-mot-de-passe-solide",
|
||||||
|
"accept_terms": True,
|
||||||
|
}
|
||||||
|
|
||||||
|
pytestmark = pytest.mark.django_db
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def ssmg_recipients(settings):
|
||||||
|
settings.SSMG_NOTIFY_EMAILS = ["cellule@ssmg.be"]
|
||||||
|
settings.FRONTEND_URL = "https://prism.test"
|
||||||
|
|
||||||
|
|
||||||
|
def register(payload=PAYLOAD, client=None):
|
||||||
|
return (client or APIClient()).post(REGISTER, payload, format="json")
|
||||||
|
|
||||||
|
|
||||||
|
def link_token(message) -> str:
|
||||||
|
return message.body.split("jeton=")[1].split()[0]
|
||||||
|
|
||||||
|
|
||||||
|
# Inscription --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_register_creates_pending_account_and_sends_confirmation(
|
||||||
|
django_capture_on_commit_callbacks,
|
||||||
|
):
|
||||||
|
with django_capture_on_commit_callbacks(execute=True):
|
||||||
|
response = register()
|
||||||
|
|
||||||
|
assert response.status_code == 201
|
||||||
|
assert response.content == b""
|
||||||
|
user = User.objects.get(email="marie.curie@exemple.be")
|
||||||
|
assert user.status == User.Status.EMAIL_PENDING
|
||||||
|
assert user.inami_number == "1-23456-78-901"
|
||||||
|
assert not user.is_active
|
||||||
|
assert user.check_password("un-mot-de-passe-solide")
|
||||||
|
|
||||||
|
assert len(mail.outbox) == 1
|
||||||
|
message = mail.outbox[0]
|
||||||
|
assert message.to == ["marie.curie@exemple.be"]
|
||||||
|
assert message.subject == "[PRISM] Confirmez votre adresse e-mail"
|
||||||
|
assert "https://prism.test/inscription/statut?jeton=" in message.body
|
||||||
|
assert message.alternatives[0][1] == "text/html"
|
||||||
|
assert MailEvent.objects.get().type == MailEvent.Type.CONFIRM_EMAIL
|
||||||
|
|
||||||
|
|
||||||
|
def test_existing_email_gets_same_response_and_a_warning(user, django_capture_on_commit_callbacks):
|
||||||
|
with django_capture_on_commit_callbacks(execute=True):
|
||||||
|
response = register({**PAYLOAD, "email": "MEDECIN@exemple.be"})
|
||||||
|
|
||||||
|
assert response.status_code == 201
|
||||||
|
assert response.content == b""
|
||||||
|
assert User.objects.count() == 1
|
||||||
|
assert mail.outbox[0].to == ["medecin@exemple.be"]
|
||||||
|
assert mail.outbox[0].subject == "[PRISM] Tentative d'inscription avec votre adresse"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("change", "field"),
|
||||||
|
[
|
||||||
|
({"accept_terms": False}, "accept_terms"),
|
||||||
|
({"password": "court"}, "password"),
|
||||||
|
({"password": "password1234"}, "password"),
|
||||||
|
({"password": "marie.curie.exemple"}, "password"),
|
||||||
|
({"email": "pas-un-email"}, "email"),
|
||||||
|
({"first_name": ""}, "first_name"),
|
||||||
|
],
|
||||||
|
ids=["conditions", "trop-court", "courant", "proche-email", "email", "prenom"],
|
||||||
|
)
|
||||||
|
def test_register_validation(change, field):
|
||||||
|
response = register({**PAYLOAD, **change})
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert field in response.json()
|
||||||
|
assert not User.objects.exists()
|
||||||
|
|
||||||
|
|
||||||
|
def test_inami_number_is_optional():
|
||||||
|
payload = {k: v for k, v in PAYLOAD.items() if k != "inami_number"}
|
||||||
|
assert register(payload).status_code == 201
|
||||||
|
|
||||||
|
|
||||||
|
# Confirmation de l'adresse ------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_verify_email_then_ssmg_is_notified(django_capture_on_commit_callbacks):
|
||||||
|
with django_capture_on_commit_callbacks(execute=True):
|
||||||
|
register()
|
||||||
|
token = link_token(mail.outbox[0])
|
||||||
|
|
||||||
|
with django_capture_on_commit_callbacks(execute=True):
|
||||||
|
response = APIClient().post(VERIFY, {"token": token}, format="json")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json() == {"status": "approval_pending"}
|
||||||
|
user = User.objects.get()
|
||||||
|
assert user.status == User.Status.APPROVAL_PENDING
|
||||||
|
assert user.email_verified_at is not None
|
||||||
|
|
||||||
|
notification = mail.outbox[1]
|
||||||
|
assert notification.to == ["cellule@ssmg.be"]
|
||||||
|
assert "Marie Curie" in notification.body
|
||||||
|
assert "1-23456-78-901" in notification.body
|
||||||
|
assert f"/admin/accounts/user/{user.pk}/change/" in notification.body
|
||||||
|
|
||||||
|
|
||||||
|
def test_verify_email_token_is_single_use(django_capture_on_commit_callbacks):
|
||||||
|
with django_capture_on_commit_callbacks(execute=True):
|
||||||
|
register()
|
||||||
|
token = link_token(mail.outbox[0])
|
||||||
|
APIClient().post(VERIFY, {"token": token}, format="json")
|
||||||
|
|
||||||
|
response = APIClient().post(VERIFY, {"token": token}, format="json")
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert response.json()["code"] == "used_token"
|
||||||
|
|
||||||
|
|
||||||
|
def test_expired_token(settings):
|
||||||
|
user = User.objects.create_user("a@exemple.be", "x", first_name="A", last_name="B")
|
||||||
|
token = make_email_token(user)
|
||||||
|
settings.EMAIL_TOKEN_MAX_AGE = -1
|
||||||
|
response = APIClient().post(VERIFY, {"token": token}, format="json")
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert response.json()["code"] == "expired_token"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"token",
|
||||||
|
["n-importe-quoi", signing.dumps({"u": 999, "e": "x@y.be"}, salt=EMAIL_SALT)],
|
||||||
|
ids=["signature-invalide", "compte-inconnu"],
|
||||||
|
)
|
||||||
|
def test_invalid_token(token):
|
||||||
|
response = APIClient().post(VERIFY, {"token": token}, format="json")
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert response.json()["code"] == "invalid_token"
|
||||||
|
|
||||||
|
|
||||||
|
def test_token_for_old_email_is_rejected():
|
||||||
|
user = User.objects.create_user("a@exemple.be", "x", first_name="A", last_name="B")
|
||||||
|
token = make_email_token(user)
|
||||||
|
user.email = "b@exemple.be"
|
||||||
|
user.save()
|
||||||
|
assert APIClient().post(VERIFY, {"token": token}, format="json").json()["code"] == (
|
||||||
|
"invalid_token"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# Renvoi de l'e-mail ------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_resend_by_email(django_capture_on_commit_callbacks):
|
||||||
|
User.objects.create_user("a@exemple.be", "x", first_name="A", last_name="B")
|
||||||
|
with django_capture_on_commit_callbacks(execute=True):
|
||||||
|
response = APIClient().post(RESEND, {"email": "A@exemple.be"}, format="json")
|
||||||
|
assert response.status_code == 202
|
||||||
|
assert mail.outbox[0].subject == "[PRISM] Confirmez votre adresse e-mail"
|
||||||
|
|
||||||
|
|
||||||
|
def test_resend_from_expired_link(settings, django_capture_on_commit_callbacks):
|
||||||
|
user = User.objects.create_user("a@exemple.be", "x", first_name="A", last_name="B")
|
||||||
|
token = make_email_token(user)
|
||||||
|
settings.EMAIL_TOKEN_MAX_AGE = -1
|
||||||
|
with django_capture_on_commit_callbacks(execute=True):
|
||||||
|
response = APIClient().post(RESEND, {"token": token}, format="json")
|
||||||
|
assert response.status_code == 202
|
||||||
|
assert mail.outbox[0].to == ["a@exemple.be"]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"payload",
|
||||||
|
[{"email": "inconnu@exemple.be"}, {"email": "medecin@exemple.be"}, {"token": "faux"}],
|
||||||
|
ids=["inconnu", "deja-actif", "jeton-invalide"],
|
||||||
|
)
|
||||||
|
def test_resend_reveals_nothing(user, payload, django_capture_on_commit_callbacks):
|
||||||
|
with django_capture_on_commit_callbacks(execute=True):
|
||||||
|
response = APIClient().post(RESEND, payload, format="json")
|
||||||
|
assert response.status_code == 202
|
||||||
|
assert mail.outbox == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_resend_requires_email_or_token():
|
||||||
|
assert APIClient().post(RESEND, {}, format="json").status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_registration_throttling(monkeypatch):
|
||||||
|
from rest_framework.throttling import ScopedRateThrottle
|
||||||
|
|
||||||
|
monkeypatch.setattr(ScopedRateThrottle, "THROTTLE_RATES", {"register": "1/hour"})
|
||||||
|
assert register().status_code == 201
|
||||||
|
assert register({**PAYLOAD, "email": "autre@exemple.be"}).status_code == 429
|
||||||
|
|
||||||
|
|
||||||
|
# Validation par la cellule SSMG -------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def pending(db):
|
||||||
|
return User.objects.create_user(
|
||||||
|
"demandeur@exemple.be",
|
||||||
|
"x",
|
||||||
|
first_name="Paul",
|
||||||
|
last_name="Martin",
|
||||||
|
status=User.Status.APPROVAL_PENDING,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def ssmg_admin(db):
|
||||||
|
return User.objects.create_superuser("cellule@ssmg.be", "un-mot-de-passe-solide")
|
||||||
|
|
||||||
|
|
||||||
|
def run_action(action, admin_user, queryset):
|
||||||
|
request = RequestFactory().post("/")
|
||||||
|
request.user = admin_user
|
||||||
|
request.session = {}
|
||||||
|
request._messages = type("M", (), {"add": lambda *a, **k: None})()
|
||||||
|
getattr(UserAdmin(User, site), action)(request, queryset)
|
||||||
|
|
||||||
|
|
||||||
|
def test_admin_approve(pending, ssmg_admin, django_capture_on_commit_callbacks):
|
||||||
|
with django_capture_on_commit_callbacks(execute=True):
|
||||||
|
run_action("approve", ssmg_admin, User.objects.filter(pk=pending.pk))
|
||||||
|
|
||||||
|
pending.refresh_from_db()
|
||||||
|
assert pending.status == User.Status.ACTIVE
|
||||||
|
assert pending.approved_by == ssmg_admin
|
||||||
|
assert pending.approved_at is not None
|
||||||
|
assert mail.outbox[0].subject == "[PRISM] Votre compte PRISM est activé"
|
||||||
|
assert "https://prism.test/login" in mail.outbox[0].body
|
||||||
|
assert login_works("demandeur@exemple.be", "x")
|
||||||
|
|
||||||
|
|
||||||
|
def test_admin_refuse_with_reason(pending, ssmg_admin, django_capture_on_commit_callbacks):
|
||||||
|
pending.refusal_reason = "Numéro INAMI introuvable."
|
||||||
|
pending.save()
|
||||||
|
with django_capture_on_commit_callbacks(execute=True):
|
||||||
|
run_action("refuse", ssmg_admin, User.objects.filter(pk=pending.pk))
|
||||||
|
|
||||||
|
pending.refresh_from_db()
|
||||||
|
assert pending.status == User.Status.REFUSED
|
||||||
|
assert "Motif : Numéro INAMI introuvable." in mail.outbox[0].body
|
||||||
|
assert not login_works("demandeur@exemple.be", "x")
|
||||||
|
|
||||||
|
|
||||||
|
def test_admin_actions_ignore_other_statuses(user, ssmg_admin, django_capture_on_commit_callbacks):
|
||||||
|
with django_capture_on_commit_callbacks(execute=True):
|
||||||
|
run_action("refuse", ssmg_admin, User.objects.filter(pk=user.pk))
|
||||||
|
user.refresh_from_db()
|
||||||
|
assert user.status == User.Status.ACTIVE
|
||||||
|
assert mail.outbox == []
|
||||||
|
|
||||||
|
|
||||||
|
def login_works(email, password):
|
||||||
|
response = APIClient().post(
|
||||||
|
"/api/v1/auth/login/", {"email": email, "password": password}, format="json"
|
||||||
|
)
|
||||||
|
return response.status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
# Purge ------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_purge_unconfirmed_requests(pending):
|
||||||
|
old = User.objects.create_user("vieux@exemple.be", "x", first_name="V", last_name="X")
|
||||||
|
User.objects.filter(pk=old.pk).update(date_joined=timezone.now() - timezone.timedelta(days=8))
|
||||||
|
recent = User.objects.create_user("recent@exemple.be", "x", first_name="R", last_name="X")
|
||||||
|
|
||||||
|
call_command("purge_pending_accounts", stdout=open("/dev/null", "w")) # noqa: SIM115
|
||||||
|
|
||||||
|
remaining = set(User.objects.values_list("email", flat=True))
|
||||||
|
assert old.email not in remaining
|
||||||
|
assert {recent.email, pending.email} <= remaining
|
||||||
|
|
||||||
|
|
||||||
|
# Échec d'envoi ----------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_failed_email_is_logged_without_content(monkeypatch, django_capture_on_commit_callbacks):
|
||||||
|
from django.core.mail import EmailMultiAlternatives
|
||||||
|
|
||||||
|
def boom(self, *args, **kwargs):
|
||||||
|
raise ConnectionRefusedError
|
||||||
|
|
||||||
|
monkeypatch.setattr(EmailMultiAlternatives, "send", boom)
|
||||||
|
with django_capture_on_commit_callbacks(execute=True):
|
||||||
|
assert register().status_code == 201
|
||||||
|
|
||||||
|
event = MailEvent.objects.get()
|
||||||
|
assert event.status == MailEvent.Status.FAILED
|
||||||
|
assert event.error == "ConnectionRefusedError"
|
||||||
@@ -16,7 +16,25 @@ def test_schema_is_public():
|
|||||||
def test_schema_documents_every_route():
|
def test_schema_documents_every_route():
|
||||||
schema = APIClient().get("/api/schema/?format=json").json()
|
schema = APIClient().get("/api/schema/?format=json").json()
|
||||||
paths = schema["paths"]
|
paths = schema["paths"]
|
||||||
assert set(paths) == {"/api/v1/assessments/", "/api/v1/factors/"}
|
assert set(paths) == {
|
||||||
|
"/api/v1/assessments/",
|
||||||
|
"/api/v1/factors/",
|
||||||
|
"/api/v1/auth/login/",
|
||||||
|
"/api/v1/auth/logout/",
|
||||||
|
"/api/v1/auth/me/",
|
||||||
|
"/api/v1/auth/register/",
|
||||||
|
"/api/v1/auth/verify-email/",
|
||||||
|
"/api/v1/auth/verify-email/resend/",
|
||||||
|
"/api/v1/auth/password/change/",
|
||||||
|
"/api/v1/auth/password-reset/",
|
||||||
|
"/api/v1/auth/password-reset/validate/",
|
||||||
|
"/api/v1/auth/password-reset/confirm/",
|
||||||
|
"/api/v1/auth/2fa/setup/",
|
||||||
|
"/api/v1/auth/2fa/enable/",
|
||||||
|
"/api/v1/auth/2fa/verify/",
|
||||||
|
"/api/v1/auth/2fa/disable/",
|
||||||
|
"/api/v1/auth/2fa/recovery-codes/",
|
||||||
|
}
|
||||||
assessments = paths["/api/v1/assessments/"]["post"]
|
assessments = paths["/api/v1/assessments/"]["post"]
|
||||||
assert set(assessments["responses"]) == {"200", "404", "422", "503"}
|
assert set(assessments["responses"]) == {"200", "404", "422", "503"}
|
||||||
assert "requestBody" in assessments
|
assert "requestBody" in assessments
|
||||||
|
|||||||
@@ -57,12 +57,14 @@ async def test_air_counts_who_exceedances(mock_irceline):
|
|||||||
result = await fetch(AirProvider())
|
result = await fetch(AirProvider())
|
||||||
assert result.status == "ok"
|
assert result.status == "ok"
|
||||||
assert result.source_value == "2"
|
assert result.source_value == "2"
|
||||||
assert result.summary == "2 dépassements des valeurs OMS"
|
assert result.summary == "2 dépassements des valeurs guides OMS 2021 (moyennes annuelles)"
|
||||||
assert result.details[0] == {
|
assert result.details[0] == {
|
||||||
"label": "PM2,5",
|
"label": "PM2,5",
|
||||||
"value": "7,1 µg/m³ (valeur guide OMS 5 : dépassée)",
|
"value": "7,1 µg/m³ (seuil 5)",
|
||||||
|
"status": "exceeded",
|
||||||
}
|
}
|
||||||
assert result.details[3] == {"label": "O3", "value": "50,1 µg/m³"}
|
assert result.details[1] == {"label": "PM10", "value": "12,0 µg/m³ (seuil 15)", "status": "ok"}
|
||||||
|
assert result.details[3] == {"label": "O₃", "value": "50,1 µg/m³"}
|
||||||
|
|
||||||
|
|
||||||
async def test_air_wms_exception_raises(mock_http):
|
async def test_air_wms_exception_raises(mock_http):
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
.eslintcache
|
||||||
|
Dockerfile
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
[*.{js,jsx,mjs,cjs,ts,tsx,mts,cts,vue,css,scss,sass,less,styl}]
|
||||||
|
charset = utf-8
|
||||||
|
indent_size = 2
|
||||||
|
indent_style = space
|
||||||
|
insert_final_newline = true
|
||||||
|
trim_trailing_whitespace = true
|
||||||
|
end_of_line = lf
|
||||||
|
max_line_length = 100
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
* text=auto eol=lf
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
# Logs
|
||||||
|
logs
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
lerna-debug.log*
|
||||||
|
|
||||||
|
node_modules
|
||||||
|
.DS_Store
|
||||||
|
dist
|
||||||
|
dist-ssr
|
||||||
|
coverage
|
||||||
|
*.local
|
||||||
|
|
||||||
|
# Editor directories and files
|
||||||
|
.vscode/*
|
||||||
|
!.vscode/extensions.json
|
||||||
|
.idea
|
||||||
|
*.suo
|
||||||
|
*.ntvs*
|
||||||
|
*.njsproj
|
||||||
|
*.sln
|
||||||
|
*.sw?
|
||||||
|
|
||||||
|
*.tsbuildinfo
|
||||||
|
|
||||||
|
.eslintcache
|
||||||
|
|
||||||
|
# Cypress
|
||||||
|
/cypress/videos/
|
||||||
|
/cypress/screenshots/
|
||||||
|
|
||||||
|
# Vitest
|
||||||
|
__screenshots__/
|
||||||
|
|
||||||
|
# Vite
|
||||||
|
*.timestamp-*-*.mjs
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||||
|
"plugins": ["eslint", "typescript", "unicorn", "oxc", "vue", "vitest"],
|
||||||
|
"env": {
|
||||||
|
"browser": true
|
||||||
|
},
|
||||||
|
"categories": {
|
||||||
|
"correctness": "error"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://json.schemastore.org/prettierrc",
|
||||||
|
"semi": false,
|
||||||
|
"singleQuote": true,
|
||||||
|
"printWidth": 100
|
||||||
|
}
|
||||||
Vendored
+10
@@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"recommendations": [
|
||||||
|
"Vue.volar",
|
||||||
|
"vitest.explorer",
|
||||||
|
"dbaeumer.vscode-eslint",
|
||||||
|
"EditorConfig.EditorConfig",
|
||||||
|
"oxc.oxc-vscode",
|
||||||
|
"esbenp.prettier-vscode"
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
FROM node:24-alpine AS build
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY package.json package-lock.json ./
|
||||||
|
RUN npm ci
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
RUN npm run build-only
|
||||||
|
|
||||||
|
# Sert le front et relaie /api, /admin et /static vers le back-end du même pod (port 8000).
|
||||||
|
FROM nginxinc/nginx-unprivileged:1.27-alpine
|
||||||
|
|
||||||
|
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
|
COPY --from=build /app/dist /usr/share/nginx/html
|
||||||
|
|
||||||
|
EXPOSE 8080
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# PRISM – front-end
|
||||||
|
|
||||||
|
Vue 3, Vite, TypeScript, Vue Router, vue-i18n, MapLibre GL JS, Bootstrap 5 (CSS seul) et Bootstrap Icons. Design repris des maquettes Penpot (charte ssmg.be, police Roboto).
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install
|
||||||
|
npm run dev # http://localhost:5173, /api relayé vers Django (localhost:8000)
|
||||||
|
npm run test:unit # Vitest
|
||||||
|
npm run type-check
|
||||||
|
npm run lint
|
||||||
|
npm run build
|
||||||
|
```
|
||||||
|
|
||||||
|
Le serveur Django doit tourner (`docker compose up -d` à la racine) et `CSRF_TRUSTED_ORIGINS` doit contenir `http://localhost:5173` (voir `.env.example`). Variable `API_PROXY_TARGET` pour relayer vers une autre adresse.
|
||||||
|
|
||||||
|
## Structure
|
||||||
|
|
||||||
|
- `src/api/` : client HTTP (session Django + jeton CSRF) et types des réponses.
|
||||||
|
- `src/composables/useAuth.ts` : utilisateur courant, connexion, déconnexion (état partagé par un `ref`).
|
||||||
|
- `src/router/` : routes et garde (`requiresAuth`, `guestOnly`).
|
||||||
|
- `src/views/` : `LoginView`, `AssessmentView`, `ErrorView` (403, 404).
|
||||||
|
- `src/components/` : `AddressForm`, `AlertBanner`, `ResultMap`, `FactorCard` (avec `ColorBadge`, `DetailList`, `InfoTabs`, `ReferenceList`), `AppHeader`, `AppFooter`.
|
||||||
|
- `src/locales/fr.json` : tous les textes de l'interface.
|
||||||
|
- `src/styles/main.css` : couleurs et surcharges Bootstrap issues des maquettes.
|
||||||
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
/// <reference types="vite/client" />
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import { globalIgnores } from 'eslint/config'
|
||||||
|
import { defineConfigWithVueTs, vueTsConfigs } from '@vue/eslint-config-typescript'
|
||||||
|
import pluginVue from 'eslint-plugin-vue'
|
||||||
|
import pluginVitest from '@vitest/eslint-plugin'
|
||||||
|
import pluginOxlint from 'eslint-plugin-oxlint'
|
||||||
|
import skipFormatting from 'eslint-config-prettier/flat'
|
||||||
|
|
||||||
|
// To allow more languages other than `ts` in `.vue` files, uncomment the following lines:
|
||||||
|
// import { configureVueProject } from '@vue/eslint-config-typescript'
|
||||||
|
// configureVueProject({ scriptLangs: ['ts', 'tsx'] })
|
||||||
|
// More info at https://github.com/vuejs/eslint-config-typescript/#advanced-setup
|
||||||
|
|
||||||
|
export default defineConfigWithVueTs(
|
||||||
|
{
|
||||||
|
name: 'app/files-to-lint',
|
||||||
|
files: ['**/*.{vue,ts,mts,tsx}'],
|
||||||
|
},
|
||||||
|
|
||||||
|
globalIgnores(['**/dist/**', '**/dist-ssr/**', '**/coverage/**']),
|
||||||
|
|
||||||
|
...pluginVue.configs['flat/essential'],
|
||||||
|
vueTsConfigs.recommended,
|
||||||
|
|
||||||
|
{
|
||||||
|
...pluginVitest.configs.recommended,
|
||||||
|
files: ['src/**/__tests__/*'],
|
||||||
|
},
|
||||||
|
|
||||||
|
...pluginOxlint.buildFromOxlintConfigFile('.oxlintrc.json'),
|
||||||
|
|
||||||
|
skipFormatting,
|
||||||
|
)
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="fr">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<!-- Favicon de la SSMG (ssmg.be) -->
|
||||||
|
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32.png">
|
||||||
|
<link rel="icon" type="image/png" sizes="57x57" href="/favicon-57.png">
|
||||||
|
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>PRISM – Environnement et santé</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="app"></div>
|
||||||
|
<script type="module" src="/src/main.ts"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
server {
|
||||||
|
listen 8080;
|
||||||
|
server_name _;
|
||||||
|
|
||||||
|
root /usr/share/nginx/html;
|
||||||
|
index index.html;
|
||||||
|
|
||||||
|
# Le back-end tourne dans le même pod que ce conteneur.
|
||||||
|
location ~ ^/(api|admin|static)/ {
|
||||||
|
proxy_pass http://127.0.0.1:8000;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
|
||||||
|
proxy_read_timeout 60s;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Fichiers versionnés par Vite : cache long.
|
||||||
|
location /assets/ {
|
||||||
|
try_files $uri =404;
|
||||||
|
add_header Cache-Control "public, max-age=31536000, immutable";
|
||||||
|
}
|
||||||
|
|
||||||
|
# Application monopage : toute autre route retombe sur index.html.
|
||||||
|
location / {
|
||||||
|
try_files $uri /index.html;
|
||||||
|
add_header Cache-Control "no-cache";
|
||||||
|
}
|
||||||
|
}
|
||||||
Generated
+6771
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,55 @@
|
|||||||
|
{
|
||||||
|
"name": "prism-frontend",
|
||||||
|
"version": "0.0.0",
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "run-p type-check \"build-only {@}\" --",
|
||||||
|
"preview": "vite preview",
|
||||||
|
"test:unit": "vitest",
|
||||||
|
"build-only": "vite build",
|
||||||
|
"type-check": "vue-tsc --build",
|
||||||
|
"lint": "run-s \"lint:*\"",
|
||||||
|
"lint:oxlint": "oxlint . --fix",
|
||||||
|
"lint:eslint": "eslint . --fix --cache",
|
||||||
|
"format": "prettier --write --experimental-cli src/"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@fontsource/roboto": "^5.3.0",
|
||||||
|
"bootstrap": "^5.3.9",
|
||||||
|
"bootstrap-icons": "^1.13.2",
|
||||||
|
"maplibre-gl": "^6.19.0",
|
||||||
|
"vue": "^3.5.42",
|
||||||
|
"vue-i18n": "^11.4.23",
|
||||||
|
"vue-router": "^5.3.1"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@tsconfig/node24": "^24.0.5",
|
||||||
|
"@types/jsdom": "^30.0.0",
|
||||||
|
"@types/node": "^24.13.4",
|
||||||
|
"@vitejs/plugin-vue": "^6.0.8",
|
||||||
|
"@vitest/eslint-plugin": "^1.6.27",
|
||||||
|
"@vue/eslint-config-typescript": "^14.9.0",
|
||||||
|
"@vue/test-utils": "^2.5.0",
|
||||||
|
"@vue/tsconfig": "^0.9.1",
|
||||||
|
"eslint": "^10.10.0",
|
||||||
|
"eslint-config-prettier": "^10.1.8",
|
||||||
|
"eslint-plugin-oxlint": "~1.82.0",
|
||||||
|
"eslint-plugin-vue": "~10.11.0",
|
||||||
|
"jiti": "^2.7.0",
|
||||||
|
"jsdom": "^30.0.1",
|
||||||
|
"npm-run-all2": "^9.0.3",
|
||||||
|
"oxlint": "~1.82.0",
|
||||||
|
"prettier": "3.9.6",
|
||||||
|
"typescript": "~6.0.0",
|
||||||
|
"vite": "^8.2.2",
|
||||||
|
"vite-plugin-vue-devtools": "^8.2.1",
|
||||||
|
"vitest": "^4.1.11",
|
||||||
|
"vue-eslint-parser": "^10.4.1",
|
||||||
|
"vue-tsc": "^3.3.11"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "^22.18.0 || >=24.12.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 6.8 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.0 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 2.4 KiB |
@@ -0,0 +1,14 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import AppFooter from '@/components/AppFooter.vue'
|
||||||
|
import AppHeader from '@/components/AppHeader.vue'
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="d-flex flex-column min-vh-100">
|
||||||
|
<AppHeader />
|
||||||
|
<main class="flex-grow-1">
|
||||||
|
<RouterView />
|
||||||
|
</main>
|
||||||
|
<AppFooter />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import { mount } from '@vue/test-utils'
|
||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import { defineComponent, ref } from 'vue'
|
||||||
|
|
||||||
|
import CodeInput from '@/components/CodeInput.vue'
|
||||||
|
|
||||||
|
// Parent avec v-model : reproduit l'usage réel (la valeur ne remonte qu'au rendu du parent).
|
||||||
|
function mountWithModel() {
|
||||||
|
const completed: string[] = []
|
||||||
|
const Parent = defineComponent({
|
||||||
|
components: { CodeInput },
|
||||||
|
setup: () => ({ code: ref(''), completed }),
|
||||||
|
template: '<CodeInput v-model="code" label="Code" @complete="completed.push($event)" />',
|
||||||
|
})
|
||||||
|
const wrapper = mount(Parent, { attachTo: document.body })
|
||||||
|
return { wrapper, completed }
|
||||||
|
}
|
||||||
|
|
||||||
|
function paste(input: Element, text: string) {
|
||||||
|
const event = new Event('paste', { bubbles: true, cancelable: true }) as ClipboardEvent
|
||||||
|
Object.defineProperty(event, 'clipboardData', { value: { getData: () => text } })
|
||||||
|
input.dispatchEvent(event)
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('CodeInput', () => {
|
||||||
|
it('affiche six cases étiquetées', () => {
|
||||||
|
const { wrapper } = mountWithModel()
|
||||||
|
const digits = wrapper.findAll('input')
|
||||||
|
expect(digits).toHaveLength(6)
|
||||||
|
expect(digits[0]!.attributes('autocomplete')).toBe('one-time-code')
|
||||||
|
expect(digits[5]!.attributes('aria-label')).toBe('Code – chiffre 6')
|
||||||
|
wrapper.unmount()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('répartit un code collé et émet complete', async () => {
|
||||||
|
const { wrapper, completed } = mountWithModel()
|
||||||
|
paste(wrapper.find('input').element, '123 456')
|
||||||
|
await wrapper.vm.$nextTick()
|
||||||
|
expect(wrapper.findAll('input').map((i) => (i.element as HTMLInputElement).value)).toEqual([
|
||||||
|
'1',
|
||||||
|
'2',
|
||||||
|
'3',
|
||||||
|
'4',
|
||||||
|
'5',
|
||||||
|
'6',
|
||||||
|
])
|
||||||
|
expect(completed).toEqual(['123456'])
|
||||||
|
wrapper.unmount()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('émet complete à la saisie du dernier chiffre', async () => {
|
||||||
|
const { wrapper, completed } = mountWithModel()
|
||||||
|
const inputs = wrapper.findAll('input')
|
||||||
|
for (const [index, digit] of [...'987654'].entries()) {
|
||||||
|
await inputs[index]!.setValue(digit)
|
||||||
|
}
|
||||||
|
expect(completed).toEqual(['987654'])
|
||||||
|
wrapper.unmount()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('ignore les caractères non numériques', async () => {
|
||||||
|
const { wrapper, completed } = mountWithModel()
|
||||||
|
await wrapper.find('input').setValue('a')
|
||||||
|
expect((wrapper.find('input').element as HTMLInputElement).value).toBe('')
|
||||||
|
expect(completed).toEqual([])
|
||||||
|
wrapper.unmount()
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
|
||||||
|
import FactorCard from '@/components/FactorCard.vue'
|
||||||
|
|
||||||
|
import { factor, mountWithPlugins } from './helpers'
|
||||||
|
|
||||||
|
describe('FactorCard', () => {
|
||||||
|
it('affiche le niveau, le résumé, le détail et les références', () => {
|
||||||
|
const wrapper = mountWithPlugins(FactorCard, { props: { factor: factor() } })
|
||||||
|
expect(wrapper.find('h2').text()).toBe('Pollution sonore')
|
||||||
|
expect(wrapper.find('.color-badge').text()).toBe('Impact faible')
|
||||||
|
expect(wrapper.find('.color-badge').classes()).toContain('level-1')
|
||||||
|
expect(wrapper.find('.summary').text()).toBe('moins de 55 dB (Lden)')
|
||||||
|
expect(wrapper.find('dl').text()).toContain('Route')
|
||||||
|
expect(wrapper.find('.references a').attributes('href')).toBe('https://eea.europa.eu')
|
||||||
|
})
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
[2, 'Impact modéré'],
|
||||||
|
[3, 'Impact élevé'],
|
||||||
|
[4, 'Impact très élevé'],
|
||||||
|
])('niveau %i → « %s »', (level, text) => {
|
||||||
|
const wrapper = mountWithPlugins(FactorCard, { props: { factor: factor({ level }) } })
|
||||||
|
expect(wrapper.find('.color-badge').text()).toBe(text)
|
||||||
|
expect(wrapper.find('.factor-dot').classes()).toContain(`level-${level}`)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('affiche « Niveau non défini » sans classe de seuil', () => {
|
||||||
|
const wrapper = mountWithPlugins(FactorCard, {
|
||||||
|
props: { factor: factor({ level: null, color: null }) },
|
||||||
|
})
|
||||||
|
expect(wrapper.find('.color-badge').text()).toBe('Niveau non défini')
|
||||||
|
expect(wrapper.find('.factor-dot').classes()).toContain('level-none')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('source indisponible : message, contour pointillé et bouton Réessayer', async () => {
|
||||||
|
const wrapper = mountWithPlugins(FactorCard, {
|
||||||
|
props: { factor: factor({ code: 'radon', label: 'Radon', status: 'unavailable' }) },
|
||||||
|
})
|
||||||
|
expect(wrapper.classes()).toContain('unavailable')
|
||||||
|
expect(wrapper.find('.color-badge').text()).toBe('Donnée indisponible')
|
||||||
|
expect(wrapper.text()).toContain('Le service de données « radon » ne répond pas')
|
||||||
|
expect(wrapper.find('dl').exists()).toBe(false)
|
||||||
|
|
||||||
|
await wrapper.find('button').trigger('click')
|
||||||
|
expect(wrapper.emitted('retry')).toHaveLength(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('donnée absente : message sans bouton Réessayer', () => {
|
||||||
|
const wrapper = mountWithPlugins(FactorCard, {
|
||||||
|
props: { factor: factor({ status: 'no_data' }) },
|
||||||
|
})
|
||||||
|
expect(wrapper.find('.color-badge').text()).toBe('Donnée absente')
|
||||||
|
expect(wrapper.text()).toContain('Aucune donnée')
|
||||||
|
expect(wrapper.find('button').exists()).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
|
||||||
|
import ResultMap from '@/components/ResultMap.vue'
|
||||||
|
|
||||||
|
import { mountWithPlugins } from './helpers'
|
||||||
|
|
||||||
|
// MapLibre a besoin de WebGL, absent de jsdom : on vérifie les appels.
|
||||||
|
type Fn = (...args: unknown[]) => unknown
|
||||||
|
|
||||||
|
const mapInstance = {
|
||||||
|
addControl: vi.fn<Fn>(),
|
||||||
|
resize: vi.fn<Fn>(),
|
||||||
|
jumpTo: vi.fn<Fn>(),
|
||||||
|
setLayoutProperty: vi.fn<Fn>(),
|
||||||
|
remove: vi.fn<Fn>(),
|
||||||
|
}
|
||||||
|
const marker = {
|
||||||
|
setLngLat: vi.fn<Fn>().mockReturnThis(),
|
||||||
|
addTo: vi.fn<Fn>().mockReturnThis(),
|
||||||
|
remove: vi.fn<Fn>(),
|
||||||
|
}
|
||||||
|
|
||||||
|
vi.mock('maplibre-gl', () => ({
|
||||||
|
Map: vi.fn<() => typeof mapInstance>(function () {
|
||||||
|
return mapInstance
|
||||||
|
}),
|
||||||
|
Marker: vi.fn<() => typeof marker>(function () {
|
||||||
|
return marker
|
||||||
|
}),
|
||||||
|
NavigationControl: vi.fn<Fn>(),
|
||||||
|
ScaleControl: vi.fn<Fn>(),
|
||||||
|
setWorkerUrl: vi.fn<Fn>(),
|
||||||
|
}))
|
||||||
|
|
||||||
|
describe('ResultMap', () => {
|
||||||
|
// On ne vide que les mocks de la carte : l'appel à setWorkerUrl a lieu à l'import.
|
||||||
|
beforeEach(() => {
|
||||||
|
for (const fn of [...Object.values(mapInstance), ...Object.values(marker)]) fn.mockClear()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('indique à MapLibre où trouver son worker', async () => {
|
||||||
|
const { setWorkerUrl } = await import('maplibre-gl')
|
||||||
|
expect(setWorkerUrl).toHaveBeenCalledWith(expect.stringContaining('maplibre-gl-worker'))
|
||||||
|
})
|
||||||
|
|
||||||
|
it('occupe toute la place tant qu’aucune adresse n’est analysée', async () => {
|
||||||
|
const wrapper = mountWithPlugins(ResultMap, { props: { location: null } })
|
||||||
|
expect(wrapper.classes()).toContain('expanded')
|
||||||
|
await wrapper.setProps({ location: { lat: 50.668, lon: 4.617, region: 'WAL' } })
|
||||||
|
expect(wrapper.classes()).not.toContain('expanded')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('interroge les trois plages d’échelle de l’aléa d’inondation', async () => {
|
||||||
|
const { Map } = await import('maplibre-gl')
|
||||||
|
mountWithPlugins(ResultMap, { props: { location: null } })
|
||||||
|
const style = vi.mocked(Map).mock.lastCall![0].style as {
|
||||||
|
sources: Record<string, { tiles?: string[] }>
|
||||||
|
}
|
||||||
|
expect(style.sources.flood!.tiles![0]).toContain('layers=1%2C2%2C3')
|
||||||
|
expect(style.sources.flood!.tiles![0]).toContain('bbox={bbox-epsg-3857}')
|
||||||
|
})
|
||||||
|
|
||||||
|
it("centre la carte et place le marqueur sur l'adresse", async () => {
|
||||||
|
const wrapper = mountWithPlugins(ResultMap, { props: { location: null } })
|
||||||
|
expect(marker.setLngLat).not.toHaveBeenCalled()
|
||||||
|
|
||||||
|
await wrapper.setProps({ location: { lat: 50.668, lon: 4.617, region: 'WAL' } })
|
||||||
|
|
||||||
|
expect(marker.setLngLat).toHaveBeenCalledWith([4.617, 50.668])
|
||||||
|
expect(mapInstance.jumpTo).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({ center: [4.617, 50.668], zoom: 15 }),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('affiche ou masque une couche WMS', async () => {
|
||||||
|
const wrapper = mountWithPlugins(ResultMap, { props: { location: null } })
|
||||||
|
await wrapper.find('#layer-noise').setValue(true)
|
||||||
|
expect(mapInstance.setLayoutProperty).toHaveBeenCalledWith('noise', 'visibility', 'visible')
|
||||||
|
await wrapper.find('#layer-flood').trigger('change')
|
||||||
|
expect(mapInstance.setLayoutProperty).toHaveBeenCalledWith('flood', 'visibility', 'none')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('libère la carte au démontage', () => {
|
||||||
|
mountWithPlugins(ResultMap, { props: { location: null } }).unmount()
|
||||||
|
expect(mapInstance.remove).toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
|
||||||
|
import { api, ApiError, csrfToken } from '@/api/client'
|
||||||
|
|
||||||
|
import { ASSESSMENT, jsonResponse, mockFetch } from './helpers'
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.unstubAllGlobals()
|
||||||
|
document.cookie = 'csrftoken=; expires=Thu, 01 Jan 1970 00:00:00 GMT'
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('csrfToken', () => {
|
||||||
|
it('lit le cookie csrftoken', () => {
|
||||||
|
document.cookie = 'autre=1'
|
||||||
|
document.cookie = 'csrftoken=abc123'
|
||||||
|
expect(csrfToken()).toBe('abc123')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('renvoie une chaîne vide sans cookie', () => {
|
||||||
|
expect(csrfToken()).toBe('')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('api', () => {
|
||||||
|
it('envoie le jeton CSRF et le corps JSON sur un POST', async () => {
|
||||||
|
document.cookie = 'csrftoken=jeton'
|
||||||
|
const fetch = mockFetch(jsonResponse(200, ASSESSMENT))
|
||||||
|
|
||||||
|
const result = await api.assess('Place de l’Université 1')
|
||||||
|
|
||||||
|
expect(result).toEqual(ASSESSMENT)
|
||||||
|
const [url, init] = fetch.mock.calls[0]!
|
||||||
|
expect(url).toBe('/api/v1/assessments/')
|
||||||
|
expect(init?.method).toBe('POST')
|
||||||
|
expect(init?.credentials).toBe('same-origin')
|
||||||
|
expect(init?.headers).toMatchObject({
|
||||||
|
'X-CSRFToken': 'jeton',
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
})
|
||||||
|
expect(JSON.parse(init?.body as string)).toEqual({ address: 'Place de l’Université 1' })
|
||||||
|
})
|
||||||
|
|
||||||
|
it("n'envoie pas de jeton CSRF sur un GET", async () => {
|
||||||
|
const fetch = mockFetch(jsonResponse(200, {}))
|
||||||
|
await api.me()
|
||||||
|
expect(fetch.mock.calls[0]![1]?.headers).not.toHaveProperty('X-CSRFToken')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('accepte une réponse 204 sans corps', async () => {
|
||||||
|
mockFetch(new Response(null, { status: 204 }))
|
||||||
|
await expect(api.logout()).resolves.toBeUndefined()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('lève une ApiError avec le statut, le message et le code', async () => {
|
||||||
|
mockFetch(jsonResponse(404, { code: 'address_not_found', detail: 'Adresse introuvable.' }))
|
||||||
|
const error = await api.assess('nulle part').catch((e) => e)
|
||||||
|
expect(error).toBeInstanceOf(ApiError)
|
||||||
|
expect(error.status).toBe(404)
|
||||||
|
expect(error.code).toBe('address_not_found')
|
||||||
|
expect(error.message).toBe('Adresse introuvable.')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('gère une erreur sans corps JSON', async () => {
|
||||||
|
mockFetch(new Response('<html>403</html>', { status: 403 }))
|
||||||
|
const error = await api.me().catch((e) => e)
|
||||||
|
expect(error).toBeInstanceOf(ApiError)
|
||||||
|
expect(error.message).toBe('HTTP 403')
|
||||||
|
expect(error.code).toBeUndefined()
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
|
||||||
|
import AddressForm from '@/components/AddressForm.vue'
|
||||||
|
import DetailList from '@/components/DetailList.vue'
|
||||||
|
import InfoTabs from '@/components/InfoTabs.vue'
|
||||||
|
import ReferenceList from '@/components/ReferenceList.vue'
|
||||||
|
|
||||||
|
import { factor, mountWithPlugins } from './helpers'
|
||||||
|
|
||||||
|
describe('DetailList', () => {
|
||||||
|
it('affiche une pastille rouge pour un dépassement et verte sinon', () => {
|
||||||
|
const wrapper = mountWithPlugins(DetailList, {
|
||||||
|
props: {
|
||||||
|
details: [
|
||||||
|
{ label: 'PM2,5', value: '7,1 µg/m³ (seuil 5)', status: 'exceeded' },
|
||||||
|
{ label: 'PM10', value: '12,0 µg/m³ (seuil 15)', status: 'ok' },
|
||||||
|
{ label: 'O₃', value: '50,1 µg/m³' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
const rows = wrapper.findAll('.detail-row')
|
||||||
|
expect(rows).toHaveLength(3)
|
||||||
|
expect(rows[0]!.find('.dot').classes()).toContain('level-4')
|
||||||
|
expect(rows[0]!.text()).toContain('(dépassé)')
|
||||||
|
expect(rows[1]!.find('.dot').classes()).toContain('level-1')
|
||||||
|
expect(rows[2]!.find('.dot').exists()).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it("n'affiche rien sans détail", () => {
|
||||||
|
expect(
|
||||||
|
mountWithPlugins(DetailList, { props: { details: [] } })
|
||||||
|
.find('dl')
|
||||||
|
.exists(),
|
||||||
|
).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('InfoTabs', () => {
|
||||||
|
it('affiche les effets sur la santé par défaut, une ligne par puce', () => {
|
||||||
|
const wrapper = mountWithPlugins(InfoTabs, { props: { tabs: factor().tabs } })
|
||||||
|
expect(wrapper.find('[aria-selected="true"]').text()).toBe('Effets sur la santé')
|
||||||
|
expect(wrapper.findAll('.bullets li').map((li) => li.text())).toEqual([
|
||||||
|
'Gêne, perturbation du sommeil',
|
||||||
|
'Effets cardiovasculaires',
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('change d’onglet', async () => {
|
||||||
|
const wrapper = mountWithPlugins(InfoTabs, { props: { tabs: factor().tabs } })
|
||||||
|
const [, actions, legend] = wrapper.findAll('[role="tab"]')
|
||||||
|
|
||||||
|
await actions!.trigger('click')
|
||||||
|
expect(actions!.attributes('aria-selected')).toBe('true')
|
||||||
|
expect(wrapper.find('.bullets').text()).toBe('Isolation acoustique')
|
||||||
|
|
||||||
|
await legend!.trigger('click')
|
||||||
|
expect(wrapper.find('.scale').text()).toBe('< 55 dB')
|
||||||
|
expect(wrapper.find('.source').text()).toBe('Source : WalOnMap')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('indique un contenu en attente de validation', () => {
|
||||||
|
const tabs = { ...factor().tabs, health_effects: '' }
|
||||||
|
const wrapper = mountWithPlugins(InfoTabs, { props: { tabs } })
|
||||||
|
expect(wrapper.find('.empty').text()).toContain('en cours de validation')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('ReferenceList', () => {
|
||||||
|
it('numérote les références et ouvre les liens dans un nouvel onglet', () => {
|
||||||
|
const wrapper = mountWithPlugins(ReferenceList, {
|
||||||
|
props: {
|
||||||
|
references: [
|
||||||
|
{ n: 1, title: 'EEA 2020', url: 'https://eea.europa.eu' },
|
||||||
|
{ n: 2, title: 'Canopea 2021', url: '' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
expect(wrapper.text()).toContain('1. EEA 2020')
|
||||||
|
expect(wrapper.text()).toContain('2. Canopea 2021')
|
||||||
|
const link = wrapper.find('a')
|
||||||
|
expect(link.attributes('target')).toBe('_blank')
|
||||||
|
expect(link.attributes('rel')).toContain('noopener')
|
||||||
|
})
|
||||||
|
|
||||||
|
it("n'affiche rien sans référence", () => {
|
||||||
|
const wrapper = mountWithPlugins(ReferenceList, { props: { references: [] } })
|
||||||
|
expect(wrapper.find('.references').exists()).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('AddressForm', () => {
|
||||||
|
it("émet l'adresse sans espaces superflus", async () => {
|
||||||
|
const wrapper = mountWithPlugins(AddressForm, { props: { loading: false } })
|
||||||
|
await wrapper.find('input').setValue(' Rue de la Loi 16, 1000 Bruxelles ')
|
||||||
|
await wrapper.find('form').trigger('submit')
|
||||||
|
expect(wrapper.emitted('submit')).toEqual([['Rue de la Loi 16, 1000 Bruxelles']])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('désactive le bouton sans adresse ou pendant le chargement', async () => {
|
||||||
|
const wrapper = mountWithPlugins(AddressForm, { props: { loading: false } })
|
||||||
|
expect(wrapper.find('button').attributes('disabled')).toBeDefined()
|
||||||
|
await wrapper.find('input').setValue('Rue')
|
||||||
|
expect(wrapper.find('button').attributes('disabled')).toBeUndefined()
|
||||||
|
await wrapper.setProps({ loading: true })
|
||||||
|
expect(wrapper.find('button').text()).toBe('Analyse…')
|
||||||
|
expect(wrapper.find('button').attributes('disabled')).toBeDefined()
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
import { mount, type ComponentMountingOptions } from '@vue/test-utils'
|
||||||
|
import { vi } from 'vitest'
|
||||||
|
import type { Component } from 'vue'
|
||||||
|
import { createMemoryHistory, createRouter } from 'vue-router'
|
||||||
|
|
||||||
|
import type { Assessment, FactorResult, User } from '@/api/types'
|
||||||
|
import i18n from '@/i18n'
|
||||||
|
import { routes } from '@/router'
|
||||||
|
|
||||||
|
export const USER: User = {
|
||||||
|
email: 'medecin@exemple.be',
|
||||||
|
first_name: 'Jean',
|
||||||
|
last_name: 'Dupont',
|
||||||
|
roles: ['Médecin'],
|
||||||
|
is_staff: false,
|
||||||
|
mfa_enabled: false,
|
||||||
|
}
|
||||||
|
|
||||||
|
export function factor(overrides: Partial<FactorResult> = {}): FactorResult {
|
||||||
|
return {
|
||||||
|
code: 'noise',
|
||||||
|
label: 'Pollution sonore',
|
||||||
|
status: 'ok',
|
||||||
|
level: 1,
|
||||||
|
color: 'green',
|
||||||
|
summary: 'moins de 55 dB (Lden)',
|
||||||
|
details: [{ label: 'Route', value: 'moins de 55 dB' }],
|
||||||
|
tabs: {
|
||||||
|
health_effects: 'Gêne, perturbation du sommeil\nEffets cardiovasculaires',
|
||||||
|
actions: 'Isolation acoustique',
|
||||||
|
legend: {
|
||||||
|
source: 'WalOnMap',
|
||||||
|
text: '',
|
||||||
|
scale: [{ level: 1, color: 'green', label: '< 55 dB' }],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
references: [{ n: 1, title: 'EEA 2020', url: 'https://eea.europa.eu' }],
|
||||||
|
...overrides,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ASSESSMENT: Assessment = {
|
||||||
|
location: { lat: 50.668, lon: 4.617, region: 'WAL' },
|
||||||
|
factors: [
|
||||||
|
factor(),
|
||||||
|
factor({ code: 'radon', label: 'Radon', status: 'unavailable', level: null, color: null }),
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Réponse JSON simulée pour `fetch`. */
|
||||||
|
export function jsonResponse(status: number, body?: unknown): Response {
|
||||||
|
return new Response(body === undefined ? null : JSON.stringify(body), {
|
||||||
|
status,
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mockFetch(...responses: Response[]) {
|
||||||
|
const fn = vi.fn<typeof fetch>()
|
||||||
|
for (const response of responses) fn.mockResolvedValueOnce(response)
|
||||||
|
vi.stubGlobal('fetch', fn)
|
||||||
|
return fn
|
||||||
|
}
|
||||||
|
|
||||||
|
export function makeRouter() {
|
||||||
|
return createRouter({ history: createMemoryHistory(), routes })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mountWithPlugins<C extends Component>(
|
||||||
|
component: C,
|
||||||
|
options: ComponentMountingOptions<C> & { router?: ReturnType<typeof makeRouter> } = {},
|
||||||
|
) {
|
||||||
|
const { router = makeRouter(), ...rest } = options
|
||||||
|
return mount(component, {
|
||||||
|
...rest,
|
||||||
|
global: { plugins: [i18n, router], ...rest.global },
|
||||||
|
} as ComponentMountingOptions<C>)
|
||||||
|
}
|
||||||
@@ -0,0 +1,245 @@
|
|||||||
|
import { flushPromises } from '@vue/test-utils'
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
|
||||||
|
import { resetAuth, useAuth } from '@/composables/useAuth'
|
||||||
|
import MfaPanel from '@/components/MfaPanel.vue'
|
||||||
|
import AccountView from '@/views/AccountView.vue'
|
||||||
|
import LoginView from '@/views/LoginView.vue'
|
||||||
|
|
||||||
|
import { jsonResponse, makeRouter, mockFetch, mountWithPlugins, USER } from './helpers'
|
||||||
|
|
||||||
|
beforeEach(resetAuth)
|
||||||
|
afterEach(() => vi.unstubAllGlobals())
|
||||||
|
|
||||||
|
const SETUP = {
|
||||||
|
secret: 'ABCD EFGH IJKL MNOP',
|
||||||
|
otpauth_url: 'otpauth://totp/PRISM:x?secret=ABCD',
|
||||||
|
qr_code: 'data:image/svg+xml;base64,PHN2Zy8+',
|
||||||
|
}
|
||||||
|
const CODES = Array.from({ length: 8 }, (_, i) => `AAAA-000${i}`)
|
||||||
|
|
||||||
|
async function pasteCode(wrapper: ReturnType<typeof mountWithPlugins>, code: string) {
|
||||||
|
const event = new Event('paste', { bubbles: true, cancelable: true })
|
||||||
|
Object.defineProperty(event, 'clipboardData', { value: { getData: () => code } })
|
||||||
|
wrapper.find('.digit').element.dispatchEvent(event)
|
||||||
|
await flushPromises()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function signIn(user = USER) {
|
||||||
|
mockFetch(jsonResponse(200, user))
|
||||||
|
await useAuth().load()
|
||||||
|
vi.unstubAllGlobals()
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('LoginView – seconde étape', () => {
|
||||||
|
async function toSecondStep() {
|
||||||
|
const router = makeRouter()
|
||||||
|
const push = vi.spyOn(router, 'push').mockResolvedValue(undefined)
|
||||||
|
const wrapper = mountWithPlugins(LoginView, { router, attachTo: document.body })
|
||||||
|
await wrapper.find('#email').setValue('medecin@exemple.be')
|
||||||
|
await wrapper.find('#password').setValue('secret')
|
||||||
|
await wrapper.find('form').trigger('submit')
|
||||||
|
await flushPromises()
|
||||||
|
return { wrapper, push }
|
||||||
|
}
|
||||||
|
|
||||||
|
it('demande le code quand la 2FA est active, sans ouvrir de session', async () => {
|
||||||
|
const fetch = mockFetch(jsonResponse(200, { mfa_required: true, user: null }))
|
||||||
|
const { wrapper, push } = await toSecondStep()
|
||||||
|
|
||||||
|
expect(wrapper.find('h1').text()).toBe('Vérification en deux étapes')
|
||||||
|
expect(wrapper.findAll('.digit')).toHaveLength(6)
|
||||||
|
expect(fetch).toHaveBeenCalledTimes(1)
|
||||||
|
expect(push).not.toHaveBeenCalled()
|
||||||
|
expect(useAuth().user.value).toBeNull()
|
||||||
|
wrapper.unmount()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('valide automatiquement un code complet puis redirige', async () => {
|
||||||
|
const fetch = mockFetch(
|
||||||
|
jsonResponse(200, { mfa_required: true, user: null }),
|
||||||
|
jsonResponse(200, { mfa_required: false, user: USER }),
|
||||||
|
jsonResponse(200, USER),
|
||||||
|
)
|
||||||
|
const { wrapper, push } = await toSecondStep()
|
||||||
|
|
||||||
|
await pasteCode(wrapper, '123456')
|
||||||
|
|
||||||
|
expect(fetch.mock.calls[1]![0]).toBe('/api/v1/auth/2fa/verify/')
|
||||||
|
expect(JSON.parse(fetch.mock.calls[1]![1]!.body as string)).toEqual({ code: '123456' })
|
||||||
|
expect(useAuth().user.value).toEqual(USER)
|
||||||
|
expect(push).toHaveBeenCalledWith({ name: 'assessment' })
|
||||||
|
wrapper.unmount()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('code faux : message et cases vidées', async () => {
|
||||||
|
mockFetch(
|
||||||
|
jsonResponse(200, { mfa_required: true, user: null }),
|
||||||
|
jsonResponse(400, { code: 'invalid_code', detail: 'Code incorrect ou expiré.' }),
|
||||||
|
)
|
||||||
|
const { wrapper } = await toSecondStep()
|
||||||
|
|
||||||
|
await pasteCode(wrapper, '000000')
|
||||||
|
|
||||||
|
expect(wrapper.find('[role="alert"]').text()).toBe('Code incorrect ou expiré.')
|
||||||
|
expect(wrapper.findAll('.digit').map((d) => (d.element as HTMLInputElement).value)).toEqual(
|
||||||
|
Array(6).fill(''),
|
||||||
|
)
|
||||||
|
wrapper.unmount()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('code de secours', async () => {
|
||||||
|
const fetch = mockFetch(
|
||||||
|
jsonResponse(200, { mfa_required: true, user: null }),
|
||||||
|
jsonResponse(200, { mfa_required: false, user: USER }),
|
||||||
|
jsonResponse(200, USER),
|
||||||
|
)
|
||||||
|
const { wrapper, push } = await toSecondStep()
|
||||||
|
|
||||||
|
await wrapper
|
||||||
|
.findAll('button')
|
||||||
|
.find((b) => b.text() === 'Utiliser un code de secours')!
|
||||||
|
.trigger('click')
|
||||||
|
await wrapper.find('#recovery').setValue('ABCD-EFGH')
|
||||||
|
await wrapper.find('form').trigger('submit')
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(JSON.parse(fetch.mock.calls[1]![1]!.body as string)).toEqual({ code: 'ABCD-EFGH' })
|
||||||
|
expect(push).toHaveBeenCalled()
|
||||||
|
wrapper.unmount()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('étape expirée : retour au mot de passe', async () => {
|
||||||
|
mockFetch(
|
||||||
|
jsonResponse(200, { mfa_required: true, user: null }),
|
||||||
|
jsonResponse(400, { code: 'mfa_expired', detail: 'Recommencez la connexion.' }),
|
||||||
|
)
|
||||||
|
const { wrapper } = await toSecondStep()
|
||||||
|
await pasteCode(wrapper, '123456')
|
||||||
|
|
||||||
|
expect(wrapper.find('h1').text()).toBe('Connexion')
|
||||||
|
expect(wrapper.find('[role="alert"]').text()).toBe('Recommencez la connexion.')
|
||||||
|
wrapper.unmount()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('MfaPanel', () => {
|
||||||
|
it('active la 2FA : QR code, code, puis codes de secours', async () => {
|
||||||
|
await signIn()
|
||||||
|
const fetch = mockFetch(
|
||||||
|
jsonResponse(200, SETUP),
|
||||||
|
jsonResponse(200, { recovery_codes: CODES }),
|
||||||
|
jsonResponse(200, { ...USER, mfa_enabled: true }),
|
||||||
|
)
|
||||||
|
const wrapper = mountWithPlugins(MfaPanel, { attachTo: document.body })
|
||||||
|
expect(wrapper.find('.status').text()).toBe('Désactivée')
|
||||||
|
|
||||||
|
await wrapper.find('button').trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
expect(wrapper.find('img.qr').attributes('src')).toBe(SETUP.qr_code)
|
||||||
|
expect(wrapper.text()).toContain('ABCD EFGH IJKL MNOP')
|
||||||
|
|
||||||
|
await pasteCode(wrapper, '123456')
|
||||||
|
await wrapper.find('form').trigger('submit')
|
||||||
|
await flushPromises()
|
||||||
|
expect(JSON.parse(fetch.mock.calls[1]![1]!.body as string)).toEqual({ code: '123456' })
|
||||||
|
expect(wrapper.findAll('.codes li').map((li) => li.text())).toEqual(CODES)
|
||||||
|
|
||||||
|
const finish = wrapper.findAll('button').find((b) => b.text() === 'Terminer')!
|
||||||
|
expect(finish.attributes('disabled')).toBeDefined()
|
||||||
|
await wrapper.find('#codes-saved').setValue(true)
|
||||||
|
await finish.trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(wrapper.find('.status').text()).toBe('Activée')
|
||||||
|
expect(wrapper.text()).toContain('La double authentification est activée.')
|
||||||
|
wrapper.unmount()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('désactive avec mot de passe et code', async () => {
|
||||||
|
await signIn({ ...USER, mfa_enabled: true })
|
||||||
|
const fetch = mockFetch(jsonResponse(204), jsonResponse(200, { ...USER, mfa_enabled: false }))
|
||||||
|
const wrapper = mountWithPlugins(MfaPanel)
|
||||||
|
|
||||||
|
await wrapper
|
||||||
|
.findAll('button')
|
||||||
|
.find((b) => b.text() === 'Désactiver')!
|
||||||
|
.trigger('click')
|
||||||
|
await wrapper.find('#mfa-password').setValue('secret')
|
||||||
|
await wrapper.find('#mfa-code').setValue('AAAA-0001')
|
||||||
|
await wrapper.find('form').trigger('submit')
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(JSON.parse(fetch.mock.calls[0]![1]!.body as string)).toEqual({
|
||||||
|
password: 'secret',
|
||||||
|
code: 'AAAA-0001',
|
||||||
|
})
|
||||||
|
expect(wrapper.find('.status').text()).toBe('Désactivée')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('compte du personnel : 2FA obligatoire, pas de bouton Désactiver', async () => {
|
||||||
|
await signIn({ ...USER, is_staff: true, mfa_enabled: true })
|
||||||
|
const wrapper = mountWithPlugins(MfaPanel)
|
||||||
|
expect(wrapper.findAll('button').map((b) => b.text())).not.toContain('Désactiver')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('signale la 2FA obligatoire à un compte du personnel qui ne l’a pas', async () => {
|
||||||
|
await signIn({ ...USER, is_staff: true })
|
||||||
|
const wrapper = mountWithPlugins(MfaPanel)
|
||||||
|
expect(wrapper.find('[role="alert"]').text()).toContain('obligatoire')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('régénère les codes de secours', async () => {
|
||||||
|
await signIn({ ...USER, mfa_enabled: true })
|
||||||
|
mockFetch(jsonResponse(200, { recovery_codes: CODES }))
|
||||||
|
const wrapper = mountWithPlugins(MfaPanel)
|
||||||
|
|
||||||
|
await wrapper
|
||||||
|
.findAll('button')
|
||||||
|
.find((b) => b.text() === 'Régénérer les codes de secours')!
|
||||||
|
.trigger('click')
|
||||||
|
await wrapper.find('#mfa-code').setValue('123456')
|
||||||
|
await wrapper.find('form').trigger('submit')
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(wrapper.findAll('.codes li')).toHaveLength(8)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('AccountView', () => {
|
||||||
|
it('affiche le profil et change le mot de passe', async () => {
|
||||||
|
await signIn()
|
||||||
|
const fetch = mockFetch(jsonResponse(204))
|
||||||
|
const wrapper = mountWithPlugins(AccountView)
|
||||||
|
|
||||||
|
expect(wrapper.find('.avatar').text()).toBe('JD')
|
||||||
|
expect(wrapper.find('.name').text()).toBe('Dr Jean Dupont')
|
||||||
|
|
||||||
|
await wrapper.find('#current').setValue('ancien-mot-de-passe')
|
||||||
|
await wrapper.find('#next').setValue('un-nouveau-mot-de-passe')
|
||||||
|
await wrapper.find('#confirm').setValue('un-nouveau-mot-de-passe')
|
||||||
|
await wrapper.find('form').trigger('submit')
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(JSON.parse(fetch.mock.calls[0]![1]!.body as string)).toEqual({
|
||||||
|
current_password: 'ancien-mot-de-passe',
|
||||||
|
new_password: 'un-nouveau-mot-de-passe',
|
||||||
|
})
|
||||||
|
expect(wrapper.text()).toContain('Mot de passe modifié')
|
||||||
|
expect((wrapper.find('#current').element as HTMLInputElement).value).toBe('')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('affiche l’erreur sur le mot de passe actuel', async () => {
|
||||||
|
await signIn()
|
||||||
|
mockFetch(jsonResponse(400, { current_password: ['Mot de passe actuel incorrect.'] }))
|
||||||
|
const wrapper = mountWithPlugins(AccountView)
|
||||||
|
await wrapper.find('#current').setValue('faux')
|
||||||
|
await wrapper.find('#next').setValue('un-nouveau-mot-de-passe')
|
||||||
|
await wrapper.find('#confirm').setValue('un-nouveau-mot-de-passe')
|
||||||
|
await wrapper.find('form').trigger('submit')
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(wrapper.find('#current').classes()).toContain('is-invalid')
|
||||||
|
expect(wrapper.text()).toContain('Mot de passe actuel incorrect.')
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
import { flushPromises } from '@vue/test-utils'
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
|
||||||
|
import { resetAuth } from '@/composables/useAuth'
|
||||||
|
import ForgotPasswordView from '@/views/ForgotPasswordView.vue'
|
||||||
|
import LoginView from '@/views/LoginView.vue'
|
||||||
|
import ResetPasswordView from '@/views/ResetPasswordView.vue'
|
||||||
|
|
||||||
|
import { jsonResponse, makeRouter, mockFetch, mountWithPlugins } from './helpers'
|
||||||
|
|
||||||
|
beforeEach(resetAuth)
|
||||||
|
afterEach(() => {
|
||||||
|
vi.unstubAllGlobals()
|
||||||
|
history.replaceState(null, '')
|
||||||
|
})
|
||||||
|
|
||||||
|
const NEW_PASSWORD = 'un-tout-nouveau-mot-de-passe'
|
||||||
|
|
||||||
|
describe('ForgotPasswordView', () => {
|
||||||
|
it('envoie la demande puis affiche « Vérifiez votre boîte mail »', async () => {
|
||||||
|
const fetch = mockFetch(jsonResponse(202), jsonResponse(202))
|
||||||
|
const wrapper = mountWithPlugins(ForgotPasswordView)
|
||||||
|
|
||||||
|
await wrapper.find('#email').setValue('medecin@exemple.be')
|
||||||
|
await wrapper.find('form').trigger('submit')
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(fetch.mock.calls[0]![0]).toBe('/api/v1/auth/password-reset/')
|
||||||
|
expect(JSON.parse(fetch.mock.calls[0]![1]!.body as string)).toEqual({
|
||||||
|
email: 'medecin@exemple.be',
|
||||||
|
})
|
||||||
|
expect(wrapper.find('h1').text()).toBe('Vérifiez votre boîte mail')
|
||||||
|
expect(wrapper.text()).toContain('Si un compte existe pour medecin@exemple.be')
|
||||||
|
|
||||||
|
await wrapper.find('button').trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
expect(fetch).toHaveBeenCalledTimes(2)
|
||||||
|
expect(wrapper.find('button').attributes('disabled')).toBeDefined()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('signale la limitation de débit', async () => {
|
||||||
|
mockFetch(jsonResponse(429, { detail: 'Throttled' }))
|
||||||
|
const wrapper = mountWithPlugins(ForgotPasswordView)
|
||||||
|
await wrapper.find('#email').setValue('medecin@exemple.be')
|
||||||
|
await wrapper.find('form').trigger('submit')
|
||||||
|
await flushPromises()
|
||||||
|
expect(wrapper.find('[role="alert"]').text()).toContain('Trop de demandes')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('ResetPasswordView', () => {
|
||||||
|
async function mountWithToken(token: string | null, ...responses: Response[]) {
|
||||||
|
const fetch = mockFetch(...responses)
|
||||||
|
const router = makeRouter()
|
||||||
|
await router.push(token ? `/reinitialisation/${token}` : '/reinitialisation')
|
||||||
|
const push = vi.spyOn(router, 'push')
|
||||||
|
const wrapper = mountWithPlugins(ResetPasswordView, { router })
|
||||||
|
await flushPromises()
|
||||||
|
return { wrapper, router, fetch, push }
|
||||||
|
}
|
||||||
|
|
||||||
|
it('vérifie le lien, retire le jeton de l’URL et affiche le formulaire', async () => {
|
||||||
|
const { wrapper, router, fetch } = await mountWithToken('Mw.abc-123', jsonResponse(204))
|
||||||
|
expect(JSON.parse(fetch.mock.calls[0]![1]!.body as string)).toEqual({ token: 'Mw.abc-123' })
|
||||||
|
expect(router.currentRoute.value.fullPath).toBe('/reinitialisation')
|
||||||
|
expect(wrapper.find('h1').text()).toBe('Nouveau mot de passe')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('lien invalide ou expiré : propose un nouveau lien', async () => {
|
||||||
|
const { wrapper } = await mountWithToken(
|
||||||
|
'vieux',
|
||||||
|
jsonResponse(400, { code: 'invalid_token', detail: '' }),
|
||||||
|
)
|
||||||
|
expect(wrapper.find('h1').text()).toBe('Lien invalide ou expiré')
|
||||||
|
expect(wrapper.find('a.btn').attributes('href')).toBe('/mot-de-passe-oublie')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('sans jeton : lien invalide, sans appel à l’API', async () => {
|
||||||
|
const { wrapper, fetch } = await mountWithToken(null)
|
||||||
|
expect(wrapper.find('h1').text()).toBe('Lien invalide ou expiré')
|
||||||
|
expect(fetch).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('enregistre le mot de passe puis renvoie à la connexion avec un message', async () => {
|
||||||
|
const { wrapper, fetch, push } = await mountWithToken(
|
||||||
|
'Mw.abc-123',
|
||||||
|
jsonResponse(204),
|
||||||
|
jsonResponse(204),
|
||||||
|
)
|
||||||
|
push.mockResolvedValue(undefined)
|
||||||
|
await wrapper.find('#password').setValue(NEW_PASSWORD)
|
||||||
|
await wrapper.find('#confirm').setValue(NEW_PASSWORD)
|
||||||
|
await wrapper.find('form').trigger('submit')
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(fetch.mock.calls[1]![0]).toBe('/api/v1/auth/password-reset/confirm/')
|
||||||
|
expect(JSON.parse(fetch.mock.calls[1]![1]!.body as string)).toEqual({
|
||||||
|
token: 'Mw.abc-123',
|
||||||
|
new_password: NEW_PASSWORD,
|
||||||
|
})
|
||||||
|
expect(push).toHaveBeenCalledWith({ name: 'login', state: { notice: 'password-reset' } })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('bloque l’envoi si les mots de passe diffèrent ou sont trop courts', async () => {
|
||||||
|
const { wrapper } = await mountWithToken('Mw.abc-123', jsonResponse(204))
|
||||||
|
const button = () => wrapper.find('button[type="submit"]')
|
||||||
|
await wrapper.find('#password').setValue(NEW_PASSWORD)
|
||||||
|
await wrapper.find('#confirm').setValue('autre-mot-de-passe-long')
|
||||||
|
expect(button().attributes('disabled')).toBeDefined()
|
||||||
|
expect(wrapper.find('#confirm').classes()).toContain('is-invalid')
|
||||||
|
await wrapper.find('#password').setValue('court')
|
||||||
|
await wrapper.find('#confirm').setValue('court')
|
||||||
|
expect(button().attributes('disabled')).toBeDefined()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('affiche le refus du mot de passe par le serveur', async () => {
|
||||||
|
const { wrapper } = await mountWithToken(
|
||||||
|
'Mw.abc-123',
|
||||||
|
jsonResponse(204),
|
||||||
|
jsonResponse(400, { new_password: ['Ce mot de passe est trop courant.'] }),
|
||||||
|
)
|
||||||
|
await wrapper.find('#password').setValue(NEW_PASSWORD)
|
||||||
|
await wrapper.find('#confirm').setValue(NEW_PASSWORD)
|
||||||
|
await wrapper.find('form').trigger('submit')
|
||||||
|
await flushPromises()
|
||||||
|
expect(wrapper.find('#password').classes()).toContain('is-invalid')
|
||||||
|
expect(wrapper.text()).toContain('Ce mot de passe est trop courant.')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('lien devenu invalide entre-temps : écran « Lien invalide »', async () => {
|
||||||
|
const { wrapper } = await mountWithToken(
|
||||||
|
'Mw.abc-123',
|
||||||
|
jsonResponse(204),
|
||||||
|
jsonResponse(400, { code: 'invalid_token', detail: '' }),
|
||||||
|
)
|
||||||
|
await wrapper.find('#password').setValue(NEW_PASSWORD)
|
||||||
|
await wrapper.find('#confirm').setValue(NEW_PASSWORD)
|
||||||
|
await wrapper.find('form').trigger('submit')
|
||||||
|
await flushPromises()
|
||||||
|
expect(wrapper.find('h1').text()).toBe('Lien invalide ou expiré')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('LoginView', () => {
|
||||||
|
it('propose le lien « Mot de passe oublié ? »', () => {
|
||||||
|
const wrapper = mountWithPlugins(LoginView)
|
||||||
|
const link = wrapper.findAll('a').find((a) => a.text() === 'Mot de passe oublié ?')
|
||||||
|
expect(link?.attributes('href')).toBe('/mot-de-passe-oublie')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('affiche la confirmation après réinitialisation', () => {
|
||||||
|
history.replaceState({ notice: 'password-reset' }, '')
|
||||||
|
const wrapper = mountWithPlugins(LoginView)
|
||||||
|
expect(wrapper.find('[role="status"]').text()).toContain('Votre mot de passe a été modifié')
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
import { flushPromises } from '@vue/test-utils'
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
|
||||||
|
import { resetAuth } from '@/composables/useAuth'
|
||||||
|
import RegisterStatusView from '@/views/RegisterStatusView.vue'
|
||||||
|
import RegisterView from '@/views/RegisterView.vue'
|
||||||
|
|
||||||
|
import { jsonResponse, makeRouter, mockFetch, mountWithPlugins } from './helpers'
|
||||||
|
|
||||||
|
beforeEach(resetAuth)
|
||||||
|
afterEach(() => {
|
||||||
|
vi.unstubAllGlobals()
|
||||||
|
history.replaceState(null, '')
|
||||||
|
})
|
||||||
|
|
||||||
|
const PASSWORD = 'un-mot-de-passe-solide'
|
||||||
|
|
||||||
|
async function fill(wrapper: ReturnType<typeof mountWithPlugins>, overrides = {}) {
|
||||||
|
const values = {
|
||||||
|
'#first_name': 'Marie',
|
||||||
|
'#last_name': 'Curie',
|
||||||
|
'#email': 'marie@exemple.be',
|
||||||
|
'#inami': '',
|
||||||
|
'#password': PASSWORD,
|
||||||
|
'#confirm': PASSWORD,
|
||||||
|
...overrides,
|
||||||
|
}
|
||||||
|
for (const [selector, value] of Object.entries(values)) {
|
||||||
|
await wrapper.find(selector).setValue(value)
|
||||||
|
}
|
||||||
|
await wrapper.find('#terms').setValue(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('RegisterView', () => {
|
||||||
|
it('envoie la demande puis affiche « Vérifiez votre boîte mail » sans e-mail dans l’URL', async () => {
|
||||||
|
const fetch = mockFetch(jsonResponse(201))
|
||||||
|
const router = makeRouter()
|
||||||
|
const push = vi.spyOn(router, 'push').mockResolvedValue(undefined)
|
||||||
|
const wrapper = mountWithPlugins(RegisterView, { router })
|
||||||
|
|
||||||
|
await fill(wrapper)
|
||||||
|
await wrapper.find('form').trigger('submit')
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(JSON.parse(fetch.mock.calls[0]![1]!.body as string)).toEqual({
|
||||||
|
first_name: 'Marie',
|
||||||
|
last_name: 'Curie',
|
||||||
|
email: 'marie@exemple.be',
|
||||||
|
inami_number: '',
|
||||||
|
password: PASSWORD,
|
||||||
|
accept_terms: true,
|
||||||
|
})
|
||||||
|
expect(push).toHaveBeenCalledWith({
|
||||||
|
name: 'register-status',
|
||||||
|
state: { email: 'marie@exemple.be' },
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('bloque l’envoi si les mots de passe diffèrent, sont trop courts ou sans conditions', async () => {
|
||||||
|
const wrapper = mountWithPlugins(RegisterView)
|
||||||
|
const button = () => wrapper.find('button[type="submit"]')
|
||||||
|
|
||||||
|
await fill(wrapper, { '#confirm': 'autre-mot-de-passe' })
|
||||||
|
expect(button().attributes('disabled')).toBeDefined()
|
||||||
|
expect(wrapper.find('#confirm').classes()).toContain('is-invalid')
|
||||||
|
|
||||||
|
await fill(wrapper, { '#password': 'court', '#confirm': 'court' })
|
||||||
|
expect(button().attributes('disabled')).toBeDefined()
|
||||||
|
|
||||||
|
await fill(wrapper)
|
||||||
|
expect(button().attributes('disabled')).toBeUndefined()
|
||||||
|
await wrapper.find('#terms').setValue(false)
|
||||||
|
expect(button().attributes('disabled')).toBeDefined()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('affiche les erreurs de validation du serveur sous chaque champ', async () => {
|
||||||
|
mockFetch(
|
||||||
|
jsonResponse(400, {
|
||||||
|
password: ['Ce mot de passe est trop courant.'],
|
||||||
|
email: ['Saisissez une adresse e-mail valide.'],
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
const wrapper = mountWithPlugins(RegisterView)
|
||||||
|
await fill(wrapper)
|
||||||
|
await wrapper.find('form').trigger('submit')
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(wrapper.find('[role="alert"]').text()).toBe('Corrigez les champs signalés.')
|
||||||
|
expect(wrapper.find('#password').classes()).toContain('is-invalid')
|
||||||
|
expect(wrapper.text()).toContain('Ce mot de passe est trop courant.')
|
||||||
|
expect(wrapper.text()).toContain('Saisissez une adresse e-mail valide.')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('RegisterStatusView', () => {
|
||||||
|
async function mountAt(path: string, state?: Record<string, unknown>) {
|
||||||
|
const router = makeRouter()
|
||||||
|
await router.push(router.resolve(path)).catch(() => {})
|
||||||
|
if (state) history.replaceState(state, '')
|
||||||
|
const wrapper = mountWithPlugins(RegisterStatusView, { router })
|
||||||
|
await flushPromises()
|
||||||
|
return { wrapper, router }
|
||||||
|
}
|
||||||
|
|
||||||
|
it('après inscription : « Vérifiez votre boîte mail » et renvoi par e-mail', async () => {
|
||||||
|
const fetch = mockFetch(jsonResponse(202))
|
||||||
|
const { wrapper } = await mountAt('/inscription/statut', { email: 'marie@exemple.be' })
|
||||||
|
|
||||||
|
expect(wrapper.find('h1').text()).toBe('Vérifiez votre boîte mail')
|
||||||
|
expect(wrapper.text()).toContain('marie@exemple.be')
|
||||||
|
|
||||||
|
await wrapper.find('button').trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
expect(JSON.parse(fetch.mock.calls[0]![1]!.body as string)).toEqual({
|
||||||
|
email: 'marie@exemple.be',
|
||||||
|
})
|
||||||
|
expect(wrapper.find('button').attributes('disabled')).toBeDefined()
|
||||||
|
expect(wrapper.text()).toContain('un nouvel e-mail vient d’être envoyé'.replace('’', "'"))
|
||||||
|
})
|
||||||
|
|
||||||
|
it('lien valide : adresse confirmée et jeton retiré de l’URL', async () => {
|
||||||
|
const fetch = mockFetch(jsonResponse(200, { status: 'approval_pending' }))
|
||||||
|
const { wrapper, router } = await mountAt('/inscription/statut?jeton=abc')
|
||||||
|
|
||||||
|
expect(JSON.parse(fetch.mock.calls[0]![1]!.body as string)).toEqual({ token: 'abc' })
|
||||||
|
expect(wrapper.find('h1').text()).toBe('Adresse confirmée')
|
||||||
|
expect(router.currentRoute.value.fullPath).toBe('/inscription/statut')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('lien expiré : renvoi à partir du jeton', async () => {
|
||||||
|
const fetch = mockFetch(
|
||||||
|
jsonResponse(400, { code: 'expired_token', detail: 'Ce lien a expiré.' }),
|
||||||
|
jsonResponse(202),
|
||||||
|
)
|
||||||
|
const { wrapper } = await mountAt('/inscription/statut?jeton=vieux')
|
||||||
|
|
||||||
|
expect(wrapper.find('h1').text()).toBe('Lien expiré')
|
||||||
|
await wrapper.find('button').trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
expect(JSON.parse(fetch.mock.calls[1]![1]!.body as string)).toEqual({ token: 'vieux' })
|
||||||
|
})
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['invalid_token', 'Lien invalide'],
|
||||||
|
['used_token', 'Adresse confirmée'],
|
||||||
|
])('%s → « %s »', async (code, title) => {
|
||||||
|
mockFetch(jsonResponse(400, { code, detail: '' }))
|
||||||
|
const { wrapper } = await mountAt('/inscription/statut?jeton=x')
|
||||||
|
expect(wrapper.find('h1').text()).toBe(title)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
|
||||||
|
import { resetAuth } from '@/composables/useAuth'
|
||||||
|
import { createAppRouter } from '@/router'
|
||||||
|
|
||||||
|
import { jsonResponse, mockFetch, USER } from './helpers'
|
||||||
|
|
||||||
|
beforeEach(resetAuth)
|
||||||
|
afterEach(() => vi.unstubAllGlobals())
|
||||||
|
|
||||||
|
async function navigate(path: string) {
|
||||||
|
const router = createAppRouter()
|
||||||
|
await router.push(path)
|
||||||
|
return router.currentRoute.value
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('garde de navigation', () => {
|
||||||
|
it("redirige un visiteur vers /login depuis l'évaluation", async () => {
|
||||||
|
mockFetch(jsonResponse(403, {}))
|
||||||
|
expect((await navigate('/')).name).toBe('login')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('laisse un utilisateur connecté accéder à l’évaluation', async () => {
|
||||||
|
mockFetch(jsonResponse(200, USER))
|
||||||
|
expect((await navigate('/')).name).toBe('assessment')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('renvoie un utilisateur connecté de /login vers l’évaluation', async () => {
|
||||||
|
mockFetch(jsonResponse(200, USER))
|
||||||
|
expect((await navigate('/login')).name).toBe('assessment')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('affiche la page 404 pour une route inconnue', async () => {
|
||||||
|
mockFetch(jsonResponse(403, {}))
|
||||||
|
const route = await navigate('/nimporte/quoi')
|
||||||
|
expect(route.name).toBe('not-found')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('protège /compte et laisse /inscription aux visiteurs', async () => {
|
||||||
|
mockFetch(jsonResponse(403, {}))
|
||||||
|
expect((await navigate('/compte')).name).toBe('login')
|
||||||
|
resetAuth()
|
||||||
|
mockFetch(jsonResponse(403, {}))
|
||||||
|
expect((await navigate('/inscription')).name).toBe('register')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('renvoie un utilisateur connecté de /inscription vers l’évaluation', async () => {
|
||||||
|
mockFetch(jsonResponse(200, USER))
|
||||||
|
expect((await navigate('/inscription')).name).toBe('assessment')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('laisse /inscription/statut ouverte à tous (lien reçu par e-mail)', async () => {
|
||||||
|
mockFetch(jsonResponse(200, USER))
|
||||||
|
expect((await navigate('/inscription/statut')).name).toBe('register-status')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('mot de passe oublié réservé aux visiteurs, lien de réinitialisation ouvert à tous', async () => {
|
||||||
|
mockFetch(jsonResponse(200, USER))
|
||||||
|
expect((await navigate('/mot-de-passe-oublie')).name).toBe('assessment')
|
||||||
|
resetAuth()
|
||||||
|
mockFetch(jsonResponse(200, USER))
|
||||||
|
expect((await navigate('/reinitialisation/abc')).name).toBe('reset-password')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('laisse la page 403 publique', async () => {
|
||||||
|
mockFetch(jsonResponse(403, {}))
|
||||||
|
expect((await navigate('/403')).name).toBe('forbidden')
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
|
||||||
|
import { ApiError } from '@/api/client'
|
||||||
|
import { resetAuth, useAuth } from '@/composables/useAuth'
|
||||||
|
|
||||||
|
import { jsonResponse, mockFetch, USER } from './helpers'
|
||||||
|
|
||||||
|
beforeEach(resetAuth)
|
||||||
|
afterEach(() => vi.unstubAllGlobals())
|
||||||
|
|
||||||
|
describe('useAuth', () => {
|
||||||
|
it("charge l'utilisateur connecté", async () => {
|
||||||
|
mockFetch(jsonResponse(200, USER))
|
||||||
|
const { load, user, isAuthenticated } = useAuth()
|
||||||
|
await load()
|
||||||
|
expect(user.value).toEqual(USER)
|
||||||
|
expect(isAuthenticated.value).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('considère un 403 comme « non connecté »', async () => {
|
||||||
|
mockFetch(jsonResponse(403, { detail: 'Non authentifié.' }))
|
||||||
|
const { load, isAuthenticated } = useAuth()
|
||||||
|
await expect(load()).resolves.toBeNull()
|
||||||
|
expect(isAuthenticated.value).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('propage les autres erreurs', async () => {
|
||||||
|
mockFetch(jsonResponse(500, {}))
|
||||||
|
await expect(useAuth().load()).rejects.toBeInstanceOf(ApiError)
|
||||||
|
})
|
||||||
|
|
||||||
|
it("n'interroge l'API qu'une fois", async () => {
|
||||||
|
const fetch = mockFetch(jsonResponse(200, USER))
|
||||||
|
const { load } = useAuth()
|
||||||
|
await load()
|
||||||
|
await load()
|
||||||
|
expect(fetch).toHaveBeenCalledTimes(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it("connecte puis recharge l'utilisateur (nouveau jeton CSRF)", async () => {
|
||||||
|
const fetch = mockFetch(
|
||||||
|
jsonResponse(200, { mfa_required: false, user: USER }),
|
||||||
|
jsonResponse(200, USER),
|
||||||
|
)
|
||||||
|
const { login, user } = useAuth()
|
||||||
|
await login('medecin@exemple.be', 'secret')
|
||||||
|
expect(user.value).toEqual(USER)
|
||||||
|
expect(fetch.mock.calls.map(([url]) => url)).toEqual([
|
||||||
|
'/api/v1/auth/login/',
|
||||||
|
'/api/v1/auth/me/',
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('déconnecte même si la requête échoue', async () => {
|
||||||
|
mockFetch(jsonResponse(200, USER), jsonResponse(500, {}), jsonResponse(403, {}))
|
||||||
|
const { load, logout, user } = useAuth()
|
||||||
|
await load()
|
||||||
|
await logout().catch(() => {})
|
||||||
|
expect(user.value).toBeNull()
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
import { flushPromises } from '@vue/test-utils'
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
|
||||||
|
import { resetAuth, useAuth } from '@/composables/useAuth'
|
||||||
|
import AssessmentView from '@/views/AssessmentView.vue'
|
||||||
|
import ErrorView from '@/views/ErrorView.vue'
|
||||||
|
import LoginView from '@/views/LoginView.vue'
|
||||||
|
|
||||||
|
import { ASSESSMENT, jsonResponse, makeRouter, mockFetch, mountWithPlugins, USER } from './helpers'
|
||||||
|
|
||||||
|
const stubs = { ResultMap: { template: '<div class="map-stub" />', props: ['location'] } }
|
||||||
|
|
||||||
|
beforeEach(resetAuth)
|
||||||
|
afterEach(() => vi.unstubAllGlobals())
|
||||||
|
|
||||||
|
async function analyse(
|
||||||
|
wrapper: ReturnType<typeof mountWithPlugins>,
|
||||||
|
address = 'Place de l’Université 1',
|
||||||
|
) {
|
||||||
|
await wrapper.find('#address').setValue(address)
|
||||||
|
await wrapper.find('form').trigger('submit')
|
||||||
|
await flushPromises()
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('AssessmentView', () => {
|
||||||
|
it('affiche l’adresse reconnue et une carte par facteur', async () => {
|
||||||
|
mockFetch(jsonResponse(200, ASSESSMENT))
|
||||||
|
const wrapper = mountWithPlugins(AssessmentView, { global: { stubs } })
|
||||||
|
|
||||||
|
await analyse(wrapper)
|
||||||
|
|
||||||
|
expect(wrapper.find('[role="status"]').text()).toBe(
|
||||||
|
'Adresse reconnue : Place de l’Université 1 — Région wallonne',
|
||||||
|
)
|
||||||
|
expect(wrapper.findAll('.factor-card')).toHaveLength(2)
|
||||||
|
})
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
[404, { code: 'address_not_found' }, 'Adresse introuvable'],
|
||||||
|
[422, { code: 'out_of_coverage' }, 'hors couverture'],
|
||||||
|
[503, { code: 'geocoding_unavailable' }, 'géocodage est indisponible'],
|
||||||
|
[429, { detail: 'Throttled' }, "Trop d'analyses"],
|
||||||
|
[500, {}, "L'analyse a échoué"],
|
||||||
|
])('erreur %i → message adapté', async (status, body, message) => {
|
||||||
|
mockFetch(jsonResponse(status, body))
|
||||||
|
const wrapper = mountWithPlugins(AssessmentView, { global: { stubs } })
|
||||||
|
|
||||||
|
await analyse(wrapper)
|
||||||
|
|
||||||
|
expect(wrapper.find('[role="alert"]').text()).toContain(message)
|
||||||
|
expect(wrapper.findAll('.factor-card')).toHaveLength(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('« Réessayer » relance l’analyse de la même adresse', async () => {
|
||||||
|
const fetch = mockFetch(jsonResponse(200, ASSESSMENT), jsonResponse(200, ASSESSMENT))
|
||||||
|
const wrapper = mountWithPlugins(AssessmentView, { global: { stubs } })
|
||||||
|
await analyse(wrapper, 'Rue de la Loi 16, 1000 Bruxelles')
|
||||||
|
|
||||||
|
await wrapper.find('.factor-card.unavailable button').trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(fetch).toHaveBeenCalledTimes(2)
|
||||||
|
expect(JSON.parse(fetch.mock.calls[1]![1]!.body as string)).toEqual({
|
||||||
|
address: 'Rue de la Loi 16, 1000 Bruxelles',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('session expirée : retour à la connexion', async () => {
|
||||||
|
mockFetch(jsonResponse(403, {}), jsonResponse(204), jsonResponse(403, {}))
|
||||||
|
const router = makeRouter()
|
||||||
|
const push = vi.spyOn(router, 'push')
|
||||||
|
const wrapper = mountWithPlugins(AssessmentView, { router, global: { stubs } })
|
||||||
|
|
||||||
|
await analyse(wrapper)
|
||||||
|
|
||||||
|
expect(push).toHaveBeenCalledWith({ name: 'login' })
|
||||||
|
})
|
||||||
|
|
||||||
|
it("ne place pas l'adresse dans l'URL ni dans le stockage du navigateur", async () => {
|
||||||
|
mockFetch(jsonResponse(200, ASSESSMENT))
|
||||||
|
const router = makeRouter()
|
||||||
|
const wrapper = mountWithPlugins(AssessmentView, { router, global: { stubs } })
|
||||||
|
|
||||||
|
await analyse(wrapper, 'Rue Secrète 1, 1348 Louvain-la-Neuve')
|
||||||
|
|
||||||
|
expect(router.currentRoute.value.fullPath).not.toContain('Secr')
|
||||||
|
expect(JSON.stringify({ ...localStorage, ...sessionStorage })).not.toContain('Secr')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('LoginView', () => {
|
||||||
|
it("affiche le message d'erreur du serveur", async () => {
|
||||||
|
mockFetch(jsonResponse(400, { detail: 'E-mail ou mot de passe incorrect.' }))
|
||||||
|
const wrapper = mountWithPlugins(LoginView)
|
||||||
|
|
||||||
|
await wrapper.find('#email').setValue('medecin@exemple.be')
|
||||||
|
await wrapper.find('#password').setValue('mauvais')
|
||||||
|
await wrapper.find('form').trigger('submit')
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(wrapper.find('[role="alert"]').text()).toBe('E-mail ou mot de passe incorrect.')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('redirige vers l’évaluation après connexion', async () => {
|
||||||
|
mockFetch(jsonResponse(200, { mfa_required: false, user: USER }), jsonResponse(200, USER))
|
||||||
|
const router = makeRouter()
|
||||||
|
const push = vi.spyOn(router, 'push').mockResolvedValue(undefined)
|
||||||
|
const wrapper = mountWithPlugins(LoginView, { router })
|
||||||
|
|
||||||
|
await wrapper.find('#email').setValue('medecin@exemple.be')
|
||||||
|
await wrapper.find('#password').setValue('un-mot-de-passe-solide')
|
||||||
|
await wrapper.find('form').trigger('submit')
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(useAuth().user.value).toEqual(USER)
|
||||||
|
expect(push).toHaveBeenCalledWith({ name: 'assessment' })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('suit le paramètre next interne et ignore une URL externe', async () => {
|
||||||
|
for (const [next, expected] of [
|
||||||
|
['/403', '/403'],
|
||||||
|
['https://evil.example', { name: 'assessment' }],
|
||||||
|
] as const) {
|
||||||
|
resetAuth()
|
||||||
|
mockFetch(jsonResponse(200, { mfa_required: false, user: USER }), jsonResponse(200, USER))
|
||||||
|
const router = makeRouter()
|
||||||
|
await router.push({ name: 'login', query: { next } }).catch(() => {})
|
||||||
|
const push = vi.spyOn(router, 'push').mockResolvedValue(undefined)
|
||||||
|
const wrapper = mountWithPlugins(LoginView, { router })
|
||||||
|
|
||||||
|
await wrapper.find('#email').setValue('medecin@exemple.be')
|
||||||
|
await wrapper.find('#password').setValue('x')
|
||||||
|
await wrapper.find('form').trigger('submit')
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(push).toHaveBeenCalledWith(expected)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('ErrorView', () => {
|
||||||
|
it.each([
|
||||||
|
[404, 'Page introuvable'],
|
||||||
|
[403, 'Accès refusé'],
|
||||||
|
] as const)('%i', (code, title) => {
|
||||||
|
const wrapper = mountWithPlugins(ErrorView, { props: { code } })
|
||||||
|
expect(wrapper.find('.error-code').text()).toBe(String(code))
|
||||||
|
expect(wrapper.find('h1').text()).toBe(title)
|
||||||
|
expect(wrapper.find('a').attributes('href')).toBe('/')
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
/**
|
||||||
|
* Client HTTP de l'API Django (sessions + CSRF).
|
||||||
|
*
|
||||||
|
* Le cookie CSRF est déposé par GET /auth/me/ ; il est renvoyé dans l'en-tête X-CSRFToken
|
||||||
|
* pour toutes les requêtes qui modifient l'état.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import type { Assessment, LoginResult, RegisterPayload, TotpSetup, User } from './types'
|
||||||
|
|
||||||
|
const BASE = '/api/v1'
|
||||||
|
|
||||||
|
export class ApiError extends Error {
|
||||||
|
readonly status: number
|
||||||
|
readonly body: Record<string, unknown>
|
||||||
|
|
||||||
|
constructor(status: number, body: Record<string, unknown>) {
|
||||||
|
super(typeof body.detail === 'string' ? body.detail : `HTTP ${status}`)
|
||||||
|
this.status = status
|
||||||
|
this.body = body
|
||||||
|
}
|
||||||
|
|
||||||
|
get code(): string | undefined {
|
||||||
|
return typeof this.body.code === 'string' ? this.body.code : undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Messages de validation par champ (réponse 400 de DRF). */
|
||||||
|
fieldErrors(): Record<string, string> {
|
||||||
|
const errors: Record<string, string> = {}
|
||||||
|
for (const [field, value] of Object.entries(this.body)) {
|
||||||
|
if (Array.isArray(value) && typeof value[0] === 'string') errors[field] = value.join(' ')
|
||||||
|
}
|
||||||
|
return errors
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function csrfToken(): string {
|
||||||
|
const match = document.cookie.match(/(?:^|;\s*)csrftoken=([^;]+)/)
|
||||||
|
return match?.[1] ? decodeURIComponent(match[1]) : ''
|
||||||
|
}
|
||||||
|
|
||||||
|
async function request<T>(method: string, path: string, body?: unknown): Promise<T> {
|
||||||
|
const headers: Record<string, string> = { Accept: 'application/json' }
|
||||||
|
if (method !== 'GET') {
|
||||||
|
headers['X-CSRFToken'] = csrfToken()
|
||||||
|
}
|
||||||
|
if (body !== undefined) {
|
||||||
|
headers['Content-Type'] = 'application/json'
|
||||||
|
}
|
||||||
|
const response = await fetch(`${BASE}${path}`, {
|
||||||
|
method,
|
||||||
|
headers,
|
||||||
|
credentials: 'same-origin',
|
||||||
|
body: body === undefined ? undefined : JSON.stringify(body),
|
||||||
|
})
|
||||||
|
if (response.status === 204) {
|
||||||
|
return undefined as T
|
||||||
|
}
|
||||||
|
const data = await response.json().catch(() => ({}))
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new ApiError(response.status, data)
|
||||||
|
}
|
||||||
|
return data as T
|
||||||
|
}
|
||||||
|
|
||||||
|
export const api = {
|
||||||
|
me: () => request<User>('GET', '/auth/me/'),
|
||||||
|
login: (email: string, password: string) =>
|
||||||
|
request<LoginResult>('POST', '/auth/login/', { email, password }),
|
||||||
|
verifyMfa: (code: string) => request<LoginResult>('POST', '/auth/2fa/verify/', { code }),
|
||||||
|
logout: () => request<void>('POST', '/auth/logout/'),
|
||||||
|
register: (payload: RegisterPayload) => request<void>('POST', '/auth/register/', payload),
|
||||||
|
verifyEmail: (token: string) =>
|
||||||
|
request<{ status: string }>('POST', '/auth/verify-email/', { token }),
|
||||||
|
resendVerification: (target: { email?: string; token?: string }) =>
|
||||||
|
request<void>('POST', '/auth/verify-email/resend/', target),
|
||||||
|
changePassword: (current_password: string, new_password: string) =>
|
||||||
|
request<void>('POST', '/auth/password/change/', { current_password, new_password }),
|
||||||
|
requestPasswordReset: (email: string) =>
|
||||||
|
request<void>('POST', '/auth/password-reset/', { email }),
|
||||||
|
validateResetToken: (token: string) =>
|
||||||
|
request<void>('POST', '/auth/password-reset/validate/', { token }),
|
||||||
|
resetPassword: (token: string, new_password: string) =>
|
||||||
|
request<void>('POST', '/auth/password-reset/confirm/', { token, new_password }),
|
||||||
|
setupTotp: () => request<TotpSetup>('POST', '/auth/2fa/setup/'),
|
||||||
|
enableTotp: (code: string) =>
|
||||||
|
request<{ recovery_codes: string[] }>('POST', '/auth/2fa/enable/', { code }),
|
||||||
|
disableTotp: (password: string, code: string) =>
|
||||||
|
request<void>('POST', '/auth/2fa/disable/', { password, code }),
|
||||||
|
regenerateRecoveryCodes: (code: string) =>
|
||||||
|
request<{ recovery_codes: string[] }>('POST', '/auth/2fa/recovery-codes/', { code }),
|
||||||
|
assess: (address: string) => request<Assessment>('POST', '/assessments/', { address }),
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
export type FactorStatus = 'ok' | 'no_data' | 'unavailable'
|
||||||
|
export type LevelColor = 'green' | 'yellow' | 'orange' | 'red'
|
||||||
|
export type Region = 'WAL' | 'BXL'
|
||||||
|
|
||||||
|
export interface User {
|
||||||
|
email: string
|
||||||
|
first_name: string
|
||||||
|
last_name: string
|
||||||
|
roles: string[]
|
||||||
|
is_staff: boolean
|
||||||
|
mfa_enabled: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LoginResult {
|
||||||
|
mfa_required: boolean
|
||||||
|
user: User | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RegisterPayload {
|
||||||
|
first_name: string
|
||||||
|
last_name: string
|
||||||
|
email: string
|
||||||
|
inami_number: string
|
||||||
|
password: string
|
||||||
|
accept_terms: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TotpSetup {
|
||||||
|
secret: string
|
||||||
|
otpauth_url: string
|
||||||
|
qr_code: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Detail {
|
||||||
|
label: string
|
||||||
|
value: string
|
||||||
|
status?: 'ok' | 'exceeded'
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ScaleItem {
|
||||||
|
level: number
|
||||||
|
color: LevelColor
|
||||||
|
label: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Legend {
|
||||||
|
source: string
|
||||||
|
text: string
|
||||||
|
scale: ScaleItem[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Reference {
|
||||||
|
n: number
|
||||||
|
title: string
|
||||||
|
url: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FactorResult {
|
||||||
|
code: string
|
||||||
|
label: string
|
||||||
|
status: FactorStatus
|
||||||
|
level: number | null
|
||||||
|
color: LevelColor | null
|
||||||
|
summary: string
|
||||||
|
details: Detail[]
|
||||||
|
tabs: {
|
||||||
|
health_effects: string
|
||||||
|
actions: string
|
||||||
|
legend: Legend
|
||||||
|
}
|
||||||
|
references: Reference[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Assessment {
|
||||||
|
location: { lat: number; lon: number; region: Region }
|
||||||
|
factors: FactorResult[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export type AssessmentErrorCode = 'address_not_found' | 'out_of_coverage' | 'geocoding_unavailable'
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 9.4 KiB |
@@ -0,0 +1,55 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ref } from 'vue'
|
||||||
|
|
||||||
|
defineProps<{ loading: boolean }>()
|
||||||
|
const emit = defineEmits<{ submit: [address: string] }>()
|
||||||
|
|
||||||
|
const address = ref('')
|
||||||
|
|
||||||
|
function onSubmit() {
|
||||||
|
const value = address.value.trim()
|
||||||
|
if (value) emit('submit', value)
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<form class="address-form prism-card" @submit.prevent="onSubmit">
|
||||||
|
<label for="address" class="form-label">{{ $t('assessment.addressLabel') }}</label>
|
||||||
|
<div class="d-flex flex-column flex-md-row gap-3">
|
||||||
|
<input
|
||||||
|
id="address"
|
||||||
|
v-model="address"
|
||||||
|
type="text"
|
||||||
|
class="form-control"
|
||||||
|
autocomplete="off"
|
||||||
|
maxlength="300"
|
||||||
|
required
|
||||||
|
:placeholder="$t('assessment.addressPlaceholder')"
|
||||||
|
/>
|
||||||
|
<button type="submit" class="btn btn-primary submit" :disabled="loading || !address.trim()">
|
||||||
|
<span
|
||||||
|
v-if="loading"
|
||||||
|
class="spinner-border spinner-border-sm me-2"
|
||||||
|
aria-hidden="true"
|
||||||
|
></span>
|
||||||
|
{{ loading ? $t('assessment.submitting') : $t('assessment.submit') }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.address-form {
|
||||||
|
padding: 22px 28px 22px;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 767.98px) {
|
||||||
|
.address-form {
|
||||||
|
padding: 18px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.submit {
|
||||||
|
min-width: 160px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
defineProps<{ variant: 'info' | 'error' }>()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div
|
||||||
|
:class="variant === 'info' ? 'prism-alert-info' : 'alert alert-danger mb-0'"
|
||||||
|
:role="variant === 'error' ? 'alert' : 'status'"
|
||||||
|
>
|
||||||
|
<i v-if="variant === 'error'" class="bi bi-exclamation-triangle me-2" aria-hidden="true"></i>
|
||||||
|
<slot />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
<template>
|
||||||
|
<footer class="app-footer">
|
||||||
|
<div class="container-xxl d-flex flex-column flex-md-row justify-content-between gap-2 py-4">
|
||||||
|
<span>{{ $t('app.disclaimer') }}</span>
|
||||||
|
<span class="footer-copyright">{{ $t('app.copyright') }}</span>
|
||||||
|
</div>
|
||||||
|
</footer>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.app-footer {
|
||||||
|
background: var(--prism-navy);
|
||||||
|
color: #fff;
|
||||||
|
font-size: 0.8125rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.container-xxl {
|
||||||
|
max-width: 1440px;
|
||||||
|
padding-inline: 48px;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 767.98px) {
|
||||||
|
.container-xxl {
|
||||||
|
padding-inline: 16px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.footer-copyright {
|
||||||
|
color: var(--prism-footer-link);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ref } from 'vue'
|
||||||
|
import { useRouter } from 'vue-router'
|
||||||
|
|
||||||
|
import logo from '@/assets/logo-ssmg.png'
|
||||||
|
import { useAuth } from '@/composables/useAuth'
|
||||||
|
|
||||||
|
const { user, logout } = useAuth()
|
||||||
|
const router = useRouter()
|
||||||
|
const menuOpen = ref(false)
|
||||||
|
|
||||||
|
async function onLogout() {
|
||||||
|
menuOpen.value = false
|
||||||
|
await logout()
|
||||||
|
await router.push({ name: 'login' })
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<header class="app-header">
|
||||||
|
<div class="container-xxl d-flex align-items-center justify-content-between gap-3">
|
||||||
|
<RouterLink to="/" class="brand text-decoration-none">
|
||||||
|
<img :src="logo" :alt="$t('app.logoAlt')" width="103" height="52" />
|
||||||
|
<span class="brand-text">
|
||||||
|
<span class="brand-name">{{ $t('app.name') }}</span>
|
||||||
|
<span class="brand-tagline d-none d-sm-block">{{ $t('app.tagline') }}</span>
|
||||||
|
</span>
|
||||||
|
</RouterLink>
|
||||||
|
|
||||||
|
<template v-if="user">
|
||||||
|
<nav class="d-none d-md-flex align-items-center gap-4">
|
||||||
|
<span class="text-muted-prism">{{ $t('nav.doctor', { name: user.last_name }) }}</span>
|
||||||
|
<RouterLink :to="{ name: 'account' }" class="nav-account">{{
|
||||||
|
$t('nav.account')
|
||||||
|
}}</RouterLink>
|
||||||
|
<button type="button" class="btn btn-link nav-logout p-0" @click="onLogout">
|
||||||
|
{{ $t('nav.logout') }}
|
||||||
|
</button>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<div class="d-md-none position-relative">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="btn menu-toggle"
|
||||||
|
:aria-label="$t('nav.menu')"
|
||||||
|
:aria-expanded="menuOpen"
|
||||||
|
@click="menuOpen = !menuOpen"
|
||||||
|
>
|
||||||
|
<i class="bi bi-list fs-4" aria-hidden="true"></i>
|
||||||
|
</button>
|
||||||
|
<div v-if="menuOpen" class="menu-overlay prism-card">
|
||||||
|
<p class="mb-2 text-muted-prism">{{ $t('nav.doctor', { name: user.last_name }) }}</p>
|
||||||
|
<RouterLink
|
||||||
|
:to="{ name: 'account' }"
|
||||||
|
class="nav-account d-block mb-2"
|
||||||
|
@click="menuOpen = false"
|
||||||
|
>
|
||||||
|
{{ $t('nav.account') }}
|
||||||
|
</RouterLink>
|
||||||
|
<button type="button" class="btn btn-link nav-logout p-0" @click="onLogout">
|
||||||
|
{{ $t('nav.logout') }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.app-header {
|
||||||
|
background: var(--prism-surface);
|
||||||
|
border-top: 4px solid var(--prism-orange);
|
||||||
|
padding: 0.6rem 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.container-xxl {
|
||||||
|
max-width: 1440px;
|
||||||
|
padding-inline: 48px;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 767.98px) {
|
||||||
|
.container-xxl {
|
||||||
|
padding-inline: 16px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.brand {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.brand img {
|
||||||
|
height: 52px;
|
||||||
|
width: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.brand-text {
|
||||||
|
border-left: 1px solid var(--prism-border);
|
||||||
|
padding-left: 20px;
|
||||||
|
line-height: 1.2;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 575.98px) {
|
||||||
|
.brand img {
|
||||||
|
height: 40px;
|
||||||
|
}
|
||||||
|
.brand-text {
|
||||||
|
border-left: 0;
|
||||||
|
padding-left: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.brand-name {
|
||||||
|
display: block;
|
||||||
|
color: var(--prism-navy);
|
||||||
|
font-size: 1.375rem;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
.brand-tagline {
|
||||||
|
color: var(--prism-muted);
|
||||||
|
font-size: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.text-muted-prism {
|
||||||
|
color: var(--prism-text);
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-account {
|
||||||
|
color: var(--prism-navy);
|
||||||
|
font-weight: 500;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-account:hover,
|
||||||
|
.nav-account.router-link-active {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-logout {
|
||||||
|
color: var(--prism-orange);
|
||||||
|
font-weight: 500;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.menu-toggle {
|
||||||
|
border: 1px solid var(--prism-border);
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 0.35rem 0.6rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.menu-overlay {
|
||||||
|
position: absolute;
|
||||||
|
right: 0;
|
||||||
|
top: calc(100% + 8px);
|
||||||
|
min-width: 220px;
|
||||||
|
padding: 1rem 1.25rem;
|
||||||
|
z-index: 1000;
|
||||||
|
box-shadow: 0 8px 24px rgb(9 41 51 / 12%);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { nextTick, ref } from 'vue'
|
||||||
|
|
||||||
|
/** Saisie d'un code à 6 chiffres en 6 cases (maquettes 13 et 14). Accepte le collage. */
|
||||||
|
const props = withDefaults(defineProps<{ length?: number; label: string; autofocus?: boolean }>(), {
|
||||||
|
length: 6,
|
||||||
|
autofocus: false,
|
||||||
|
})
|
||||||
|
const emit = defineEmits<{ complete: [code: string] }>()
|
||||||
|
const model = defineModel<string>({ default: '' })
|
||||||
|
|
||||||
|
const inputs = ref<HTMLInputElement[]>([])
|
||||||
|
const digits = ref<string[]>(Array.from({ length: props.length }, (_, i) => model.value[i] ?? ''))
|
||||||
|
|
||||||
|
function sync() {
|
||||||
|
// On teste la chaîne locale : `model.value` n'est mis à jour qu'au rendu du parent.
|
||||||
|
const code = digits.value.join('')
|
||||||
|
model.value = code
|
||||||
|
if (code.length === props.length) emit('complete', code)
|
||||||
|
}
|
||||||
|
|
||||||
|
function focus(index: number) {
|
||||||
|
void nextTick(() => inputs.value[Math.max(0, Math.min(index, props.length - 1))]?.focus())
|
||||||
|
}
|
||||||
|
|
||||||
|
function onInput(index: number, event: Event) {
|
||||||
|
const value = (event.target as HTMLInputElement).value.replace(/\D/g, '')
|
||||||
|
if (value.length > 1) {
|
||||||
|
fill(index, value)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
digits.value[index] = value
|
||||||
|
sync()
|
||||||
|
if (value) focus(index + 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
function fill(start: number, value: string) {
|
||||||
|
for (const [offset, char] of [...value].entries()) {
|
||||||
|
if (start + offset < props.length) digits.value[start + offset] = char
|
||||||
|
}
|
||||||
|
sync()
|
||||||
|
focus(start + value.length)
|
||||||
|
}
|
||||||
|
|
||||||
|
function onPaste(index: number, event: ClipboardEvent) {
|
||||||
|
const text = event.clipboardData?.getData('text').replace(/\D/g, '') ?? ''
|
||||||
|
if (!text) return
|
||||||
|
event.preventDefault()
|
||||||
|
fill(index, text)
|
||||||
|
}
|
||||||
|
|
||||||
|
function onKeydown(index: number, event: KeyboardEvent) {
|
||||||
|
if (event.key === 'Backspace' && !digits.value[index]) focus(index - 1)
|
||||||
|
if (event.key === 'ArrowLeft') focus(index - 1)
|
||||||
|
if (event.key === 'ArrowRight') focus(index + 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
function clear() {
|
||||||
|
digits.value = digits.value.map(() => '')
|
||||||
|
sync()
|
||||||
|
focus(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
defineExpose({ clear })
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="code-input" role="group" :aria-label="label">
|
||||||
|
<input
|
||||||
|
v-for="(_, index) in digits"
|
||||||
|
:key="index"
|
||||||
|
ref="inputs"
|
||||||
|
v-model="digits[index]"
|
||||||
|
type="text"
|
||||||
|
inputmode="numeric"
|
||||||
|
maxlength="6"
|
||||||
|
:autocomplete="index === 0 ? 'one-time-code' : 'off'"
|
||||||
|
:autofocus="autofocus && index === 0"
|
||||||
|
:aria-label="`${label} – chiffre ${index + 1}`"
|
||||||
|
class="form-control digit"
|
||||||
|
@input="onInput(index, $event)"
|
||||||
|
@paste="onPaste(index, $event)"
|
||||||
|
@keydown="onKeydown(index, $event)"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.code-input {
|
||||||
|
display: flex;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.digit {
|
||||||
|
width: 52px;
|
||||||
|
height: 60px;
|
||||||
|
padding: 0;
|
||||||
|
text-align: center;
|
||||||
|
font-size: 1.5rem;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 400px) {
|
||||||
|
.digit {
|
||||||
|
width: 42px;
|
||||||
|
height: 52px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed } from 'vue'
|
||||||
|
import { useI18n } from 'vue-i18n'
|
||||||
|
|
||||||
|
import type { FactorStatus } from '@/api/types'
|
||||||
|
|
||||||
|
const props = defineProps<{ level: number | null; status: FactorStatus }>()
|
||||||
|
const { t } = useI18n()
|
||||||
|
|
||||||
|
const levelClass = computed(() =>
|
||||||
|
props.status === 'ok' && props.level ? `level-${props.level}` : 'level-none',
|
||||||
|
)
|
||||||
|
|
||||||
|
const text = computed(() => {
|
||||||
|
if (props.status === 'unavailable') return t('factor.unavailableBadge')
|
||||||
|
if (props.status === 'no_data') return t('factor.noDataBadge')
|
||||||
|
return t(`factor.levels.${props.level ?? 'none'}`)
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<span class="color-badge" :class="[levelClass, { muted: status !== 'ok' || !level }]">
|
||||||
|
{{ text }}
|
||||||
|
</span>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.color-badge {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
height: 28px;
|
||||||
|
padding: 0 14px;
|
||||||
|
border-radius: 14px;
|
||||||
|
background: var(--level-color);
|
||||||
|
color: #fff;
|
||||||
|
font-size: 0.8125rem;
|
||||||
|
font-weight: 500;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.color-badge.muted {
|
||||||
|
background: var(--prism-bg);
|
||||||
|
border: 1px solid var(--prism-border);
|
||||||
|
color: var(--prism-text);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { Detail } from '@/api/types'
|
||||||
|
|
||||||
|
defineProps<{ details: Detail[] }>()
|
||||||
|
|
||||||
|
function dotClass(detail: Detail): string {
|
||||||
|
return detail.status === 'exceeded' ? 'level-4' : 'level-1'
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<dl v-if="details.length" class="detail-list">
|
||||||
|
<div v-for="detail in details" :key="detail.label" class="detail-row">
|
||||||
|
<dt>{{ detail.label }}</dt>
|
||||||
|
<dd>
|
||||||
|
<span v-if="detail.status" class="dot" :class="dotClass(detail)" aria-hidden="true"></span>
|
||||||
|
<span>{{ detail.value }}</span>
|
||||||
|
<span v-if="detail.status === 'exceeded'" class="visually-hidden"> (dépassé)</span>
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
|
</dl>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.detail-list {
|
||||||
|
background: var(--prism-bg);
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 6px 16px;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.detail-row {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
gap: 1rem;
|
||||||
|
min-height: 36px;
|
||||||
|
padding: 0.4rem 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.detail-row + .detail-row {
|
||||||
|
border-top: 1px solid var(--prism-border);
|
||||||
|
}
|
||||||
|
|
||||||
|
dt {
|
||||||
|
font-weight: 400;
|
||||||
|
color: var(--prism-text);
|
||||||
|
}
|
||||||
|
|
||||||
|
dd {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
margin: 0;
|
||||||
|
color: var(--prism-navy);
|
||||||
|
font-weight: 500;
|
||||||
|
text-align: right;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed } from 'vue'
|
||||||
|
|
||||||
|
import type { FactorResult } from '@/api/types'
|
||||||
|
|
||||||
|
import ColorBadge from './ColorBadge.vue'
|
||||||
|
import DetailList from './DetailList.vue'
|
||||||
|
import InfoTabs from './InfoTabs.vue'
|
||||||
|
import ReferenceList from './ReferenceList.vue'
|
||||||
|
|
||||||
|
const props = defineProps<{ factor: FactorResult }>()
|
||||||
|
defineEmits<{ retry: [] }>()
|
||||||
|
|
||||||
|
const levelClass = computed(() =>
|
||||||
|
props.factor.status === 'ok' && props.factor.level ? `level-${props.factor.level}` : 'level-none',
|
||||||
|
)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<article
|
||||||
|
class="factor-card prism-card"
|
||||||
|
:class="{ unavailable: factor.status !== 'ok' }"
|
||||||
|
:aria-labelledby="`factor-${factor.code}`"
|
||||||
|
>
|
||||||
|
<header class="factor-header">
|
||||||
|
<span class="factor-dot" :class="levelClass" aria-hidden="true"></span>
|
||||||
|
<h2 :id="`factor-${factor.code}`" class="factor-title">{{ factor.label }}</h2>
|
||||||
|
<ColorBadge class="ms-sm-auto" :level="factor.level" :status="factor.status" />
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<template v-if="factor.status === 'ok'">
|
||||||
|
<p v-if="factor.summary" class="summary">{{ factor.summary }}</p>
|
||||||
|
<DetailList :details="factor.details" />
|
||||||
|
<InfoTabs :tabs="factor.tabs" />
|
||||||
|
<ReferenceList :references="factor.references" />
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<template v-else>
|
||||||
|
<p class="summary">
|
||||||
|
{{
|
||||||
|
factor.status === 'unavailable'
|
||||||
|
? $t('factor.unavailable', { label: factor.label.toLowerCase() })
|
||||||
|
: $t('factor.noData')
|
||||||
|
}}
|
||||||
|
</p>
|
||||||
|
<div v-if="factor.status === 'unavailable'">
|
||||||
|
<button type="button" class="btn btn-outline-primary" @click="$emit('retry')">
|
||||||
|
{{ $t('factor.retry') }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</article>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.factor-card {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 14px;
|
||||||
|
padding: 22px 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.factor-card.unavailable {
|
||||||
|
border: 1px dashed var(--prism-level-none);
|
||||||
|
}
|
||||||
|
|
||||||
|
.factor-header {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 575.98px) {
|
||||||
|
.factor-header :deep(.color-badge) {
|
||||||
|
order: 3;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.factor-dot {
|
||||||
|
width: 22px;
|
||||||
|
height: 22px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--level-color);
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.factor-title {
|
||||||
|
font-size: 1.25rem;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.summary {
|
||||||
|
color: var(--prism-navy);
|
||||||
|
font-size: 0.9375rem;
|
||||||
|
font-weight: 500;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref, useId } from 'vue'
|
||||||
|
|
||||||
|
import type { FactorResult } from '@/api/types'
|
||||||
|
|
||||||
|
const props = defineProps<{ tabs: FactorResult['tabs'] }>()
|
||||||
|
|
||||||
|
type TabKey = 'health_effects' | 'actions' | 'legend'
|
||||||
|
const keys: TabKey[] = ['health_effects', 'actions', 'legend']
|
||||||
|
const active = ref<TabKey>('health_effects')
|
||||||
|
const id = useId()
|
||||||
|
|
||||||
|
/** Les textes de la SSMG sont rédigés une idée par ligne : rendus en liste à puces. */
|
||||||
|
function lines(text: string): string[] {
|
||||||
|
return text
|
||||||
|
.split('\n')
|
||||||
|
.map((line) => line.replace(/^[-•]\s*/, '').trim())
|
||||||
|
.filter(Boolean)
|
||||||
|
}
|
||||||
|
|
||||||
|
const content = computed(() =>
|
||||||
|
active.value === 'legend' ? lines(props.tabs.legend.text) : lines(props.tabs[active.value]),
|
||||||
|
)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div>
|
||||||
|
<div class="tab-list" role="tablist">
|
||||||
|
<button
|
||||||
|
v-for="key in keys"
|
||||||
|
:id="`${id}-tab-${key}`"
|
||||||
|
:key="key"
|
||||||
|
type="button"
|
||||||
|
role="tab"
|
||||||
|
class="tab"
|
||||||
|
:class="{ active: active === key }"
|
||||||
|
:aria-selected="active === key"
|
||||||
|
:aria-controls="`${id}-panel`"
|
||||||
|
@click="active = key"
|
||||||
|
>
|
||||||
|
{{ $t(`factor.tabs.${key}`) }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div
|
||||||
|
:id="`${id}-panel`"
|
||||||
|
role="tabpanel"
|
||||||
|
:aria-labelledby="`${id}-tab-${active}`"
|
||||||
|
class="tab-panel"
|
||||||
|
>
|
||||||
|
<template v-if="active === 'legend'">
|
||||||
|
<ul v-if="tabs.legend.scale.length" class="list-unstyled scale">
|
||||||
|
<li v-for="item in tabs.legend.scale" :key="item.level + item.label">
|
||||||
|
<span class="dot" :class="`level-${item.level}`" aria-hidden="true"></span>
|
||||||
|
{{ item.label }}
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<p v-if="tabs.legend.source" class="source">
|
||||||
|
{{ $t('factor.source', { source: tabs.legend.source }) }}
|
||||||
|
</p>
|
||||||
|
</template>
|
||||||
|
<ul v-if="content.length" class="bullets">
|
||||||
|
<li v-for="line in content" :key="line">{{ line }}</li>
|
||||||
|
</ul>
|
||||||
|
<p v-else-if="active !== 'legend' || !tabs.legend.scale.length" class="empty">
|
||||||
|
{{ $t('factor.emptyTab') }}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.tab-list {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab {
|
||||||
|
height: 32px;
|
||||||
|
padding: 0 14px;
|
||||||
|
border-radius: 14px;
|
||||||
|
border: 1px solid var(--prism-border);
|
||||||
|
background: var(--prism-surface);
|
||||||
|
color: var(--prism-text);
|
||||||
|
font-size: 0.8125rem;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab.active {
|
||||||
|
background: var(--prism-navy);
|
||||||
|
border-color: var(--prism-navy);
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab:focus-visible {
|
||||||
|
outline: 2px solid var(--prism-orange);
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab-panel {
|
||||||
|
padding-top: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bullets {
|
||||||
|
margin: 0;
|
||||||
|
padding-left: 0;
|
||||||
|
list-style: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bullets li {
|
||||||
|
position: relative;
|
||||||
|
padding-left: 12px;
|
||||||
|
margin-bottom: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bullets li::before {
|
||||||
|
content: '•';
|
||||||
|
position: absolute;
|
||||||
|
left: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.scale li {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
margin-bottom: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.source,
|
||||||
|
.empty {
|
||||||
|
color: var(--prism-muted);
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,266 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ref } from 'vue'
|
||||||
|
import { useI18n } from 'vue-i18n'
|
||||||
|
|
||||||
|
import { api, ApiError } from '@/api/client'
|
||||||
|
import type { TotpSetup } from '@/api/types'
|
||||||
|
import { useAuth } from '@/composables/useAuth'
|
||||||
|
|
||||||
|
import AlertBanner from './AlertBanner.vue'
|
||||||
|
import CodeInput from './CodeInput.vue'
|
||||||
|
import RecoveryCodes from './RecoveryCodes.vue'
|
||||||
|
|
||||||
|
type Mode = 'idle' | 'setup' | 'codes' | 'disable' | 'regenerate'
|
||||||
|
|
||||||
|
const { user, load } = useAuth()
|
||||||
|
const { t } = useI18n()
|
||||||
|
|
||||||
|
const mode = ref<Mode>('idle')
|
||||||
|
const setup = ref<TotpSetup | null>(null)
|
||||||
|
const codes = ref<string[]>([])
|
||||||
|
const code = ref('')
|
||||||
|
const password = ref('')
|
||||||
|
const error = ref('')
|
||||||
|
const loading = ref(false)
|
||||||
|
const done = ref('')
|
||||||
|
|
||||||
|
function reset(next: Mode = 'idle') {
|
||||||
|
mode.value = next
|
||||||
|
code.value = ''
|
||||||
|
password.value = ''
|
||||||
|
error.value = ''
|
||||||
|
}
|
||||||
|
|
||||||
|
function message(e: unknown) {
|
||||||
|
if (e instanceof ApiError && e.status === 400) return e.message
|
||||||
|
if (e instanceof ApiError && e.status === 429) return t('login.throttled')
|
||||||
|
return t('account.error')
|
||||||
|
}
|
||||||
|
|
||||||
|
async function run(action: () => Promise<void>) {
|
||||||
|
error.value = ''
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
await action()
|
||||||
|
} catch (e) {
|
||||||
|
error.value = message(e)
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const start = () =>
|
||||||
|
run(async () => {
|
||||||
|
done.value = ''
|
||||||
|
setup.value = await api.setupTotp()
|
||||||
|
reset('setup')
|
||||||
|
})
|
||||||
|
|
||||||
|
const enable = () =>
|
||||||
|
run(async () => {
|
||||||
|
codes.value = (await api.enableTotp(code.value)).recovery_codes
|
||||||
|
setup.value = null
|
||||||
|
reset('codes')
|
||||||
|
})
|
||||||
|
|
||||||
|
const disable = () =>
|
||||||
|
run(async () => {
|
||||||
|
await api.disableTotp(password.value, code.value)
|
||||||
|
await load(true)
|
||||||
|
reset()
|
||||||
|
done.value = t('account.mfa.disabled')
|
||||||
|
})
|
||||||
|
|
||||||
|
const regenerate = () =>
|
||||||
|
run(async () => {
|
||||||
|
codes.value = (await api.regenerateRecoveryCodes(code.value)).recovery_codes
|
||||||
|
reset('codes')
|
||||||
|
})
|
||||||
|
|
||||||
|
async function finish() {
|
||||||
|
codes.value = []
|
||||||
|
await load(true)
|
||||||
|
reset()
|
||||||
|
done.value = t('account.mfa.enabledDone')
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<section class="prism-card panel" aria-labelledby="mfa-heading">
|
||||||
|
<!-- Étape 1 et 2 de l'activation (maquette 14) -->
|
||||||
|
<template v-if="mode === 'setup' && setup">
|
||||||
|
<h2 id="mfa-heading" class="card-title">{{ $t('account.mfa.setupTitle') }}</h2>
|
||||||
|
<AlertBanner v-if="error" variant="error" class="mb-3">{{ error }}</AlertBanner>
|
||||||
|
<div class="row g-4">
|
||||||
|
<div class="col-12">
|
||||||
|
<h3 class="step">{{ $t('account.mfa.step1') }}</h3>
|
||||||
|
<p class="small-text">{{ $t('account.mfa.step1Text') }}</p>
|
||||||
|
<img :src="setup.qr_code" :alt="$t('account.mfa.qrAlt')" class="qr" />
|
||||||
|
<p class="secret">
|
||||||
|
{{ $t('account.mfa.secret') }} <span class="font-monospace">{{ setup.secret }}</span>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div class="col-12">
|
||||||
|
<h3 class="step">{{ $t('account.mfa.step2') }}</h3>
|
||||||
|
<p class="small-text">{{ $t('account.mfa.step2Text') }}</p>
|
||||||
|
<form @submit.prevent="enable">
|
||||||
|
<CodeInput v-model="code" class="mb-3" :label="$t('mfa.codeLabel')" />
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
class="btn btn-primary action"
|
||||||
|
:disabled="loading || code.length !== 6"
|
||||||
|
>
|
||||||
|
{{ $t('account.mfa.activate') }}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
<button type="button" class="btn btn-link link-strong px-0 mt-2" @click="reset()">
|
||||||
|
{{ $t('account.cancel') }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- Codes de secours (maquette 15) -->
|
||||||
|
<RecoveryCodes v-else-if="mode === 'codes'" :codes="codes" @done="finish" />
|
||||||
|
|
||||||
|
<template v-else>
|
||||||
|
<div class="d-flex align-items-start justify-content-between gap-3 mb-3">
|
||||||
|
<h2 id="mfa-heading" class="card-title mb-0">{{ $t('account.mfa.title') }}</h2>
|
||||||
|
<span class="status" :class="{ on: user?.mfa_enabled }">
|
||||||
|
{{ user?.mfa_enabled ? $t('account.mfa.on') : $t('account.mfa.off') }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<AlertBanner v-if="done" variant="info" class="mb-3">{{ done }}</AlertBanner>
|
||||||
|
<AlertBanner v-if="user?.is_staff && !user.mfa_enabled" variant="error" class="mb-3">
|
||||||
|
{{ $t('account.mfa.mandatory') }}
|
||||||
|
</AlertBanner>
|
||||||
|
|
||||||
|
<template v-if="!user?.mfa_enabled">
|
||||||
|
<p>{{ $t('account.mfa.explain') }}</p>
|
||||||
|
<AlertBanner v-if="error" variant="error" class="mb-3">{{ error }}</AlertBanner>
|
||||||
|
<button type="button" class="btn btn-outline-primary" :disabled="loading" @click="start">
|
||||||
|
{{ $t('account.mfa.enable') }}
|
||||||
|
</button>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<template v-else>
|
||||||
|
<p>{{ $t('account.mfa.enabledText') }}</p>
|
||||||
|
|
||||||
|
<form
|
||||||
|
v-if="mode === 'regenerate' || mode === 'disable'"
|
||||||
|
class="mt-3"
|
||||||
|
@submit.prevent="mode === 'disable' ? disable() : regenerate()"
|
||||||
|
>
|
||||||
|
<AlertBanner v-if="error" variant="error" class="mb-3">{{ error }}</AlertBanner>
|
||||||
|
<div v-if="mode === 'disable'" class="mb-3">
|
||||||
|
<label for="mfa-password" class="form-label">{{ $t('account.currentPassword') }}</label>
|
||||||
|
<input
|
||||||
|
id="mfa-password"
|
||||||
|
v-model="password"
|
||||||
|
type="password"
|
||||||
|
class="form-control"
|
||||||
|
autocomplete="current-password"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<label for="mfa-code" class="form-label">
|
||||||
|
{{ mode === 'disable' ? $t('account.mfa.codeOrRecovery') : $t('mfa.codeLabel') }}
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="mfa-code"
|
||||||
|
v-model.trim="code"
|
||||||
|
class="form-control mb-3"
|
||||||
|
autocomplete="one-time-code"
|
||||||
|
:inputmode="mode === 'disable' ? 'text' : 'numeric'"
|
||||||
|
/>
|
||||||
|
<div class="d-flex flex-wrap gap-3 align-items-center">
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
class="btn"
|
||||||
|
:class="mode === 'disable' ? 'btn-danger' : 'btn-primary'"
|
||||||
|
:disabled="loading || !code || (mode === 'disable' && !password)"
|
||||||
|
>
|
||||||
|
{{ mode === 'disable' ? $t('account.mfa.disable') : $t('account.mfa.regenerate') }}
|
||||||
|
</button>
|
||||||
|
<button type="button" class="btn btn-link link-strong px-0" @click="reset()">
|
||||||
|
{{ $t('account.cancel') }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div v-else class="d-flex flex-wrap gap-3">
|
||||||
|
<button type="button" class="btn btn-outline-primary" @click="reset('regenerate')">
|
||||||
|
{{ $t('account.mfa.regenerate') }}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
v-if="!user.is_staff"
|
||||||
|
type="button"
|
||||||
|
class="btn btn-link link-strong px-0"
|
||||||
|
@click="reset('disable')"
|
||||||
|
>
|
||||||
|
{{ $t('account.mfa.disable') }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</template>
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.panel {
|
||||||
|
padding: 24px 28px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card-title {
|
||||||
|
font-size: 1.25rem;
|
||||||
|
margin-bottom: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.step {
|
||||||
|
font-size: 1rem;
|
||||||
|
margin-bottom: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.small-text {
|
||||||
|
font-size: 0.8125rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.qr {
|
||||||
|
width: 200px;
|
||||||
|
height: 200px;
|
||||||
|
padding: 10px;
|
||||||
|
border: 1px solid var(--prism-border);
|
||||||
|
border-radius: 8px;
|
||||||
|
background: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.secret {
|
||||||
|
margin-top: 1rem;
|
||||||
|
font-size: 0.8125rem;
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--prism-navy);
|
||||||
|
}
|
||||||
|
|
||||||
|
.action {
|
||||||
|
min-width: 160px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
height: 28px;
|
||||||
|
padding: 0 14px;
|
||||||
|
border-radius: 14px;
|
||||||
|
border: 1px solid var(--prism-border);
|
||||||
|
background: var(--prism-bg);
|
||||||
|
font-size: 0.8125rem;
|
||||||
|
font-weight: 500;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status.on {
|
||||||
|
background: var(--prism-level-1);
|
||||||
|
border-color: var(--prism-level-1);
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ref } from 'vue'
|
||||||
|
|
||||||
|
const props = defineProps<{ codes: string[] }>()
|
||||||
|
const emit = defineEmits<{ done: [] }>()
|
||||||
|
|
||||||
|
const saved = ref(false)
|
||||||
|
const copied = ref(false)
|
||||||
|
|
||||||
|
async function copy() {
|
||||||
|
await navigator.clipboard.writeText(props.codes.join('\n'))
|
||||||
|
copied.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
function download() {
|
||||||
|
const blob = new Blob([`Codes de secours PRISM\n\n${props.codes.join('\n')}\n`], {
|
||||||
|
type: 'text/plain',
|
||||||
|
})
|
||||||
|
const url = URL.createObjectURL(blob)
|
||||||
|
const link = document.createElement('a')
|
||||||
|
link.href = url
|
||||||
|
link.download = 'prism-codes-de-secours.txt'
|
||||||
|
link.click()
|
||||||
|
URL.revokeObjectURL(url)
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div>
|
||||||
|
<h2 class="card-title">{{ $t('account.mfa.codesTitle') }}</h2>
|
||||||
|
<p>{{ $t('account.mfa.codesText', { count: codes.length }) }}</p>
|
||||||
|
<div class="codes-warning" role="status">{{ $t('account.mfa.codesWarning') }}</div>
|
||||||
|
|
||||||
|
<ul class="codes list-unstyled">
|
||||||
|
<li v-for="code in codes" :key="code" class="font-monospace">{{ code }}</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<div class="d-flex flex-wrap gap-3 mb-4">
|
||||||
|
<button type="button" class="btn btn-outline-primary action" @click="copy">
|
||||||
|
{{ copied ? $t('account.mfa.copied') : $t('account.mfa.copy') }}
|
||||||
|
</button>
|
||||||
|
<button type="button" class="btn btn-outline-primary action" @click="download">
|
||||||
|
{{ $t('account.mfa.download') }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<hr />
|
||||||
|
<div class="form-check mb-3">
|
||||||
|
<input id="codes-saved" v-model="saved" class="form-check-input" type="checkbox" />
|
||||||
|
<label for="codes-saved" class="form-check-label">{{ $t('account.mfa.saved') }}</label>
|
||||||
|
</div>
|
||||||
|
<button type="button" class="btn btn-primary action" :disabled="!saved" @click="emit('done')">
|
||||||
|
{{ $t('account.mfa.finish') }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.card-title {
|
||||||
|
font-size: 1.25rem;
|
||||||
|
margin-bottom: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.codes-warning {
|
||||||
|
background: #fdf0e6;
|
||||||
|
color: #7a3b0e;
|
||||||
|
font-weight: 500;
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 0.6rem 0.875rem;
|
||||||
|
margin-bottom: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.codes {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
gap: 10px;
|
||||||
|
margin-bottom: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.codes li {
|
||||||
|
background: var(--prism-bg);
|
||||||
|
border: 1px solid var(--prism-border);
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 0.7rem 0.875rem;
|
||||||
|
font-size: 1rem;
|
||||||
|
color: var(--prism-navy);
|
||||||
|
}
|
||||||
|
|
||||||
|
.action {
|
||||||
|
min-width: 160px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-check-input:checked {
|
||||||
|
background-color: var(--prism-orange);
|
||||||
|
border-color: var(--prism-orange);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { Reference } from '@/api/types'
|
||||||
|
|
||||||
|
defineProps<{ references: Reference[] }>()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<p v-if="references.length" class="references">
|
||||||
|
{{ $t('factor.references') }}
|
||||||
|
<template v-for="ref in references" :key="ref.n">
|
||||||
|
<a v-if="ref.url" :href="ref.url" target="_blank" rel="noopener noreferrer">
|
||||||
|
{{ ref.n }}. {{ ref.title }}</a
|
||||||
|
><span v-else>{{ ref.n }}. {{ ref.title }}</span>
|
||||||
|
</template>
|
||||||
|
</p>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.references {
|
||||||
|
border-top: 1px solid var(--prism-border);
|
||||||
|
padding-top: 14px;
|
||||||
|
margin: 0;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
color: var(--prism-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.references a,
|
||||||
|
.references span {
|
||||||
|
margin-left: 0.5rem;
|
||||||
|
color: var(--prism-muted);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,250 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { setWorkerUrl } from 'maplibre-gl'
|
||||||
|
import workerUrl from 'maplibre-gl/dist/maplibre-gl-worker.mjs?url'
|
||||||
|
|
||||||
|
// MapLibre cherche son worker à côté de son propre module, ce que le regroupement de Vite
|
||||||
|
// casse : sans worker, aucune source raster (couches WMS) ne se charge.
|
||||||
|
setWorkerUrl(workerUrl)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { Map as MapLibreMap, Marker, NavigationControl, ScaleControl } from 'maplibre-gl'
|
||||||
|
import { onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||||
|
|
||||||
|
import type { Assessment } from '@/api/types'
|
||||||
|
|
||||||
|
const props = defineProps<{ location: Assessment['location'] | null }>()
|
||||||
|
|
||||||
|
const WALONMAP_WMS = 'https://geoservices.wallonie.be/arcgis/services'
|
||||||
|
// Fond OpenStreetMap : les serveurs publics ne sont pas prévus pour la production
|
||||||
|
// (specs, risque 12). À remplacer par un fournisseur de tuiles avant la mise en production.
|
||||||
|
const OSM_TILES = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png'
|
||||||
|
const BELGIUM: [number, number] = [4.47, 50.5]
|
||||||
|
|
||||||
|
function wms(service: string, layers: string): string {
|
||||||
|
const params = new URLSearchParams({
|
||||||
|
service: 'WMS',
|
||||||
|
request: 'GetMap',
|
||||||
|
version: '1.3.0',
|
||||||
|
layers,
|
||||||
|
styles: '',
|
||||||
|
format: 'image/png',
|
||||||
|
transparent: 'true',
|
||||||
|
crs: 'EPSG:3857',
|
||||||
|
width: '256',
|
||||||
|
height: '256',
|
||||||
|
})
|
||||||
|
return `${WALONMAP_WMS}/${service}/MapServer/WMSServer?${params}&bbox={bbox-epsg-3857}`
|
||||||
|
}
|
||||||
|
|
||||||
|
const overlays = [
|
||||||
|
// Couches 1, 2 et 3 : chacune ne couvre qu'une plage d'échelles (1:25 000 et moins, entre
|
||||||
|
// 1:25 000 et 1:5 000, au-delà de 1:5 000).
|
||||||
|
{ id: 'flood', url: wms('EAU/ALEA_INOND', '1,2,3'), color: '#00b0f0' },
|
||||||
|
{ id: 'noise', url: wms('INDUSTRIES_SERVICES/BRUIT_MROAD_2017', '1'), color: '#e85b25' },
|
||||||
|
] as const
|
||||||
|
|
||||||
|
type OverlayId = (typeof overlays)[number]['id']
|
||||||
|
|
||||||
|
const container = ref<HTMLDivElement>()
|
||||||
|
const layersPanel = ref<HTMLFieldSetElement>()
|
||||||
|
const visible = ref<Record<OverlayId, boolean>>({ flood: true, noise: false })
|
||||||
|
let map: MapLibreMap | null = null
|
||||||
|
let marker: Marker | null = null
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
const instance = new MapLibreMap({
|
||||||
|
container: container.value!,
|
||||||
|
center: BELGIUM,
|
||||||
|
zoom: 7,
|
||||||
|
attributionControl: { compact: false },
|
||||||
|
style: {
|
||||||
|
version: 8,
|
||||||
|
sources: {
|
||||||
|
osm: {
|
||||||
|
type: 'raster',
|
||||||
|
tiles: [OSM_TILES],
|
||||||
|
tileSize: 256,
|
||||||
|
maxzoom: 19,
|
||||||
|
attribution: '© OpenStreetMap contributors',
|
||||||
|
},
|
||||||
|
...Object.fromEntries(
|
||||||
|
overlays.map((o) => [
|
||||||
|
o.id,
|
||||||
|
{ type: 'raster', tiles: [o.url], tileSize: 256, attribution: '© SPW – WalOnMap' },
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
},
|
||||||
|
layers: [
|
||||||
|
{ id: 'osm', type: 'raster', source: 'osm' },
|
||||||
|
...overlays.map((o) => ({
|
||||||
|
id: o.id,
|
||||||
|
type: 'raster' as const,
|
||||||
|
source: o.id,
|
||||||
|
paint: { 'raster-opacity': 0.6 },
|
||||||
|
layout: { visibility: visible.value[o.id] ? ('visible' as const) : ('none' as const) },
|
||||||
|
})),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
instance.addControl(new NavigationControl({ showCompass: false }), 'top-right')
|
||||||
|
instance.addControl(new ScaleControl({ unit: 'metric' }), 'bottom-left')
|
||||||
|
map = instance
|
||||||
|
showLocation()
|
||||||
|
})
|
||||||
|
|
||||||
|
onBeforeUnmount(() => {
|
||||||
|
map?.remove()
|
||||||
|
map = null
|
||||||
|
})
|
||||||
|
|
||||||
|
function showLocation() {
|
||||||
|
if (!map || !props.location) return
|
||||||
|
const lngLat: [number, number] = [props.location.lon, props.location.lat]
|
||||||
|
marker?.remove()
|
||||||
|
marker = new Marker({ color: '#e85b25' }).setLngLat(lngLat).addTo(map)
|
||||||
|
// La mise en page peut avoir changé depuis la création de la carte.
|
||||||
|
map.resize()
|
||||||
|
// Décale le centre sous le panneau des couches pour que le marqueur reste visible.
|
||||||
|
const top = (layersPanel.value?.offsetHeight ?? 0) + 12
|
||||||
|
map.jumpTo({ center: lngLat, zoom: 15, padding: { top, bottom: 0, left: 0, right: 0 } })
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggle(id: OverlayId) {
|
||||||
|
visible.value[id] = !visible.value[id]
|
||||||
|
map?.setLayoutProperty(id, 'visibility', visible.value[id] ? 'visible' : 'none')
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(() => props.location, showLocation, { flush: 'post' })
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="result-map prism-card" :class="{ expanded: !location }">
|
||||||
|
<div ref="container" class="map" role="region" :aria-label="$t('map.label')"></div>
|
||||||
|
|
||||||
|
<fieldset ref="layersPanel" class="map-panel layers">
|
||||||
|
<legend>{{ $t('map.layers') }}</legend>
|
||||||
|
<div class="form-check">
|
||||||
|
<input id="layer-osm" class="form-check-input" type="checkbox" checked disabled />
|
||||||
|
<label class="form-check-label" for="layer-osm">{{ $t('map.basemap') }}</label>
|
||||||
|
</div>
|
||||||
|
<div v-for="overlay in overlays" :key="overlay.id" class="form-check">
|
||||||
|
<input
|
||||||
|
:id="`layer-${overlay.id}`"
|
||||||
|
class="form-check-input"
|
||||||
|
type="checkbox"
|
||||||
|
:checked="visible[overlay.id]"
|
||||||
|
@change="toggle(overlay.id)"
|
||||||
|
/>
|
||||||
|
<label class="form-check-label" :for="`layer-${overlay.id}`">
|
||||||
|
{{ $t(`map.${overlay.id}`) }}
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
|
<div class="map-panel legend">
|
||||||
|
<strong>{{ $t('map.legend') }}</strong>
|
||||||
|
<div>
|
||||||
|
<span class="swatch round" style="background: #e85b25"></span>{{ $t('map.patient') }}
|
||||||
|
</div>
|
||||||
|
<template v-for="overlay in overlays" :key="overlay.id">
|
||||||
|
<div v-if="visible[overlay.id]">
|
||||||
|
<span class="swatch" :style="{ background: overlay.color }"></span>
|
||||||
|
{{ $t(`map.${overlay.id}`) }}
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.result-map {
|
||||||
|
position: relative;
|
||||||
|
overflow: hidden;
|
||||||
|
height: 720px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Avant la première analyse, la carte occupe toute la hauteur disponible. */
|
||||||
|
.result-map.expanded {
|
||||||
|
height: max(420px, calc(100vh - 330px));
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (min-width: 992px) {
|
||||||
|
.result-map {
|
||||||
|
position: sticky;
|
||||||
|
top: 24px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 991.98px) {
|
||||||
|
.result-map,
|
||||||
|
.result-map.expanded {
|
||||||
|
height: 240px;
|
||||||
|
}
|
||||||
|
.legend {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.map {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.map-panel {
|
||||||
|
position: absolute;
|
||||||
|
left: 12px;
|
||||||
|
z-index: 2;
|
||||||
|
background: var(--prism-surface);
|
||||||
|
border: 1px solid var(--prism-border);
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 10px 12px;
|
||||||
|
font-size: 0.6875rem;
|
||||||
|
box-shadow: 0 2px 8px rgb(9 41 51 / 10%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.layers {
|
||||||
|
top: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.layers legend {
|
||||||
|
float: none;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--prism-navy);
|
||||||
|
margin-bottom: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-check {
|
||||||
|
margin-bottom: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-check-input:checked {
|
||||||
|
background-color: var(--prism-orange);
|
||||||
|
border-color: var(--prism-orange);
|
||||||
|
}
|
||||||
|
|
||||||
|
.legend {
|
||||||
|
bottom: 40px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.legend strong {
|
||||||
|
display: block;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
color: var(--prism-navy);
|
||||||
|
margin-bottom: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.swatch {
|
||||||
|
display: inline-block;
|
||||||
|
width: 10px;
|
||||||
|
height: 10px;
|
||||||
|
margin-right: 8px;
|
||||||
|
border-radius: 2px;
|
||||||
|
vertical-align: middle;
|
||||||
|
}
|
||||||
|
|
||||||
|
.swatch.round {
|
||||||
|
border-radius: 50%;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import { computed, ref } from 'vue'
|
||||||
|
|
||||||
|
import { api, ApiError } from '@/api/client'
|
||||||
|
import type { User } from '@/api/types'
|
||||||
|
|
||||||
|
// État partagé : un simple ref suffit (pas de Pinia, specs §3).
|
||||||
|
const user = ref<User | null>(null)
|
||||||
|
const loaded = ref(false)
|
||||||
|
|
||||||
|
export function useAuth() {
|
||||||
|
/** Charge l'utilisateur courant une seule fois ; dépose aussi le cookie CSRF. */
|
||||||
|
async function load(force = false): Promise<User | null> {
|
||||||
|
if (loaded.value && !force) {
|
||||||
|
return user.value
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
user.value = await api.me()
|
||||||
|
} catch (error) {
|
||||||
|
if (!(error instanceof ApiError) || error.status !== 403) {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
user.value = null
|
||||||
|
} finally {
|
||||||
|
loaded.value = true
|
||||||
|
}
|
||||||
|
return user.value
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Étape 1. Renvoie `true` si un second facteur est demandé. */
|
||||||
|
async function login(email: string, password: string): Promise<boolean> {
|
||||||
|
const result = await api.login(email, password)
|
||||||
|
if (result.mfa_required) return true
|
||||||
|
// Django renouvelle le jeton CSRF à la connexion : on recharge l'utilisateur (et le jeton).
|
||||||
|
await load(true)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Étape 2 : code TOTP ou code de secours. */
|
||||||
|
async function verifyMfa(code: string): Promise<void> {
|
||||||
|
await api.verifyMfa(code)
|
||||||
|
await load(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function logout(): Promise<void> {
|
||||||
|
try {
|
||||||
|
await api.logout()
|
||||||
|
} finally {
|
||||||
|
user.value = null
|
||||||
|
await load(true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
user,
|
||||||
|
isAuthenticated: computed(() => user.value !== null),
|
||||||
|
load,
|
||||||
|
login,
|
||||||
|
verifyMfa,
|
||||||
|
logout,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Réinitialise l'état (tests). */
|
||||||
|
export function resetAuth() {
|
||||||
|
user.value = null
|
||||||
|
loaded.value = false
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { createI18n } from 'vue-i18n'
|
||||||
|
|
||||||
|
import fr from './locales/fr.json'
|
||||||
|
|
||||||
|
export default createI18n({
|
||||||
|
legacy: false,
|
||||||
|
locale: 'fr',
|
||||||
|
fallbackLocale: 'fr',
|
||||||
|
messages: { fr },
|
||||||
|
})
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
{
|
||||||
|
"app": {
|
||||||
|
"name": "PRISM",
|
||||||
|
"tagline": "Environnement et santé",
|
||||||
|
"disclaimer": "Outil complémentaire d'aide à la consultation : il ne remplace pas un diagnostic.",
|
||||||
|
"copyright": "© SSMG – Société Scientifique de Médecine Générale",
|
||||||
|
"logoAlt": "SSMG – Société Scientifique de Médecine Générale"
|
||||||
|
},
|
||||||
|
"nav": {
|
||||||
|
"doctor": "Dr {name}",
|
||||||
|
"logout": "Déconnexion",
|
||||||
|
"menu": "Menu",
|
||||||
|
"account": "Mon compte"
|
||||||
|
},
|
||||||
|
"login": {
|
||||||
|
"title": "Connexion",
|
||||||
|
"intro": "Accédez à l'évaluation de l'exposome environnemental de vos patients.",
|
||||||
|
"email": "Adresse e-mail",
|
||||||
|
"emailPlaceholder": "prenom.nom{'@'}exemple.be",
|
||||||
|
"password": "Mot de passe",
|
||||||
|
"submit": "Se connecter",
|
||||||
|
"submitting": "Connexion…",
|
||||||
|
"error": "Connexion impossible. Réessayez dans un instant.",
|
||||||
|
"noAccount": "Pas encore de compte ?",
|
||||||
|
"createAccount": "Créer un compte",
|
||||||
|
"throttled": "Trop de tentatives. Réessayez dans une minute.",
|
||||||
|
"forgot": "Mot de passe oublié ?"
|
||||||
|
},
|
||||||
|
"assessment": {
|
||||||
|
"addressLabel": "Adresse du patient",
|
||||||
|
"addressPlaceholder": "Rue, numéro, code postal, commune",
|
||||||
|
"submit": "Analyser",
|
||||||
|
"submitting": "Analyse…",
|
||||||
|
"recognized": "Adresse reconnue : {address} — {region}",
|
||||||
|
"regions": {
|
||||||
|
"WAL": "Région wallonne",
|
||||||
|
"BXL": "Région de Bruxelles-Capitale"
|
||||||
|
},
|
||||||
|
"errors": {
|
||||||
|
"address_not_found": "Adresse introuvable. Vérifiez la rue, le numéro et le code postal.",
|
||||||
|
"out_of_coverage": "Cette adresse est hors couverture : PRISM couvre la Wallonie et Bruxelles.",
|
||||||
|
"geocoding_unavailable": "Le service de géocodage est indisponible. Réessayez dans un instant.",
|
||||||
|
"throttled": "Trop d'analyses en peu de temps. Réessayez plus tard.",
|
||||||
|
"generic": "L'analyse a échoué. Réessayez dans un instant."
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"factor": {
|
||||||
|
"levels": {
|
||||||
|
"1": "Impact faible",
|
||||||
|
"2": "Impact modéré",
|
||||||
|
"3": "Impact élevé",
|
||||||
|
"4": "Impact très élevé",
|
||||||
|
"none": "Niveau non défini"
|
||||||
|
},
|
||||||
|
"unavailableBadge": "Donnée indisponible",
|
||||||
|
"noDataBadge": "Donnée absente",
|
||||||
|
"unavailable": "Le service de données « {label} » ne répond pas pour le moment.",
|
||||||
|
"noData": "Aucune donnée n'est disponible pour cette adresse.",
|
||||||
|
"retry": "Réessayer",
|
||||||
|
"loading": "Chargement…",
|
||||||
|
"tabs": {
|
||||||
|
"health_effects": "Effets sur la santé",
|
||||||
|
"actions": "Pistes d'action",
|
||||||
|
"legend": "Légende"
|
||||||
|
},
|
||||||
|
"emptyTab": "Contenu en cours de validation par la cellule Environnement de la SSMG.",
|
||||||
|
"source": "Source : {source}",
|
||||||
|
"references": "Références :"
|
||||||
|
},
|
||||||
|
"map": {
|
||||||
|
"layers": "Couches",
|
||||||
|
"basemap": "Fond de carte (OpenStreetMap)",
|
||||||
|
"flood": "Aléa d'inondation (WalOnMap)",
|
||||||
|
"noise": "Bruit routier – Lden (WalOnMap)",
|
||||||
|
"legend": "Légende",
|
||||||
|
"patient": "Adresse du patient",
|
||||||
|
"label": "Carte de l'adresse du patient"
|
||||||
|
},
|
||||||
|
"errors": {
|
||||||
|
"404": {
|
||||||
|
"title": "Page introuvable",
|
||||||
|
"text": "La page demandée n'existe pas ou a été déplacée."
|
||||||
|
},
|
||||||
|
"403": {
|
||||||
|
"title": "Accès refusé",
|
||||||
|
"text": "Vous n'avez pas les droits nécessaires pour accéder à cette page."
|
||||||
|
},
|
||||||
|
"back": "Retour à l'évaluation"
|
||||||
|
},
|
||||||
|
"mfa": {
|
||||||
|
"title": "Vérification en deux étapes",
|
||||||
|
"intro": "Saisissez le code à 6 chiffres affiché par votre application d'authentification.",
|
||||||
|
"recoveryIntro": "Saisissez l'un de vos codes de secours. Chaque code ne fonctionne qu'une fois.",
|
||||||
|
"codeLabel": "Code de vérification",
|
||||||
|
"recoveryLabel": "Code de secours",
|
||||||
|
"submit": "Valider",
|
||||||
|
"useRecovery": "Utiliser un code de secours",
|
||||||
|
"useApp": "Utiliser l'application d'authentification",
|
||||||
|
"back": "Retour à la connexion"
|
||||||
|
},
|
||||||
|
"register": {
|
||||||
|
"title": "Créer un compte",
|
||||||
|
"intro": "Réservé aux médecins généralistes. Votre demande sera validée par la cellule Environnement de la SSMG.",
|
||||||
|
"firstName": "Prénom",
|
||||||
|
"lastName": "Nom",
|
||||||
|
"inami": "Numéro INAMI (facultatif)",
|
||||||
|
"passwordRules": "12 caractères minimum. Évitez les mots de passe courants ou proches de votre nom.",
|
||||||
|
"confirm": "Confirmer le mot de passe",
|
||||||
|
"mismatch": "Les deux mots de passe ne correspondent pas.",
|
||||||
|
"terms": "J'accepte les conditions d'utilisation et la politique de confidentialité.",
|
||||||
|
"submit": "Créer mon compte",
|
||||||
|
"submitting": "Envoi…",
|
||||||
|
"haveAccount": "Déjà un compte ? Se connecter",
|
||||||
|
"fixErrors": "Corrigez les champs signalés.",
|
||||||
|
"throttled": "Trop de demandes depuis cette connexion. Réessayez plus tard.",
|
||||||
|
"error": "La demande n'a pas pu être envoyée. Réessayez dans un instant."
|
||||||
|
},
|
||||||
|
"registerStatus": {
|
||||||
|
"loading": "Vérification du lien…",
|
||||||
|
"sent": {
|
||||||
|
"title": "Vérifiez votre boîte mail",
|
||||||
|
"textTo": "Un lien de confirmation a été envoyé à {email}.",
|
||||||
|
"text": "Un lien de confirmation vient de vous être envoyé.",
|
||||||
|
"hint": "Le lien est valable 24 heures. Pensez à vérifier vos courriers indésirables."
|
||||||
|
},
|
||||||
|
"confirmed": {
|
||||||
|
"title": "Adresse confirmée",
|
||||||
|
"text": "Votre demande est en attente de validation par la cellule Environnement de la SSMG. Vous recevrez un e-mail dès qu'elle sera traitée."
|
||||||
|
},
|
||||||
|
"expired": {
|
||||||
|
"title": "Lien expiré",
|
||||||
|
"text": "Ce lien de confirmation n'est plus valable. Demandez un nouvel e-mail."
|
||||||
|
},
|
||||||
|
"invalid": {
|
||||||
|
"title": "Lien invalide",
|
||||||
|
"text": "Ce lien de confirmation n'est pas valide. Vérifiez que vous l'avez copié en entier."
|
||||||
|
},
|
||||||
|
"resend": "Renvoyer l'e-mail",
|
||||||
|
"resent": "Si une demande est en attente pour cette adresse, un nouvel e-mail vient d'être envoyé.",
|
||||||
|
"toLogin": "Aller à la connexion",
|
||||||
|
"restart": "Créer un compte"
|
||||||
|
},
|
||||||
|
"account": {
|
||||||
|
"title": "Mon compte",
|
||||||
|
"passwordTitle": "Changer le mot de passe",
|
||||||
|
"currentPassword": "Mot de passe actuel",
|
||||||
|
"newPassword": "Nouveau mot de passe",
|
||||||
|
"confirmPassword": "Confirmer le nouveau mot de passe",
|
||||||
|
"save": "Enregistrer",
|
||||||
|
"passwordSaved": "Mot de passe modifié. Un e-mail de confirmation vous a été envoyé.",
|
||||||
|
"cancel": "Annuler",
|
||||||
|
"error": "L'opération a échoué. Réessayez dans un instant.",
|
||||||
|
"mfa": {
|
||||||
|
"title": "Double authentification",
|
||||||
|
"on": "Activée",
|
||||||
|
"off": "Désactivée",
|
||||||
|
"explain": "Ajoutez une seconde étape de vérification à la connexion avec une application d'authentification. Elle protège l'accès aux données de vos patients.",
|
||||||
|
"enabledText": "Un code de votre application d'authentification est demandé à chaque connexion.",
|
||||||
|
"mandatory": "La double authentification est obligatoire pour votre compte : activez-la pour accéder à l'espace d'administration.",
|
||||||
|
"enable": "Activer la double authentification",
|
||||||
|
"setupTitle": "Activer la double authentification",
|
||||||
|
"step1": "1. Scannez le QR code",
|
||||||
|
"step1Text": "Avec une application d'authentification (Google Authenticator, Microsoft Authenticator, Authy, 1Password…).",
|
||||||
|
"qrAlt": "QR code à scanner avec l'application d'authentification",
|
||||||
|
"secret": "Ou saisissez la clé :",
|
||||||
|
"step2": "2. Saisissez le code",
|
||||||
|
"step2Text": "Entrez le code à 6 chiffres affiché dans l'application pour confirmer.",
|
||||||
|
"activate": "Activer",
|
||||||
|
"codesTitle": "Codes de secours",
|
||||||
|
"codesText": "Conservez ces {count} codes dans un endroit sûr. Chacun ne fonctionne qu'une seule fois et ne sera plus affiché.",
|
||||||
|
"codesWarning": "Enregistrez vos codes avant de continuer : ils permettent de vous connecter si vous perdez votre téléphone.",
|
||||||
|
"copy": "Copier",
|
||||||
|
"copied": "Copié",
|
||||||
|
"download": "Télécharger",
|
||||||
|
"saved": "J'ai enregistré mes codes de secours.",
|
||||||
|
"finish": "Terminer",
|
||||||
|
"enabledDone": "La double authentification est activée.",
|
||||||
|
"regenerate": "Régénérer les codes de secours",
|
||||||
|
"disable": "Désactiver",
|
||||||
|
"disabled": "La double authentification est désactivée.",
|
||||||
|
"codeOrRecovery": "Code de l'application ou code de secours"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"forgot": {
|
||||||
|
"title": "Mot de passe oublié",
|
||||||
|
"intro": "Saisissez l'adresse e-mail de votre compte. Si elle existe, nous vous enverrons un lien de réinitialisation valable 1 heure.",
|
||||||
|
"submit": "Envoyer le lien",
|
||||||
|
"submitting": "Envoi…",
|
||||||
|
"sentTitle": "Vérifiez votre boîte mail",
|
||||||
|
"sentText": "Si un compte existe pour {email}, un e-mail vient d'être envoyé. Le lien est valable 1 heure.",
|
||||||
|
"resend": "Renvoyer l'e-mail",
|
||||||
|
"resent": "Un nouvel e-mail a été demandé.",
|
||||||
|
"back": "Retour à la connexion",
|
||||||
|
"throttled": "Trop de demandes depuis cette connexion. Réessayez plus tard.",
|
||||||
|
"error": "La demande n'a pas pu être envoyée. Réessayez dans un instant."
|
||||||
|
},
|
||||||
|
"reset": {
|
||||||
|
"title": "Nouveau mot de passe",
|
||||||
|
"intro": "Choisissez un mot de passe d'au moins 12 caractères.",
|
||||||
|
"password": "Nouveau mot de passe",
|
||||||
|
"confirm": "Confirmer le mot de passe",
|
||||||
|
"submit": "Enregistrer le mot de passe",
|
||||||
|
"submitting": "Enregistrement…",
|
||||||
|
"checking": "Vérification du lien…",
|
||||||
|
"invalidTitle": "Lien invalide ou expiré",
|
||||||
|
"invalidText": "Ce lien de réinitialisation n'est plus valable. Demandez-en un nouveau.",
|
||||||
|
"newLink": "Demander un nouveau lien",
|
||||||
|
"done": "Votre mot de passe a été modifié. Connectez-vous avec le nouveau mot de passe.",
|
||||||
|
"error": "Le mot de passe n'a pas pu être enregistré. Réessayez dans un instant."
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import 'bootstrap/dist/css/bootstrap.min.css'
|
||||||
|
import 'bootstrap-icons/font/bootstrap-icons.min.css'
|
||||||
|
import 'maplibre-gl/dist/maplibre-gl.css'
|
||||||
|
import '@fontsource/roboto/300.css'
|
||||||
|
import '@fontsource/roboto/400.css'
|
||||||
|
import '@fontsource/roboto/500.css'
|
||||||
|
import '@fontsource/roboto/700.css'
|
||||||
|
import './styles/main.css'
|
||||||
|
|
||||||
|
import { createApp } from 'vue'
|
||||||
|
|
||||||
|
import App from './App.vue'
|
||||||
|
import i18n from './i18n'
|
||||||
|
import router from './router'
|
||||||
|
|
||||||
|
createApp(App).use(i18n).use(router).mount('#app')
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
|
||||||
|
|
||||||
|
import { useAuth } from '@/composables/useAuth'
|
||||||
|
|
||||||
|
declare module 'vue-router' {
|
||||||
|
interface RouteMeta {
|
||||||
|
/** Page réservée aux utilisateurs connectés. */
|
||||||
|
requiresAuth?: boolean
|
||||||
|
/** Page d'accès : redirige vers l'évaluation si l'utilisateur est déjà connecté. */
|
||||||
|
guestOnly?: boolean
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const routes: RouteRecordRaw[] = [
|
||||||
|
{
|
||||||
|
path: '/',
|
||||||
|
name: 'assessment',
|
||||||
|
component: () => import('@/views/AssessmentView.vue'),
|
||||||
|
meta: { requiresAuth: true },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/login',
|
||||||
|
name: 'login',
|
||||||
|
component: () => import('@/views/LoginView.vue'),
|
||||||
|
meta: { guestOnly: true },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/inscription',
|
||||||
|
name: 'register',
|
||||||
|
component: () => import('@/views/RegisterView.vue'),
|
||||||
|
meta: { guestOnly: true },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// Ouverte depuis l'e-mail de confirmation : accessible connecté ou non.
|
||||||
|
path: '/inscription/statut',
|
||||||
|
name: 'register-status',
|
||||||
|
component: () => import('@/views/RegisterStatusView.vue'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/mot-de-passe-oublie',
|
||||||
|
name: 'forgot-password',
|
||||||
|
component: () => import('@/views/ForgotPasswordView.vue'),
|
||||||
|
meta: { guestOnly: true },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// Ouverte depuis l'e-mail ; le jeton est retiré de l'URL dès l'arrivée sur la page.
|
||||||
|
path: '/reinitialisation/:jeton?',
|
||||||
|
name: 'reset-password',
|
||||||
|
component: () => import('@/views/ResetPasswordView.vue'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/compte',
|
||||||
|
name: 'account',
|
||||||
|
component: () => import('@/views/AccountView.vue'),
|
||||||
|
meta: { requiresAuth: true },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/403',
|
||||||
|
name: 'forbidden',
|
||||||
|
component: () => import('@/views/ErrorView.vue'),
|
||||||
|
props: { code: 403 },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/:pathMatch(.*)*',
|
||||||
|
name: 'not-found',
|
||||||
|
component: () => import('@/views/ErrorView.vue'),
|
||||||
|
props: { code: 404 },
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
export function createAppRouter() {
|
||||||
|
const router = createRouter({
|
||||||
|
history: createWebHistory(import.meta.env.BASE_URL),
|
||||||
|
routes,
|
||||||
|
scrollBehavior: (_to, _from, saved) => saved ?? { top: 0 },
|
||||||
|
})
|
||||||
|
|
||||||
|
router.beforeEach(async (to) => {
|
||||||
|
const { load } = useAuth()
|
||||||
|
const user = await load()
|
||||||
|
if (to.meta.requiresAuth && !user) {
|
||||||
|
return { name: 'login', query: to.fullPath === '/' ? {} : { next: to.fullPath } }
|
||||||
|
}
|
||||||
|
if (to.meta.guestOnly && user) {
|
||||||
|
return { name: 'assessment' }
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
return router
|
||||||
|
}
|
||||||
|
|
||||||
|
export default createAppRouter()
|
||||||
@@ -0,0 +1,215 @@
|
|||||||
|
/*
|
||||||
|
* Charte PRISM (maquettes Penpot, charte ssmg.be).
|
||||||
|
* Bootstrap 5 est utilisé en CSS seul ; ses variables sont surchargées ici.
|
||||||
|
*/
|
||||||
|
|
||||||
|
:root {
|
||||||
|
--prism-orange: #e85b25;
|
||||||
|
--prism-navy: #092933;
|
||||||
|
--prism-text: #464d5f;
|
||||||
|
--prism-muted: #6b7280;
|
||||||
|
--prism-border: #d9d4d0;
|
||||||
|
--prism-bg: #f6f4f2;
|
||||||
|
--prism-surface: #ffffff;
|
||||||
|
--prism-info-bg: #e6f6fd;
|
||||||
|
--prism-footer-link: #74c5da;
|
||||||
|
|
||||||
|
--prism-level-1: #3e9b4f;
|
||||||
|
--prism-level-2: #e0b400; /* jaune : absent des maquettes, à valider */
|
||||||
|
--prism-level-3: #f2994a;
|
||||||
|
--prism-level-4: #d64545;
|
||||||
|
--prism-level-none: #9aa0a6;
|
||||||
|
|
||||||
|
--bs-body-font-family: 'Roboto', system-ui, sans-serif;
|
||||||
|
--bs-body-color: var(--prism-text);
|
||||||
|
--bs-body-bg: var(--prism-bg);
|
||||||
|
--bs-heading-color: var(--prism-navy);
|
||||||
|
--bs-border-color: var(--prism-border);
|
||||||
|
--bs-link-color: var(--prism-orange);
|
||||||
|
--bs-link-color-rgb: 232, 91, 37;
|
||||||
|
--bs-link-hover-color: #c74a1b;
|
||||||
|
--bs-link-hover-color-rgb: 199, 74, 27;
|
||||||
|
--bs-primary: var(--prism-orange);
|
||||||
|
--bs-primary-rgb: 232, 91, 37;
|
||||||
|
--bs-focus-ring-color: rgba(232, 91, 37, 0.25);
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
h1,
|
||||||
|
h2,
|
||||||
|
h3 {
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Boutons --------------------------------------------------------------- */
|
||||||
|
|
||||||
|
.btn {
|
||||||
|
--bs-btn-font-weight: 500;
|
||||||
|
--bs-btn-border-radius: 6px;
|
||||||
|
--bs-btn-padding-y: 0.65rem;
|
||||||
|
--bs-btn-padding-x: 1.25rem;
|
||||||
|
--bs-btn-font-size: 0.9375rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary {
|
||||||
|
--bs-btn-bg: var(--prism-orange);
|
||||||
|
--bs-btn-border-color: var(--prism-orange);
|
||||||
|
--bs-btn-hover-bg: #c74a1b;
|
||||||
|
--bs-btn-hover-border-color: #c74a1b;
|
||||||
|
--bs-btn-active-bg: #b14218;
|
||||||
|
--bs-btn-active-border-color: #b14218;
|
||||||
|
--bs-btn-disabled-bg: var(--prism-orange);
|
||||||
|
--bs-btn-disabled-border-color: var(--prism-orange);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-outline-primary {
|
||||||
|
--bs-btn-color: var(--prism-orange);
|
||||||
|
--bs-btn-border-color: var(--prism-orange);
|
||||||
|
--bs-btn-hover-bg: var(--prism-orange);
|
||||||
|
--bs-btn-hover-border-color: var(--prism-orange);
|
||||||
|
--bs-btn-active-bg: #c74a1b;
|
||||||
|
--bs-btn-active-border-color: #c74a1b;
|
||||||
|
--bs-btn-bg: var(--prism-surface);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Champs ---------------------------------------------------------------- */
|
||||||
|
|
||||||
|
.form-label {
|
||||||
|
font-size: 0.8125rem;
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--prism-navy);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-control {
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 0.7rem 0.875rem;
|
||||||
|
font-size: 0.9375rem;
|
||||||
|
color: var(--prism-navy);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-control:focus {
|
||||||
|
border-color: var(--prism-orange);
|
||||||
|
box-shadow: 0 0 0 0.2rem var(--bs-focus-ring-color);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Surfaces -------------------------------------------------------------- */
|
||||||
|
|
||||||
|
.prism-card {
|
||||||
|
background: var(--prism-surface);
|
||||||
|
border: 1px solid var(--prism-border);
|
||||||
|
border-radius: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.prism-alert-info {
|
||||||
|
background: var(--prism-info-bg);
|
||||||
|
border-radius: 8px;
|
||||||
|
color: var(--prism-navy);
|
||||||
|
font-weight: 500;
|
||||||
|
padding: 0.75rem 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Niveaux --------------------------------------------------------------- */
|
||||||
|
|
||||||
|
.level-1 {
|
||||||
|
--level-color: var(--prism-level-1);
|
||||||
|
}
|
||||||
|
.level-2 {
|
||||||
|
--level-color: var(--prism-level-2);
|
||||||
|
}
|
||||||
|
.level-3 {
|
||||||
|
--level-color: var(--prism-level-3);
|
||||||
|
}
|
||||||
|
.level-4 {
|
||||||
|
--level-color: var(--prism-level-4);
|
||||||
|
}
|
||||||
|
.level-none {
|
||||||
|
--level-color: var(--prism-level-none);
|
||||||
|
}
|
||||||
|
|
||||||
|
.dot {
|
||||||
|
display: inline-block;
|
||||||
|
width: 10px;
|
||||||
|
height: 10px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--level-color);
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Pages d'accès (connexion, inscription…) ---------------------------------- */
|
||||||
|
|
||||||
|
.auth-page {
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 100px 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.auth-card {
|
||||||
|
width: 100%;
|
||||||
|
max-width: 460px;
|
||||||
|
padding: 40px 39px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.auth-card.wide {
|
||||||
|
max-width: 560px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.auth-card h1 {
|
||||||
|
font-size: 1.75rem;
|
||||||
|
margin-bottom: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.auth-card .intro {
|
||||||
|
margin-bottom: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.auth-links {
|
||||||
|
text-align: center;
|
||||||
|
margin-top: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.link-strong {
|
||||||
|
color: var(--prism-orange);
|
||||||
|
font-weight: 500;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.link-strong:hover {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-circle {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 72px;
|
||||||
|
height: 72px;
|
||||||
|
margin: 0 auto 1.5rem;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--prism-info-bg);
|
||||||
|
color: var(--prism-navy);
|
||||||
|
font-size: 1.25rem;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-circle.warning {
|
||||||
|
background: #fdf0e6;
|
||||||
|
color: var(--prism-level-3);
|
||||||
|
font-size: 1.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-text {
|
||||||
|
color: var(--prism-muted);
|
||||||
|
font-size: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 575.98px) {
|
||||||
|
.auth-page {
|
||||||
|
padding: 32px 16px;
|
||||||
|
}
|
||||||
|
.auth-card {
|
||||||
|
padding: 28px 20px;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, reactive, ref } from 'vue'
|
||||||
|
import { useI18n } from 'vue-i18n'
|
||||||
|
|
||||||
|
import { api, ApiError } from '@/api/client'
|
||||||
|
import AlertBanner from '@/components/AlertBanner.vue'
|
||||||
|
import MfaPanel from '@/components/MfaPanel.vue'
|
||||||
|
import { useAuth } from '@/composables/useAuth'
|
||||||
|
|
||||||
|
const { user } = useAuth()
|
||||||
|
const { t } = useI18n()
|
||||||
|
|
||||||
|
const initials = computed(() =>
|
||||||
|
`${user.value?.first_name[0] ?? ''}${user.value?.last_name[0] ?? ''}`.toUpperCase(),
|
||||||
|
)
|
||||||
|
|
||||||
|
const form = reactive({ current: '', next: '', confirm: '' })
|
||||||
|
const errors = ref<Record<string, string>>({})
|
||||||
|
const saved = ref(false)
|
||||||
|
const loading = ref(false)
|
||||||
|
const mismatch = computed(() => form.confirm !== '' && form.confirm !== form.next)
|
||||||
|
|
||||||
|
async function changePassword() {
|
||||||
|
errors.value = {}
|
||||||
|
saved.value = false
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
await api.changePassword(form.current, form.next)
|
||||||
|
Object.assign(form, { current: '', next: '', confirm: '' })
|
||||||
|
saved.value = true
|
||||||
|
} catch (e) {
|
||||||
|
errors.value =
|
||||||
|
e instanceof ApiError && e.status === 400
|
||||||
|
? e.fieldErrors()
|
||||||
|
: { new_password: t('account.error') }
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div v-if="user" class="account container-xxl">
|
||||||
|
<h1>{{ $t('account.title') }}</h1>
|
||||||
|
|
||||||
|
<section class="prism-card profile">
|
||||||
|
<span class="avatar" aria-hidden="true">{{ initials }}</span>
|
||||||
|
<div>
|
||||||
|
<p class="name">{{ $t('nav.doctor', { name: `${user.first_name} ${user.last_name}` }) }}</p>
|
||||||
|
<p class="meta">
|
||||||
|
{{ user.email
|
||||||
|
}}<template v-if="user.roles.length"> · {{ user.roles.join(', ') }}</template>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div class="row g-4">
|
||||||
|
<div class="col-lg-6">
|
||||||
|
<section class="prism-card panel" aria-labelledby="password-heading">
|
||||||
|
<h2 id="password-heading" class="card-title">{{ $t('account.passwordTitle') }}</h2>
|
||||||
|
<AlertBanner v-if="saved" variant="info" class="mb-3">
|
||||||
|
{{ $t('account.passwordSaved') }}
|
||||||
|
</AlertBanner>
|
||||||
|
<form novalidate @submit.prevent="changePassword">
|
||||||
|
<div class="mb-3">
|
||||||
|
<label for="current" class="form-label">{{ $t('account.currentPassword') }}</label>
|
||||||
|
<input
|
||||||
|
id="current"
|
||||||
|
v-model="form.current"
|
||||||
|
type="password"
|
||||||
|
class="form-control"
|
||||||
|
:class="{ 'is-invalid': errors.current_password }"
|
||||||
|
autocomplete="current-password"
|
||||||
|
/>
|
||||||
|
<div class="invalid-feedback">{{ errors.current_password }}</div>
|
||||||
|
</div>
|
||||||
|
<div class="mb-3">
|
||||||
|
<label for="next" class="form-label">{{ $t('account.newPassword') }}</label>
|
||||||
|
<input
|
||||||
|
id="next"
|
||||||
|
v-model="form.next"
|
||||||
|
type="password"
|
||||||
|
class="form-control"
|
||||||
|
:class="{ 'is-invalid': errors.new_password }"
|
||||||
|
autocomplete="new-password"
|
||||||
|
aria-describedby="new-password-rules"
|
||||||
|
/>
|
||||||
|
<div class="invalid-feedback">{{ errors.new_password }}</div>
|
||||||
|
<div id="new-password-rules" class="form-text">
|
||||||
|
{{ $t('register.passwordRules') }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="mb-4">
|
||||||
|
<label for="confirm" class="form-label">{{ $t('account.confirmPassword') }}</label>
|
||||||
|
<input
|
||||||
|
id="confirm"
|
||||||
|
v-model="form.confirm"
|
||||||
|
type="password"
|
||||||
|
class="form-control"
|
||||||
|
:class="{ 'is-invalid': mismatch }"
|
||||||
|
autocomplete="new-password"
|
||||||
|
/>
|
||||||
|
<div class="invalid-feedback">{{ $t('register.mismatch') }}</div>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
class="btn btn-primary save"
|
||||||
|
:disabled="
|
||||||
|
loading || !form.current || form.next.length < 12 || form.next !== form.confirm
|
||||||
|
"
|
||||||
|
>
|
||||||
|
{{ $t('account.save') }}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
<div class="col-lg-6">
|
||||||
|
<MfaPanel />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.account {
|
||||||
|
max-width: 1440px;
|
||||||
|
padding: 40px 48px;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 767.98px) {
|
||||||
|
.account {
|
||||||
|
padding: 24px 16px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
font-size: 1.875rem;
|
||||||
|
margin-bottom: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.profile {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 20px;
|
||||||
|
padding: 20px 28px;
|
||||||
|
margin-bottom: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.avatar {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 56px;
|
||||||
|
height: 56px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--prism-navy);
|
||||||
|
color: #fff;
|
||||||
|
font-size: 1.125rem;
|
||||||
|
font-weight: 700;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.name {
|
||||||
|
margin: 0;
|
||||||
|
color: var(--prism-navy);
|
||||||
|
font-size: 1.125rem;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
.meta {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.panel {
|
||||||
|
padding: 24px 28px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card-title {
|
||||||
|
font-size: 1.25rem;
|
||||||
|
margin-bottom: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.save {
|
||||||
|
min-width: 160px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, ref } from 'vue'
|
||||||
|
import { useRouter } from 'vue-router'
|
||||||
|
|
||||||
|
import { api, ApiError } from '@/api/client'
|
||||||
|
import type { Assessment } from '@/api/types'
|
||||||
|
import AddressForm from '@/components/AddressForm.vue'
|
||||||
|
import AlertBanner from '@/components/AlertBanner.vue'
|
||||||
|
import FactorCard from '@/components/FactorCard.vue'
|
||||||
|
import ResultMap from '@/components/ResultMap.vue'
|
||||||
|
import { useAuth } from '@/composables/useAuth'
|
||||||
|
|
||||||
|
const router = useRouter()
|
||||||
|
const { logout } = useAuth()
|
||||||
|
|
||||||
|
// L'adresse ne quitte pas la mémoire du composant : ni URL, ni stockage local.
|
||||||
|
const address = ref('')
|
||||||
|
const result = ref<Assessment | null>(null)
|
||||||
|
const errorKey = ref('')
|
||||||
|
const loading = ref(false)
|
||||||
|
|
||||||
|
const KNOWN_ERRORS = ['address_not_found', 'out_of_coverage', 'geocoding_unavailable']
|
||||||
|
|
||||||
|
async function analyse(value: string) {
|
||||||
|
address.value = value
|
||||||
|
errorKey.value = ''
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
result.value = await api.assess(value)
|
||||||
|
} catch (e) {
|
||||||
|
result.value = null
|
||||||
|
if (e instanceof ApiError && e.status === 403) {
|
||||||
|
// Session expirée.
|
||||||
|
await logout()
|
||||||
|
await router.push({ name: 'login' })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (e instanceof ApiError && e.status === 429) {
|
||||||
|
errorKey.value = 'assessment.errors.throttled'
|
||||||
|
} else if (e instanceof ApiError && e.code && KNOWN_ERRORS.includes(e.code)) {
|
||||||
|
errorKey.value = `assessment.errors.${e.code}`
|
||||||
|
} else {
|
||||||
|
errorKey.value = 'assessment.errors.generic'
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const location = computed(() => result.value?.location ?? null)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="assessment container-xxl">
|
||||||
|
<AddressForm :loading="loading" @submit="analyse" />
|
||||||
|
|
||||||
|
<AlertBanner v-if="errorKey" variant="error">{{ $t(errorKey) }}</AlertBanner>
|
||||||
|
<AlertBanner v-else-if="result" variant="info">
|
||||||
|
{{
|
||||||
|
$t('assessment.recognized', {
|
||||||
|
address,
|
||||||
|
region: $t(`assessment.regions.${result.location.region}`),
|
||||||
|
})
|
||||||
|
}}
|
||||||
|
</AlertBanner>
|
||||||
|
|
||||||
|
<div class="row g-4">
|
||||||
|
<div :class="result ? 'col-lg-5' : 'col-12'">
|
||||||
|
<ResultMap :location="location" />
|
||||||
|
</div>
|
||||||
|
<div v-if="result" class="col-lg-7 d-flex flex-column gap-4" aria-live="polite">
|
||||||
|
<FactorCard
|
||||||
|
v-for="factor in result.factors"
|
||||||
|
:key="factor.code"
|
||||||
|
:factor="factor"
|
||||||
|
@retry="analyse(address)"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.assessment {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 24px;
|
||||||
|
max-width: 1440px;
|
||||||
|
padding: 32px 48px 40px;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 767.98px) {
|
||||||
|
.assessment {
|
||||||
|
padding: 16px 16px 32px;
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
defineProps<{ code: 403 | 404 }>()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="error-page">
|
||||||
|
<section class="error-card prism-card text-center" aria-labelledby="error-title">
|
||||||
|
<p class="error-code" aria-hidden="true">{{ code }}</p>
|
||||||
|
<h1 id="error-title">{{ $t(`errors.${code}.title`) }}</h1>
|
||||||
|
<p>{{ $t(`errors.${code}.text`) }}</p>
|
||||||
|
<RouterLink to="/" class="btn btn-primary back">{{ $t('errors.back') }}</RouterLink>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.error-page {
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 120px 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 575.98px) {
|
||||||
|
.error-page {
|
||||||
|
padding: 48px 16px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-card {
|
||||||
|
width: 100%;
|
||||||
|
max-width: 560px;
|
||||||
|
padding: 48px 32px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-code {
|
||||||
|
color: var(--prism-orange);
|
||||||
|
font-size: 4.5rem;
|
||||||
|
font-weight: 700;
|
||||||
|
line-height: 1;
|
||||||
|
margin-bottom: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
font-size: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.back {
|
||||||
|
min-width: 240px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ref } from 'vue'
|
||||||
|
import { useI18n } from 'vue-i18n'
|
||||||
|
|
||||||
|
import { api, ApiError } from '@/api/client'
|
||||||
|
import AlertBanner from '@/components/AlertBanner.vue'
|
||||||
|
|
||||||
|
const { t } = useI18n()
|
||||||
|
|
||||||
|
const email = ref('')
|
||||||
|
const sent = ref(false)
|
||||||
|
const resent = ref(false)
|
||||||
|
const error = ref('')
|
||||||
|
const loading = ref(false)
|
||||||
|
|
||||||
|
async function send() {
|
||||||
|
error.value = ''
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
await api.requestPasswordReset(email.value)
|
||||||
|
resent.value = sent.value
|
||||||
|
sent.value = true
|
||||||
|
} catch (e) {
|
||||||
|
error.value =
|
||||||
|
e instanceof ApiError && e.status === 429
|
||||||
|
? t('forgot.throttled')
|
||||||
|
: e instanceof ApiError && e.status === 400
|
||||||
|
? (e.fieldErrors().email ?? t('forgot.error'))
|
||||||
|
: t('forgot.error')
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="auth-page">
|
||||||
|
<!-- Maquette 9 -->
|
||||||
|
<section v-if="!sent" class="auth-card wide prism-card" aria-labelledby="forgot-title">
|
||||||
|
<h1 id="forgot-title">{{ $t('forgot.title') }}</h1>
|
||||||
|
<p class="intro">{{ $t('forgot.intro') }}</p>
|
||||||
|
|
||||||
|
<AlertBanner v-if="error" variant="error" class="mb-3">{{ error }}</AlertBanner>
|
||||||
|
|
||||||
|
<form novalidate @submit.prevent="send">
|
||||||
|
<div class="mb-3">
|
||||||
|
<label for="email" class="form-label">{{ $t('login.email') }}</label>
|
||||||
|
<input
|
||||||
|
id="email"
|
||||||
|
v-model.trim="email"
|
||||||
|
type="email"
|
||||||
|
class="form-control"
|
||||||
|
autocomplete="username"
|
||||||
|
required
|
||||||
|
:placeholder="$t('login.emailPlaceholder')"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<button type="submit" class="btn btn-primary w-100" :disabled="loading || !email">
|
||||||
|
{{ loading ? $t('forgot.submitting') : $t('forgot.submit') }}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<p class="auth-links mb-0">
|
||||||
|
<RouterLink :to="{ name: 'login' }" class="link-strong">{{ $t('forgot.back') }}</RouterLink>
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- Maquette 10 -->
|
||||||
|
<section
|
||||||
|
v-else
|
||||||
|
class="auth-card wide prism-card text-center"
|
||||||
|
aria-labelledby="sent-title"
|
||||||
|
aria-live="polite"
|
||||||
|
>
|
||||||
|
<div class="icon-circle" aria-hidden="true">@</div>
|
||||||
|
<h1 id="sent-title">{{ $t('forgot.sentTitle') }}</h1>
|
||||||
|
<p>{{ $t('forgot.sentText', { email }) }}</p>
|
||||||
|
<AlertBanner v-if="error" variant="error" class="mb-3 text-start">{{ error }}</AlertBanner>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="btn btn-outline-primary w-100"
|
||||||
|
:disabled="loading || resent"
|
||||||
|
@click="send"
|
||||||
|
>
|
||||||
|
{{ $t('forgot.resend') }}
|
||||||
|
</button>
|
||||||
|
<p v-if="resent" class="text-success mt-2 mb-0" role="status">{{ $t('forgot.resent') }}</p>
|
||||||
|
<p class="auth-links mb-0">
|
||||||
|
<RouterLink :to="{ name: 'login' }" class="link-strong">{{ $t('forgot.back') }}</RouterLink>
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,192 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ref } from 'vue'
|
||||||
|
import { useI18n } from 'vue-i18n'
|
||||||
|
import { useRoute, useRouter } from 'vue-router'
|
||||||
|
|
||||||
|
import { ApiError } from '@/api/client'
|
||||||
|
import AlertBanner from '@/components/AlertBanner.vue'
|
||||||
|
import CodeInput from '@/components/CodeInput.vue'
|
||||||
|
import { useAuth } from '@/composables/useAuth'
|
||||||
|
|
||||||
|
const { login, verifyMfa } = useAuth()
|
||||||
|
const router = useRouter()
|
||||||
|
const route = useRoute()
|
||||||
|
const { t } = useI18n()
|
||||||
|
|
||||||
|
const step = ref<'password' | 'code'>('password')
|
||||||
|
const useRecovery = ref(false)
|
||||||
|
const email = ref('')
|
||||||
|
const password = ref('')
|
||||||
|
const code = ref('')
|
||||||
|
const error = ref('')
|
||||||
|
const loading = ref(false)
|
||||||
|
// Message transmis par la page de réinitialisation (état de navigation, pas l'URL).
|
||||||
|
const notice = ref<string>(history.state?.notice === 'password-reset' ? t('reset.done') : '')
|
||||||
|
const codeInput = ref<InstanceType<typeof CodeInput>>()
|
||||||
|
|
||||||
|
function message(e: unknown): string {
|
||||||
|
if (e instanceof ApiError && e.status === 429) return t('login.throttled')
|
||||||
|
if (e instanceof ApiError && e.status === 400) return e.message
|
||||||
|
return t('login.error')
|
||||||
|
}
|
||||||
|
|
||||||
|
async function done() {
|
||||||
|
const next = route.query.next
|
||||||
|
await router.push(
|
||||||
|
typeof next === 'string' && next.startsWith('/') && !next.startsWith('//')
|
||||||
|
? next
|
||||||
|
: { name: 'assessment' },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submitPassword() {
|
||||||
|
error.value = ''
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
if (await login(email.value, password.value)) {
|
||||||
|
password.value = ''
|
||||||
|
step.value = 'code'
|
||||||
|
} else {
|
||||||
|
await done()
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
error.value = message(e)
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submitCode() {
|
||||||
|
if (!code.value) return
|
||||||
|
error.value = ''
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
await verifyMfa(code.value)
|
||||||
|
await done()
|
||||||
|
} catch (e) {
|
||||||
|
error.value = message(e)
|
||||||
|
if (e instanceof ApiError && e.code === 'mfa_expired') backToPassword()
|
||||||
|
else if (!useRecovery.value) codeInput.value?.clear()
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function backToPassword() {
|
||||||
|
step.value = 'password'
|
||||||
|
code.value = ''
|
||||||
|
useRecovery.value = false
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleRecovery() {
|
||||||
|
useRecovery.value = !useRecovery.value
|
||||||
|
code.value = ''
|
||||||
|
error.value = ''
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="auth-page">
|
||||||
|
<section v-if="step === 'password'" class="auth-card prism-card" aria-labelledby="login-title">
|
||||||
|
<h1 id="login-title">{{ $t('login.title') }}</h1>
|
||||||
|
<p class="intro">{{ $t('login.intro') }}</p>
|
||||||
|
|
||||||
|
<AlertBanner v-if="error" variant="error" class="mb-3">{{ error }}</AlertBanner>
|
||||||
|
<AlertBanner v-else-if="notice" variant="info" class="mb-3">{{ notice }}</AlertBanner>
|
||||||
|
|
||||||
|
<form novalidate @submit.prevent="submitPassword">
|
||||||
|
<div class="mb-3">
|
||||||
|
<label for="email" class="form-label">{{ $t('login.email') }}</label>
|
||||||
|
<input
|
||||||
|
id="email"
|
||||||
|
v-model="email"
|
||||||
|
type="email"
|
||||||
|
class="form-control"
|
||||||
|
autocomplete="username"
|
||||||
|
required
|
||||||
|
:placeholder="$t('login.emailPlaceholder')"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div class="mb-4">
|
||||||
|
<label for="password" class="form-label">{{ $t('login.password') }}</label>
|
||||||
|
<input
|
||||||
|
id="password"
|
||||||
|
v-model="password"
|
||||||
|
type="password"
|
||||||
|
class="form-control"
|
||||||
|
autocomplete="current-password"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
class="btn btn-primary w-100"
|
||||||
|
:disabled="loading || !email || !password"
|
||||||
|
>
|
||||||
|
{{ loading ? $t('login.submitting') : $t('login.submit') }}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<p class="auth-links mb-0">
|
||||||
|
<RouterLink :to="{ name: 'forgot-password' }" class="link-strong">
|
||||||
|
{{ $t('login.forgot') }}
|
||||||
|
</RouterLink>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<hr class="my-4" />
|
||||||
|
<p class="text-center mb-3">{{ $t('login.noAccount') }}</p>
|
||||||
|
<RouterLink :to="{ name: 'register' }" class="btn btn-outline-primary w-100">
|
||||||
|
{{ $t('login.createAccount') }}
|
||||||
|
</RouterLink>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section v-else class="auth-card wide prism-card text-center" aria-labelledby="mfa-title">
|
||||||
|
<div class="icon-circle" aria-hidden="true">2FA</div>
|
||||||
|
<h1 id="mfa-title">{{ $t('mfa.title') }}</h1>
|
||||||
|
<p class="intro">
|
||||||
|
{{ useRecovery ? $t('mfa.recoveryIntro') : $t('mfa.intro') }}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<AlertBanner v-if="error" variant="error" class="mb-3 text-start">{{ error }}</AlertBanner>
|
||||||
|
|
||||||
|
<form novalidate @submit.prevent="submitCode">
|
||||||
|
<div v-if="useRecovery" class="mb-4 text-start">
|
||||||
|
<label for="recovery" class="form-label">{{ $t('mfa.recoveryLabel') }}</label>
|
||||||
|
<input
|
||||||
|
id="recovery"
|
||||||
|
v-model="code"
|
||||||
|
type="text"
|
||||||
|
class="form-control font-monospace"
|
||||||
|
autocomplete="off"
|
||||||
|
placeholder="ABCD-EFGH"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<CodeInput
|
||||||
|
v-else
|
||||||
|
ref="codeInput"
|
||||||
|
v-model="code"
|
||||||
|
class="justify-content-center mb-4"
|
||||||
|
:label="$t('mfa.codeLabel')"
|
||||||
|
autofocus
|
||||||
|
@complete="submitCode"
|
||||||
|
/>
|
||||||
|
<button type="submit" class="btn btn-primary w-100" :disabled="loading || !code">
|
||||||
|
{{ $t('mfa.submit') }}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<p class="auth-links mb-2">
|
||||||
|
<button type="button" class="btn btn-link link-strong p-0" @click="toggleRecovery">
|
||||||
|
{{ useRecovery ? $t('mfa.useApp') : $t('mfa.useRecovery') }}
|
||||||
|
</button>
|
||||||
|
</p>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="btn btn-link text-reset text-decoration-none p-0"
|
||||||
|
@click="backToPassword"
|
||||||
|
>
|
||||||
|
{{ $t('mfa.back') }}
|
||||||
|
</button>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { onMounted, ref } from 'vue'
|
||||||
|
import { useRoute, useRouter } from 'vue-router'
|
||||||
|
|
||||||
|
import { api, ApiError } from '@/api/client'
|
||||||
|
|
||||||
|
type State = 'loading' | 'sent' | 'confirmed' | 'expired' | 'invalid' | 'used'
|
||||||
|
|
||||||
|
const route = useRoute()
|
||||||
|
const router = useRouter()
|
||||||
|
|
||||||
|
const state = ref<State>('loading')
|
||||||
|
const email = ref<string>((history.state?.email as string | undefined) ?? '')
|
||||||
|
const token = ref('')
|
||||||
|
const resent = ref(false)
|
||||||
|
const resending = ref(false)
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
const jeton = route.query.jeton
|
||||||
|
if (typeof jeton !== 'string' || !jeton) {
|
||||||
|
state.value = 'sent'
|
||||||
|
return
|
||||||
|
}
|
||||||
|
token.value = jeton
|
||||||
|
// Retire le jeton de la barre d'adresse et de l'historique.
|
||||||
|
await router.replace({ name: 'register-status' })
|
||||||
|
try {
|
||||||
|
await api.verifyEmail(jeton)
|
||||||
|
state.value = 'confirmed'
|
||||||
|
} catch (e) {
|
||||||
|
const code = e instanceof ApiError ? e.code : undefined
|
||||||
|
state.value = code === 'expired_token' ? 'expired' : code === 'used_token' ? 'used' : 'invalid'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
async function resend() {
|
||||||
|
resending.value = true
|
||||||
|
try {
|
||||||
|
await api.resendVerification(token.value ? { token: token.value } : { email: email.value })
|
||||||
|
resent.value = true
|
||||||
|
} finally {
|
||||||
|
resending.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const ICONS: Record<State, string> = {
|
||||||
|
loading: 'bi-hourglass-split',
|
||||||
|
sent: 'bi-envelope',
|
||||||
|
confirmed: 'bi-check-lg',
|
||||||
|
expired: 'bi-clock-history',
|
||||||
|
invalid: 'bi-x-lg',
|
||||||
|
used: 'bi-check-lg',
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="auth-page">
|
||||||
|
<section
|
||||||
|
class="auth-card wide prism-card text-center"
|
||||||
|
aria-labelledby="status-title"
|
||||||
|
aria-live="polite"
|
||||||
|
>
|
||||||
|
<div class="icon-circle" aria-hidden="true"><i class="bi" :class="ICONS[state]"></i></div>
|
||||||
|
|
||||||
|
<template v-if="state === 'loading'">
|
||||||
|
<h1 id="status-title">{{ $t('registerStatus.loading') }}</h1>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<template v-else-if="state === 'sent'">
|
||||||
|
<h1 id="status-title">{{ $t('registerStatus.sent.title') }}</h1>
|
||||||
|
<p v-if="email">{{ $t('registerStatus.sent.textTo', { email }) }}</p>
|
||||||
|
<p v-else>{{ $t('registerStatus.sent.text') }}</p>
|
||||||
|
<p class="form-text">{{ $t('registerStatus.sent.hint') }}</p>
|
||||||
|
<button
|
||||||
|
v-if="email"
|
||||||
|
type="button"
|
||||||
|
class="btn btn-outline-primary"
|
||||||
|
:disabled="resending || resent"
|
||||||
|
@click="resend"
|
||||||
|
>
|
||||||
|
{{ $t('registerStatus.resend') }}
|
||||||
|
</button>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<template v-else-if="state === 'confirmed' || state === 'used'">
|
||||||
|
<h1 id="status-title">{{ $t('registerStatus.confirmed.title') }}</h1>
|
||||||
|
<p>{{ $t('registerStatus.confirmed.text') }}</p>
|
||||||
|
<RouterLink :to="{ name: 'login' }" class="btn btn-primary">
|
||||||
|
{{ $t('registerStatus.toLogin') }}
|
||||||
|
</RouterLink>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<template v-else-if="state === 'expired'">
|
||||||
|
<h1 id="status-title">{{ $t('registerStatus.expired.title') }}</h1>
|
||||||
|
<p>{{ $t('registerStatus.expired.text') }}</p>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="btn btn-primary"
|
||||||
|
:disabled="resending || resent"
|
||||||
|
@click="resend"
|
||||||
|
>
|
||||||
|
{{ $t('registerStatus.resend') }}
|
||||||
|
</button>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<template v-else>
|
||||||
|
<h1 id="status-title">{{ $t('registerStatus.invalid.title') }}</h1>
|
||||||
|
<p>{{ $t('registerStatus.invalid.text') }}</p>
|
||||||
|
<RouterLink :to="{ name: 'register' }" class="btn btn-outline-primary">
|
||||||
|
{{ $t('registerStatus.restart') }}
|
||||||
|
</RouterLink>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<p v-if="resent" class="text-success mt-3 mb-0" role="status">
|
||||||
|
{{ $t('registerStatus.resent') }}
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,196 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, reactive, ref } from 'vue'
|
||||||
|
import { useI18n } from 'vue-i18n'
|
||||||
|
import { useRouter } from 'vue-router'
|
||||||
|
|
||||||
|
import { api, ApiError } from '@/api/client'
|
||||||
|
import AlertBanner from '@/components/AlertBanner.vue'
|
||||||
|
|
||||||
|
const router = useRouter()
|
||||||
|
const { t } = useI18n()
|
||||||
|
|
||||||
|
const form = reactive({
|
||||||
|
first_name: '',
|
||||||
|
last_name: '',
|
||||||
|
email: '',
|
||||||
|
inami_number: '',
|
||||||
|
password: '',
|
||||||
|
confirm: '',
|
||||||
|
accept_terms: false,
|
||||||
|
})
|
||||||
|
const errors = ref<Record<string, string>>({})
|
||||||
|
const error = ref('')
|
||||||
|
const loading = ref(false)
|
||||||
|
|
||||||
|
const mismatch = computed(() => form.confirm !== '' && form.confirm !== form.password)
|
||||||
|
const canSubmit = computed(
|
||||||
|
() =>
|
||||||
|
form.first_name &&
|
||||||
|
form.last_name &&
|
||||||
|
form.email &&
|
||||||
|
form.password.length >= 12 &&
|
||||||
|
form.password === form.confirm &&
|
||||||
|
form.accept_terms,
|
||||||
|
)
|
||||||
|
|
||||||
|
async function submit() {
|
||||||
|
errors.value = {}
|
||||||
|
error.value = ''
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
await api.register({
|
||||||
|
first_name: form.first_name,
|
||||||
|
last_name: form.last_name,
|
||||||
|
email: form.email,
|
||||||
|
inami_number: form.inami_number,
|
||||||
|
password: form.password,
|
||||||
|
accept_terms: form.accept_terms,
|
||||||
|
})
|
||||||
|
// L'adresse du médecin passe par l'état de navigation, pas par l'URL.
|
||||||
|
await router.push({ name: 'register-status', state: { email: form.email } })
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof ApiError && e.status === 400) {
|
||||||
|
errors.value = e.fieldErrors()
|
||||||
|
error.value = errors.value.non_field_errors ?? t('register.fixErrors')
|
||||||
|
} else if (e instanceof ApiError && e.status === 429) {
|
||||||
|
error.value = t('register.throttled')
|
||||||
|
} else {
|
||||||
|
error.value = t('register.error')
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="auth-page register-page">
|
||||||
|
<section class="auth-card wide prism-card" aria-labelledby="register-title">
|
||||||
|
<h1 id="register-title">{{ $t('register.title') }}</h1>
|
||||||
|
<p class="intro">{{ $t('register.intro') }}</p>
|
||||||
|
|
||||||
|
<AlertBanner v-if="error" variant="error" class="mb-3">{{ error }}</AlertBanner>
|
||||||
|
|
||||||
|
<form novalidate @submit.prevent="submit">
|
||||||
|
<div class="row g-3 mb-3">
|
||||||
|
<div class="col-sm-6">
|
||||||
|
<label for="first_name" class="form-label">{{ $t('register.firstName') }}</label>
|
||||||
|
<input
|
||||||
|
id="first_name"
|
||||||
|
v-model.trim="form.first_name"
|
||||||
|
class="form-control"
|
||||||
|
:class="{ 'is-invalid': errors.first_name }"
|
||||||
|
autocomplete="given-name"
|
||||||
|
placeholder="Jean"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<div class="invalid-feedback">{{ errors.first_name }}</div>
|
||||||
|
</div>
|
||||||
|
<div class="col-sm-6">
|
||||||
|
<label for="last_name" class="form-label">{{ $t('register.lastName') }}</label>
|
||||||
|
<input
|
||||||
|
id="last_name"
|
||||||
|
v-model.trim="form.last_name"
|
||||||
|
class="form-control"
|
||||||
|
:class="{ 'is-invalid': errors.last_name }"
|
||||||
|
autocomplete="family-name"
|
||||||
|
placeholder="Dupont"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<div class="invalid-feedback">{{ errors.last_name }}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mb-3">
|
||||||
|
<label for="email" class="form-label">{{ $t('login.email') }}</label>
|
||||||
|
<input
|
||||||
|
id="email"
|
||||||
|
v-model.trim="form.email"
|
||||||
|
type="email"
|
||||||
|
class="form-control"
|
||||||
|
:class="{ 'is-invalid': errors.email }"
|
||||||
|
autocomplete="email"
|
||||||
|
:placeholder="$t('login.emailPlaceholder')"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<div class="invalid-feedback">{{ errors.email }}</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mb-3">
|
||||||
|
<label for="inami" class="form-label">{{ $t('register.inami') }}</label>
|
||||||
|
<input
|
||||||
|
id="inami"
|
||||||
|
v-model.trim="form.inami_number"
|
||||||
|
class="form-control"
|
||||||
|
:class="{ 'is-invalid': errors.inami_number }"
|
||||||
|
placeholder="1-23456-78-901"
|
||||||
|
/>
|
||||||
|
<div class="invalid-feedback">{{ errors.inami_number }}</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mb-3">
|
||||||
|
<label for="password" class="form-label">{{ $t('login.password') }}</label>
|
||||||
|
<input
|
||||||
|
id="password"
|
||||||
|
v-model="form.password"
|
||||||
|
type="password"
|
||||||
|
class="form-control"
|
||||||
|
:class="{ 'is-invalid': errors.password }"
|
||||||
|
autocomplete="new-password"
|
||||||
|
aria-describedby="password-rules"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<div class="invalid-feedback">{{ errors.password }}</div>
|
||||||
|
<div id="password-rules" class="form-text">{{ $t('register.passwordRules') }}</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mb-3">
|
||||||
|
<label for="confirm" class="form-label">{{ $t('register.confirm') }}</label>
|
||||||
|
<input
|
||||||
|
id="confirm"
|
||||||
|
v-model="form.confirm"
|
||||||
|
type="password"
|
||||||
|
class="form-control"
|
||||||
|
:class="{ 'is-invalid': mismatch }"
|
||||||
|
autocomplete="new-password"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<div class="invalid-feedback">{{ $t('register.mismatch') }}</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-check mb-4">
|
||||||
|
<input
|
||||||
|
id="terms"
|
||||||
|
v-model="form.accept_terms"
|
||||||
|
class="form-check-input"
|
||||||
|
:class="{ 'is-invalid': errors.accept_terms }"
|
||||||
|
type="checkbox"
|
||||||
|
/>
|
||||||
|
<label class="form-check-label" for="terms">{{ $t('register.terms') }}</label>
|
||||||
|
<div class="invalid-feedback">{{ errors.accept_terms }}</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button type="submit" class="btn btn-primary w-100" :disabled="loading || !canSubmit">
|
||||||
|
{{ loading ? $t('register.submitting') : $t('register.submit') }}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<p class="auth-links mb-0">
|
||||||
|
<RouterLink :to="{ name: 'login' }" class="link-strong">
|
||||||
|
{{ $t('register.haveAccount') }}
|
||||||
|
</RouterLink>
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.register-page {
|
||||||
|
padding-top: 32px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-check-input:checked {
|
||||||
|
background-color: var(--prism-orange);
|
||||||
|
border-color: var(--prism-orange);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onMounted, ref } from 'vue'
|
||||||
|
import { useI18n } from 'vue-i18n'
|
||||||
|
import { useRoute, useRouter } from 'vue-router'
|
||||||
|
|
||||||
|
import { api, ApiError } from '@/api/client'
|
||||||
|
import AlertBanner from '@/components/AlertBanner.vue'
|
||||||
|
|
||||||
|
const route = useRoute()
|
||||||
|
const router = useRouter()
|
||||||
|
const { t } = useI18n()
|
||||||
|
|
||||||
|
// Le jeton reste en mémoire : il est retiré de la barre d'adresse et de l'historique.
|
||||||
|
const token = ref('')
|
||||||
|
const state = ref<'checking' | 'form' | 'invalid'>('checking')
|
||||||
|
const password = ref('')
|
||||||
|
const confirm = ref('')
|
||||||
|
const errors = ref<Record<string, string>>({})
|
||||||
|
const error = ref('')
|
||||||
|
const loading = ref(false)
|
||||||
|
|
||||||
|
const mismatch = computed(() => confirm.value !== '' && confirm.value !== password.value)
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
const jeton = route.params.jeton
|
||||||
|
if (typeof jeton !== 'string' || !jeton) {
|
||||||
|
state.value = 'invalid'
|
||||||
|
return
|
||||||
|
}
|
||||||
|
token.value = jeton
|
||||||
|
await router.replace({ name: 'reset-password' })
|
||||||
|
try {
|
||||||
|
await api.validateResetToken(jeton)
|
||||||
|
state.value = 'form'
|
||||||
|
} catch {
|
||||||
|
state.value = 'invalid'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
async function submit() {
|
||||||
|
errors.value = {}
|
||||||
|
error.value = ''
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
await api.resetPassword(token.value, password.value)
|
||||||
|
await router.push({ name: 'login', state: { notice: 'password-reset' } })
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof ApiError && e.code === 'invalid_token') {
|
||||||
|
state.value = 'invalid'
|
||||||
|
} else if (e instanceof ApiError && e.status === 400) {
|
||||||
|
errors.value = e.fieldErrors()
|
||||||
|
} else {
|
||||||
|
error.value = t('reset.error')
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="auth-page">
|
||||||
|
<section
|
||||||
|
v-if="state === 'checking'"
|
||||||
|
class="auth-card wide prism-card text-center"
|
||||||
|
aria-live="polite"
|
||||||
|
>
|
||||||
|
<p class="mb-0">{{ $t('reset.checking') }}</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- Maquette 11 -->
|
||||||
|
<section
|
||||||
|
v-else-if="state === 'form'"
|
||||||
|
class="auth-card wide prism-card"
|
||||||
|
aria-labelledby="reset-title"
|
||||||
|
>
|
||||||
|
<h1 id="reset-title">{{ $t('reset.title') }}</h1>
|
||||||
|
<p class="intro">{{ $t('reset.intro') }}</p>
|
||||||
|
|
||||||
|
<AlertBanner v-if="error" variant="error" class="mb-3">{{ error }}</AlertBanner>
|
||||||
|
|
||||||
|
<form novalidate @submit.prevent="submit">
|
||||||
|
<div class="mb-3">
|
||||||
|
<label for="password" class="form-label">{{ $t('reset.password') }}</label>
|
||||||
|
<input
|
||||||
|
id="password"
|
||||||
|
v-model="password"
|
||||||
|
type="password"
|
||||||
|
class="form-control"
|
||||||
|
:class="{ 'is-invalid': errors.new_password }"
|
||||||
|
autocomplete="new-password"
|
||||||
|
aria-describedby="password-rules"
|
||||||
|
/>
|
||||||
|
<div class="invalid-feedback">{{ errors.new_password }}</div>
|
||||||
|
<div id="password-rules" class="form-text">{{ $t('register.passwordRules') }}</div>
|
||||||
|
</div>
|
||||||
|
<div class="mb-4">
|
||||||
|
<label for="confirm" class="form-label">{{ $t('reset.confirm') }}</label>
|
||||||
|
<input
|
||||||
|
id="confirm"
|
||||||
|
v-model="confirm"
|
||||||
|
type="password"
|
||||||
|
class="form-control"
|
||||||
|
:class="{ 'is-invalid': mismatch }"
|
||||||
|
autocomplete="new-password"
|
||||||
|
/>
|
||||||
|
<div class="invalid-feedback">{{ $t('register.mismatch') }}</div>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
class="btn btn-primary w-100"
|
||||||
|
:disabled="loading || password.length < 12 || password !== confirm"
|
||||||
|
>
|
||||||
|
{{ loading ? $t('reset.submitting') : $t('reset.submit') }}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- Maquette 12 -->
|
||||||
|
<section v-else class="auth-card wide prism-card text-center" aria-labelledby="invalid-title">
|
||||||
|
<div class="icon-circle warning" aria-hidden="true">!</div>
|
||||||
|
<h1 id="invalid-title">{{ $t('reset.invalidTitle') }}</h1>
|
||||||
|
<p>{{ $t('reset.invalidText') }}</p>
|
||||||
|
<RouterLink :to="{ name: 'forgot-password' }" class="btn btn-primary w-100">
|
||||||
|
{{ $t('reset.newLink') }}
|
||||||
|
</RouterLink>
|
||||||
|
<p class="auth-links mb-0">
|
||||||
|
<RouterLink :to="{ name: 'login' }" class="link-strong">{{ $t('forgot.back') }}</RouterLink>
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
{
|
||||||
|
"extends": "@vue/tsconfig/tsconfig.dom.json",
|
||||||
|
"include": ["env.d.ts", "src/**/*", "src/**/*.vue"],
|
||||||
|
"exclude": ["src/**/__tests__/*"],
|
||||||
|
"compilerOptions": {
|
||||||
|
// Extra safety for array and object lookups, but may have false positives.
|
||||||
|
"noUncheckedIndexedAccess": true,
|
||||||
|
|
||||||
|
// Path mapping for cleaner imports.
|
||||||
|
"paths": {
|
||||||
|
"@/*": ["./src/*"]
|
||||||
|
},
|
||||||
|
|
||||||
|
// `vue-tsc --build` produces a .tsbuildinfo file for incremental type-checking.
|
||||||
|
// Specified here to keep it out of the root directory.
|
||||||
|
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
{
|
||||||
|
"files": [],
|
||||||
|
"references": [
|
||||||
|
{
|
||||||
|
"path": "./tsconfig.node.json"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "./tsconfig.app.json"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "./tsconfig.vitest.json"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
Loaded 100 of 104 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user