Debian Codegraph @

tests/apps/account/test_reauthentication.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 import app_settings as allauth_settings
10 from allauth.account.adapter import get_adapter
11 from allauth.account.authentication import AUTHENTICATION_METHODS_SESSION_KEY
12
13
14 @pytest.mark.parametrize(
15 "with_totp,with_password,expected_method_urlnames",
16 [
17 (False, True, ["account_reauthenticate"]),
18 (True, True, ["account_reauthenticate", "mfa_reauthenticate"]),
19 (True, False, ["mfa_reauthenticate"]),
20 ],
21 )
22 def test_user_with_mfa_only(
23 user_factory, with_totp, with_password, expected_method_urlnames, client
24 ):
25 if not allauth_settings.MFA_ENABLED and with_totp:
26 return
27 user = user_factory(with_totp=with_totp, password=None if with_password else "!")
28 assert user.has_usable_password() == with_password
29 client.force_login(user)
30 methods = get_adapter().get_reauthentication_methods(user)
31 assert len(methods) == len(expected_method_urlnames)
32 assert {m["url"] for m in methods} == set(map(reverse, expected_method_urlnames))
33 for urlname in ["account_reauthenticate", "mfa_reauthenticate"]:
34 if urlname == "mfa_reauthenticate" and not allauth_settings.MFA_ENABLED:
35 continue
36 resp = client.get(f"{reverse(urlname)}?next=/foo")
37 if urlname in expected_method_urlnames:
38 assert resp.status_code == HTTPStatus.OK
39 else:
40 assert resp.status_code == HTTPStatus.FOUND
41 assert "next=%2Ffoo" in resp["location"]
42
43
44 def test_reauthentication(settings, auth_client, user_password):
45 settings.ACCOUNT_REAUTHENTICATION_REQUIRED = True
46 resp = auth_client.post(
47 reverse("account_email"),
48 {"action_add": "", "email": "[email protected]"},
49 )
50 assert resp["location"].startswith(reverse("account_reauthenticate"))
51 resp = auth_client.get(reverse("account_reauthenticate"))
52 assertTemplateUsed(resp, "account/reauthenticate.html")
53 resp = auth_client.post(
54 reverse("account_reauthenticate"), data={"password": user_password}
55 )
56 assert resp.status_code == HTTPStatus.FOUND
57 resp = auth_client.post(
58 reverse("account_email"),
59 {"action_add": "", "email": "[email protected]"},
60 )
61 assert resp["location"].startswith(reverse("account_email"))
62 methods = auth_client.session[AUTHENTICATION_METHODS_SESSION_KEY]
63 assert methods[-1] == {"method": "password", "at": ANY, "reauthenticated": True}