Debian Codegraph @

tests/apps/account/test_login_by_code.py

raw
1 from http import HTTPStatus
2 from unittest.mock import ANY, patch
3
4 from django.urls import reverse
5
6 import pytest
7
8 from allauth import app_settings as allauth_settings
9 from allauth.account.authentication import AUTHENTICATION_METHODS_SESSION_KEY
10 from allauth.account.internal.stagekit import LOGIN_SESSION_KEY
11 from allauth.account.models import EmailAddress
12 from allauth.account.stages import LoginByCodeStage
13
14
15 @pytest.fixture
16 def get_expected_login_code():
17 def f(client):
18 return client.session[LOGIN_SESSION_KEY]["state"]["stages"][
19 LoginByCodeStage.key
20 ]["data"]["code"]
21
22 return f
23
24
25 @pytest.fixture
26 def request_login_by_code(mailoutbox, get_expected_login_code):
27 def f(client, email):
28 resp = client.get(f"{reverse('account_request_login_code')}?next=/foo")
29 assert resp.status_code == HTTPStatus.OK
30 assert b'value="/foo"' in resp.content
31 resp = client.post(
32 reverse("account_request_login_code"), data={"email": email, "next": "/foo"}
33 )
34 assert resp.status_code == HTTPStatus.FOUND
35 assert (
36 resp["location"] == f"{reverse('account_confirm_login_code')}?next=%2Ffoo"
37 )
38 assert len(mailoutbox) == 1
39 code = get_expected_login_code(client)
40 assert len(code) == 9
41 assert code in mailoutbox[0].body
42 return code
43
44 return f
45
46
47 def test_login_by_code(client, user, request_login_by_code):
48 code = request_login_by_code(client, user.email)
49 code_with_ws = f" {code[0:3]} {code[3:]}"
50 resp = client.post(
51 reverse("account_confirm_login_code"),
52 data={"code": code_with_ws, "next": "/foo"},
53 )
54 assert resp.status_code == HTTPStatus.FOUND
55 assert LOGIN_SESSION_KEY not in client.session
56 assert resp["location"] == "/foo"
57 assert client.session[AUTHENTICATION_METHODS_SESSION_KEY][-1] == {
58 "method": "code",
59 "email": user.email,
60 "at": ANY,
61 }
62
63
64 def test_login_by_code_resend_limited(
65 client, user, request_login_by_code, settings, get_expected_login_code
66 ):
67 settings.ACCOUNT_LOGIN_BY_CODE_SUPPORTS_RESEND = 2
68 code = request_login_by_code(client, user.email)
69 for i in range(3):
70 resp = client.post(
71 reverse("account_confirm_login_code"), data={"action": "resend"}
72 )
73
74 assert resp.status_code == (
75 # Form error if resend not possible
76 HTTPStatus.OK
77 if i == 2
78 # If resend allowed, the resend form is valid and results in a redirect.
79 else HTTPStatus.FOUND
80 )
81 new_code = get_expected_login_code(client)
82 if i == 2:
83 assert new_code == code
84 else:
85 assert new_code != code
86 code = new_code
87
88
89 def test_login_by_code_resend_uses_new_code(
90 client, user, request_login_by_code, settings, get_expected_login_code
91 ):
92 settings.ACCOUNT_LOGIN_BY_CODE_SUPPORTS_RESEND = 2
93 code = request_login_by_code(client, user.email)
94 resp = client.post(reverse("account_confirm_login_code"), data={"action": "resend"})
95 assert resp.status_code == HTTPStatus.FOUND
96 assert resp["location"] == reverse("account_confirm_login_code")
97 new_code = get_expected_login_code(client)
98 assert new_code != code
99 resp = client.post(reverse("account_confirm_login_code"), data={"code": new_code})
100 assert resp.status_code == HTTPStatus.FOUND
101 assert resp["location"] == settings.LOGIN_REDIRECT_URL
102
103
104 def test_login_by_code_max_attempts(client, user, request_login_by_code, settings):
105 settings.ACCOUNT_LOGIN_BY_CODE_MAX_ATTEMPTS = 2
106 request_login_by_code(client, user.email)
107 for i in range(3):
108 with patch(
109 "allauth.account.signals.login_code_rejected"
110 ) as code_rejected_signal:
111 resp = client.post(
112 reverse("account_confirm_login_code"), data={"code": "wrong"}
113 )
114 if i >= 1:
115 assert resp.status_code == HTTPStatus.FOUND
116 assert resp["location"] == reverse("account_request_login_code")
117 assert LOGIN_SESSION_KEY not in client.session
118 else:
119 assert resp.status_code == HTTPStatus.OK
120 assert LOGIN_SESSION_KEY in client.session
121 assert resp.context["form"].errors == {"code": ["Incorrect code."]}
122
123 signal_called = i <= 1
124 assert code_rejected_signal.send.called == signal_called
125 if signal_called:
126 signal_kwargs = code_rejected_signal.send.call_args[1]
127 assert signal_kwargs["user"] == user
128 assert signal_kwargs["last_attempt"] == (i == 1)
129
130
131 def test_login_by_code_unknown_user(mailoutbox, client, db):
132 resp = client.post(
133 reverse("account_request_login_code"),
134 data={"email": "[email protected]"},
135 )
136 assert resp.status_code == HTTPStatus.FOUND
137 assert resp["location"] == reverse("account_confirm_login_code")
138 resp = client.post(reverse("account_confirm_login_code"), data={"code": "123456"})
139
140
141 @pytest.mark.parametrize(
142 "setting,code_required",
143 [
144 (True, True),
145 ({"password"}, True),
146 ({"socialaccount"}, False),
147 ],
148 )
149 def test_login_by_code_required(
150 client, settings, user_factory, password_factory, setting, code_required
151 ):
152 password = password_factory()
153 user = user_factory(password=password, email_verified=False)
154 email_address = EmailAddress.objects.get(email=user.email)
155 assert not email_address.verified
156 settings.ACCOUNT_LOGIN_BY_CODE_REQUIRED = setting
157 resp = client.post(
158 reverse("account_login"),
159 data={"login": user.username, "password": password},
160 )
161 assert resp.status_code == HTTPStatus.FOUND
162 if code_required:
163 assert resp["location"] == reverse("account_confirm_login_code")
164 code = client.session[LOGIN_SESSION_KEY]["state"]["stages"][
165 LoginByCodeStage.key
166 ]["data"]["code"]
167 resp = client.get(
168 reverse("account_confirm_login_code"),
169 data={"login": user.username, "password": password},
170 )
171 assert resp.status_code == HTTPStatus.OK
172 resp = client.post(reverse("account_confirm_login_code"), data={"code": code})
173 email_address.refresh_from_db()
174 assert email_address.verified
175 assert resp["location"] == settings.LOGIN_REDIRECT_URL
176
177
178 def test_login_by_code_redirect(client, user, request_login_by_code):
179 request_login_by_code(client, user.email)
180 resp = client.get(reverse("account_login"))
181 assert resp["location"] == reverse("account_confirm_login_code")
182
183
184 @pytest.mark.parametrize("action", ["", "trust"])
185 def test_trust_flow(
186 client,
187 user,
188 user_password,
189 settings_impacting_urls,
190 action,
191 settings,
192 ):
193 if not allauth_settings.MFA_ENABLED:
194 return
195
196 with settings_impacting_urls(
197 ACCOUNT_LOGIN_BY_CODE_TRUST_ENABLED=True, ACCOUNT_LOGIN_BY_CODE_REQUIRED=True
198 ):
199
200 # Login
201 resp = client.post(
202 reverse("account_login"),
203 {"login": user.username, "password": user_password},
204 )
205 assert resp.status_code == HTTPStatus.FOUND
206 assert resp["location"] == reverse("account_confirm_login_code")
207
208 code = client.session[LOGIN_SESSION_KEY]["state"]["stages"][
209 LoginByCodeStage.key
210 ]["data"]["code"]
211
212 # Enter code
213 resp = client.post(reverse("account_confirm_login_code"), data={"code": code})
214 assert resp.status_code == HTTPStatus.FOUND
215 assert resp["location"] == reverse("mfa_trust")
216
217 # Indicate trust
218 resp = client.post(
219 reverse("mfa_trust"),
220 {"action": action},
221 )
222 assert resp["location"] == settings.LOGIN_REDIRECT_URL
223
224 # Sign out
225 resp = client.post(
226 reverse("account_logout"),
227 )
228 assert resp.status_code == HTTPStatus.FOUND
229
230 # Sign in
231 resp = client.post(
232 reverse("account_login"),
233 {"login": user.username, "password": user_password},
234 )
235 assert resp.status_code == HTTPStatus.FOUND
236 assert resp["location"] == (
237 settings.LOGIN_REDIRECT_URL
238 if action == "trust"
239 else reverse("account_confirm_login_code")
240 )
241
242
243 def test_trust_while_already_register(
244 client, user, user_password, settings_impacting_urls, settings, mailoutbox
245 ):
246 if not allauth_settings.MFA_ENABLED:
247 return
248
249 with settings_impacting_urls(
250 ACCOUNT_SIGNUP_FIELDS=["email*", "password*"],
251 ACCOUNT_LOGIN_BY_CODE_TRUST_ENABLED=True,
252 ACCOUNT_LOGIN_BY_CODE_REQUIRED=True,
253 ACCOUNT_PREVENT_ENUMERATION=True,
254 ACCOUNT_EMAIL_VERIFICATION="mandatory",
255 ):
256 resp = client.post(
257 reverse("account_signup"),
258 {"email": user.email, "password": user_password},
259 )
260 assert resp.status_code == HTTPStatus.FOUND
261 assert resp["location"] == reverse("account_confirm_login_code")
262 assert mailoutbox[0].subject == "[example.com] Account Already Exists"