Debian Codegraph @

tests/apps/mfa/base/test_views.py

raw
1 from http import HTTPStatus
2 from unittest.mock import ANY
3
4 from django.urls import reverse
5
6 import pytest
7 from pytest_django.asserts import assertTemplateUsed
8
9 from allauth.account.authentication import AUTHENTICATION_METHODS_SESSION_KEY
10 from allauth.mfa.models import Authenticator
11
12
13 def test_reauthentication(auth_client, user_with_recovery_codes):
14 resp = auth_client.get(reverse("mfa_view_recovery_codes"))
15 assert resp.status_code == HTTPStatus.FOUND
16 assert resp["location"].startswith(reverse("account_reauthenticate"))
17 resp = auth_client.get(reverse("mfa_reauthenticate"))
18 assertTemplateUsed(resp, "mfa/reauthenticate.html")
19 authenticator = Authenticator.objects.get(
20 user=user_with_recovery_codes, type=Authenticator.Type.RECOVERY_CODES
21 )
22 unused_code = authenticator.wrap().get_unused_codes()[0]
23 resp = auth_client.post(reverse("mfa_reauthenticate"), data={"code": unused_code})
24 assert resp.status_code == HTTPStatus.FOUND
25 resp = auth_client.get(reverse("mfa_view_recovery_codes"))
26 assert resp.status_code == HTTPStatus.OK
27 assertTemplateUsed(resp, "mfa/recovery_codes/index.html")
28 methods = auth_client.session[AUTHENTICATION_METHODS_SESSION_KEY]
29 assert methods[-1] == {
30 "method": "mfa",
31 "type": "recovery_codes",
32 "id": authenticator.pk,
33 "at": ANY,
34 "reauthenticated": True,
35 }
36
37
38 @pytest.mark.parametrize(
39 "url_name",
40 (
41 "mfa_activate_totp",
42 "mfa_index",
43 "mfa_deactivate_totp",
44 ),
45 )
46 def test_login_required_views(client, url_name):
47 resp = client.get(reverse(url_name))
48 assert resp.status_code == HTTPStatus.FOUND
49 assert resp["location"].startswith(reverse("account_login"))
50
51
52 def test_index(auth_client, user_with_totp):
53 resp = auth_client.get(reverse("mfa_index"))
54 assert "authenticators" in resp.context
55
56
57 @pytest.mark.parametrize("allowed", [False, True])
58 def test_add_email_not_allowed(
59 auth_client,
60 user_with_totp,
61 settings,
62 allowed,
63 ):
64 settings.MFA_ALLOW_UNVERIFIED_EMAIL = allowed
65 resp = auth_client.post(
66 reverse("account_email"),
67 {"action_add": "", "email": "[email protected]"},
68 )
69 if allowed:
70 assert resp.status_code == HTTPStatus.FOUND
71 else:
72 assert resp.status_code == HTTPStatus.OK
73 assert resp.context["form"].errors == {
74 "email": [
75 "You cannot add an email address to an account protected by two-factor authentication."
76 ]
77 }
78
79
80 def test_add_email_allowed_when_verification_by_code(
81 auth_client,
82 user_with_totp,
83 settings,
84 ):
85 settings.ACCOUNT_EMAIL_VERIFICATION_BY_CODE_ENABLED = True
86 resp = auth_client.post(
87 reverse("account_email"),
88 {"action_add": "", "email": "[email protected]"},
89 )
90 assert resp.status_code == HTTPStatus.FOUND
91 assert resp["location"] == reverse("account_email_verification_sent")