| 1 |
from http import HTTPStatus |
| 2 |
|
| 3 |
import pytest |
| 4 |
|
| 5 |
from allauth.mfa.models import Authenticator |
| 6 |
|
| 7 |
|
| 8 |
def test_get_recovery_codes_requires_reauth( |
| 9 |
auth_client, user_with_recovery_codes, headless_reverse |
| 10 |
): |
| 11 |
rc = Authenticator.objects.get( |
| 12 |
type=Authenticator.Type.RECOVERY_CODES, user=user_with_recovery_codes |
| 13 |
) |
| 14 |
resp = auth_client.get(headless_reverse("headless:mfa:manage_recovery_codes")) |
| 15 |
assert resp.status_code == HTTPStatus.UNAUTHORIZED |
| 16 |
data = resp.json() |
| 17 |
assert data["meta"]["is_authenticated"] |
| 18 |
resp = auth_client.post( |
| 19 |
headless_reverse("headless:mfa:reauthenticate"), |
| 20 |
data={"code": rc.wrap().get_unused_codes()[0]}, |
| 21 |
content_type="application/json", |
| 22 |
) |
| 23 |
assert resp.status_code == HTTPStatus.OK |
| 24 |
|
| 25 |
|
| 26 |
@pytest.mark.parametrize("show_once", [False, True]) |
| 27 |
def test_get_recovery_codes( |
| 28 |
auth_client, |
| 29 |
user_with_recovery_codes, |
| 30 |
headless_reverse, |
| 31 |
reauthentication_bypass, |
| 32 |
show_once, |
| 33 |
settings, |
| 34 |
): |
| 35 |
settings.MFA_RECOVERY_CODES_SHOW_ONCE = show_once |
| 36 |
with reauthentication_bypass(): |
| 37 |
for attempt in range(2): |
| 38 |
resp = auth_client.get( |
| 39 |
headless_reverse("headless:mfa:manage_recovery_codes") |
| 40 |
) |
| 41 |
assert resp.status_code == HTTPStatus.OK |
| 42 |
data = resp.json() |
| 43 |
assert data["data"]["type"] == "recovery_codes" |
| 44 |
if show_once and attempt == 1: |
| 45 |
assert "unused_codes" not in data["data"] |
| 46 |
else: |
| 47 |
assert len(data["data"]["unused_codes"]) == 10 |
| 48 |
|
| 49 |
with reauthentication_bypass(): |
| 50 |
resp = auth_client.get(headless_reverse("headless:mfa:authenticators")) |
| 51 |
data = resp.json() |
| 52 |
assert len(data["data"]) == 2 |
| 53 |
rc = [autor for autor in data["data"] if autor["type"] == "recovery_codes"][0] |
| 54 |
assert "unused_codes" not in rc |
| 55 |
|
| 56 |
|
| 57 |
def test_generate_recovery_codes( |
| 58 |
auth_client, |
| 59 |
user_with_totp, |
| 60 |
headless_reverse, |
| 61 |
reauthentication_bypass, |
| 62 |
): |
| 63 |
with reauthentication_bypass(): |
| 64 |
resp = auth_client.get(headless_reverse("headless:mfa:manage_recovery_codes")) |
| 65 |
assert resp.status_code == HTTPStatus.NOT_FOUND |
| 66 |
with reauthentication_bypass(): |
| 67 |
resp = auth_client.post( |
| 68 |
headless_reverse("headless:mfa:manage_recovery_codes"), |
| 69 |
content_type="application/json", |
| 70 |
) |
| 71 |
assert resp.status_code == HTTPStatus.OK |
| 72 |
data = resp.json() |
| 73 |
assert data["data"]["type"] == "recovery_codes" |
| 74 |
assert len(data["data"]["unused_codes"]) == 10 |