Ajoute l'inscription, la 2FA TOTP et le mot de passe oublié (API)
- Inscription avec confirmation de l'adresse (lien signé, 24 h, usage unique), notification de la cellule SSMG, validation ou refus depuis l'admin ; réponse identique si l'adresse est déjà utilisée. - Connexion en deux étapes : code TOTP (django-otp) ou code de secours (8 codes hachés, usage unique) ; activation, désactivation et régénération des codes ; 2FA obligatoire pour l'admin hors DEBUG. - Mot de passe oublié : lien d'une heure à usage unique, vérification du lien, fermeture des autres sessions ; changement du mot de passe. - Les 8 e-mails transactionnels (texte + HTML), envoyés après commit et tracés dans MailEvent sans contenu ; limitation de débit par route. - Commande purge_pending_accounts (demandes non confirmées après 7 jours). - 156 tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
26153caeaf
commit
d2da878dbd
29 files changed
+1833
-28
No files matched your search
@@ -32,6 +32,7 @@ def test_login_opens_a_session(user):
|
||||
"last_name": "Dupont",
|
||||
"roles": [],
|
||||
"is_staff": False,
|
||||
"mfa_enabled": False,
|
||||
},
|
||||
}
|
||||
assert client.get(ME).status_code == 200
|
||||
|
||||
@@ -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"
|
||||
@@ -22,6 +22,18 @@ def test_schema_documents_every_route():
|
||||
"/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"]
|
||||
assert set(assessments["responses"]) == {"200", "404", "422", "503"}
|
||||
|
||||
Reference in new issue
Block a user