- app/auth/ : jetons (lien magique aléatoire haché SHA-256, JWT HS256), dépendances get_current_account / current_account_in_edition / require_roles + require_coordinator / require_staff, et ensure_can_write_position/_shift - Endpoints app/api/auth.py : POST .../auth/magic-link (202 constant, pas de divulgation), POST .../auth/verify (JWT, jeton à usage unique), GET /auth/me - Envoi d'email stubé : le lien est journalisé (logger app.auth, identifiants seulement, aucune donnée nominative) - app/api/accounts.py : CRUD des comptes réservé à la COORDINATION - Rôles appliqués sur toute l'API : COORDINATION accès complet ; RÉFÉRENT lecture globale + écriture sur ses seuls postes/créneaux/affectations ; BÉNÉVOLE sa fiche et ses affectations, aucune écriture - imports.py aligné sur la dépendance get_edition (404 avant 403) - Secret JWT porté à >= 32 octets (config, .env.example, docker-compose) - seed : crée un compte VOLUNTEER pour chaque bénévole avec email (104 comptes) - conftest : fixtures make_account / coordinator / as_account / raw_client ; la suite existante s'exécute en COORDINATION - 13 tests d'authentification + de rôles ; 119 tests au total ; alembic check toujours vert (Account / MagicLinkToken déjà dans la migration 0001) Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017uUsRg7XzopkCPWimwg9ZM
100 lines
3.1 KiB
Python
100 lines
3.1 KiB
Python
import datetime as dt
|
|
import logging
|
|
|
|
from sqlmodel import select
|
|
|
|
from app.auth.tokens import hash_token
|
|
from app.models import MagicLinkToken, Role, local_now
|
|
|
|
|
|
def _url(edition, suffix):
|
|
return f"/editions/{edition.id}/auth/{suffix}"
|
|
|
|
|
|
def test_magic_link_unknown_email_is_accepted_without_token(
|
|
raw_client, session, edition
|
|
):
|
|
resp = raw_client.post(
|
|
_url(edition, "magic-link"), json={"email": "personne@example.fr"}
|
|
)
|
|
assert resp.status_code == 202
|
|
assert session.exec(select(MagicLinkToken)).all() == []
|
|
|
|
|
|
def test_full_flow_magic_link_then_jwt_then_me(
|
|
raw_client, session, edition, make_account, caplog
|
|
):
|
|
make_account(Role.COORDINATOR, email="coord@example.fr")
|
|
|
|
with caplog.at_level(logging.INFO, logger="app.auth"):
|
|
resp = raw_client.post(
|
|
_url(edition, "magic-link"), json={"email": "COORD@example.fr"}
|
|
)
|
|
assert resp.status_code == 202
|
|
log_line = next(m for m in caplog.messages if "STUB lien magique" in m)
|
|
raw_token = log_line.split("jeton=")[-1].strip()
|
|
|
|
verified = raw_client.post(
|
|
_url(edition, "verify"), json={"token": raw_token}
|
|
)
|
|
assert verified.status_code == 200
|
|
body = verified.json()
|
|
assert body["token_type"] == "bearer"
|
|
assert body["account"]["role"] == "COORDINATOR"
|
|
|
|
me = raw_client.get(
|
|
"/auth/me",
|
|
headers={"Authorization": f"Bearer {body['access_token']}"},
|
|
)
|
|
assert me.status_code == 200
|
|
assert me.json()["email"] == "coord@example.fr"
|
|
|
|
|
|
def test_verify_is_single_use(raw_client, session, edition, make_account):
|
|
account = make_account(Role.VOLUNTEER, email="v@example.fr")
|
|
session.add(
|
|
MagicLinkToken(
|
|
account_id=account.id,
|
|
token_hash=hash_token("jeton-connu"),
|
|
expires_at=local_now() + dt.timedelta(minutes=10),
|
|
)
|
|
)
|
|
session.commit()
|
|
|
|
first = raw_client.post(_url(edition, "verify"), json={"token": "jeton-connu"})
|
|
assert first.status_code == 200
|
|
second = raw_client.post(
|
|
_url(edition, "verify"), json={"token": "jeton-connu"}
|
|
)
|
|
assert second.status_code == 401
|
|
assert second.json()["detail"]["code"] == "auth.invalid_token"
|
|
|
|
|
|
def test_verify_rejects_expired_token(raw_client, session, edition, make_account):
|
|
account = make_account(Role.VOLUNTEER, email="v@example.fr")
|
|
session.add(
|
|
MagicLinkToken(
|
|
account_id=account.id,
|
|
token_hash=hash_token("perime"),
|
|
expires_at=local_now() - dt.timedelta(minutes=1),
|
|
)
|
|
)
|
|
session.commit()
|
|
resp = raw_client.post(_url(edition, "verify"), json={"token": "perime"})
|
|
assert resp.status_code == 401
|
|
|
|
|
|
def test_verify_rejects_unknown_token(raw_client, edition):
|
|
resp = raw_client.post(_url(edition, "verify"), json={"token": "n'importe"})
|
|
assert resp.status_code == 401
|
|
|
|
|
|
def test_me_requires_a_valid_bearer(raw_client):
|
|
assert raw_client.get("/auth/me").status_code == 401
|
|
assert (
|
|
raw_client.get(
|
|
"/auth/me", headers={"Authorization": "Bearer pas-un-jwt"}
|
|
).status_code
|
|
== 401
|
|
)
|