Debian Codegraph @

tests/apps/headless/account/test_email_verification_by_code.py

raw
1 from http import HTTPStatus
2 from unittest.mock import ANY
3
4 from django.contrib.auth.models import User
5
6 import pytest
7 from pytest_django.asserts import assertTemplateNotUsed, assertTemplateUsed
8
9 from allauth.account import app_settings
10 from allauth.account.models import EmailAddress
11 from allauth.headless.constants import Flow
12
13
14 def test_email_verification_rate_limits_login(
15 client,
16 db,
17 user_password,
18 settings,
19 user_factory,
20 password_factory,
21 enable_cache,
22 headless_reverse,
23 ):
24 settings.ACCOUNT_AUTHENTICATION_METHOD = "email"
25 settings.ACCOUNT_EMAIL_VERIFICATION_BY_CODE_ENABLED = True
26 settings.ACCOUNT_EMAIL_VERIFICATION = "mandatory"
27 settings.ACCOUNT_RATE_LIMITS = {"confirm_email": "1/m/key"}
28 email = "[email protected]"
29 user_factory(email=email, email_verified=False, password=user_password)
30 for attempt in range(2):
31 resp = client.post(
32 headless_reverse("headless:account:login"),
33 data={
34 "email": email,
35 "password": user_password,
36 },
37 content_type="application/json",
38 )
39 if attempt == 0:
40 assert resp.status_code == HTTPStatus.UNAUTHORIZED
41 flow = [
42 flow for flow in resp.json()["data"]["flows"] if flow.get("is_pending")
43 ][0]
44 assert flow["id"] == Flow.VERIFY_EMAIL
45 else:
46 assert resp.status_code == HTTPStatus.BAD_REQUEST
47 assert resp.json() == {
48 "status": HTTPStatus.BAD_REQUEST,
49 "errors": [
50 {
51 "message": "Too many failed login attempts. Try again later.",
52 "code": "too_many_login_attempts",
53 }
54 ],
55 }
56
57
58 @pytest.mark.parametrize("method", ["GET", "POST"])
59 def test_email_verification_rate_limits_submitting_codes(
60 client,
61 db,
62 user_password,
63 settings,
64 user_factory,
65 password_factory,
66 enable_cache,
67 headless_reverse,
68 method,
69 ):
70 settings.ACCOUNT_AUTHENTICATION_METHOD = "email"
71 settings.ACCOUNT_EMAIL_VERIFICATION_BY_CODE_ENABLED = True
72 settings.ACCOUNT_EMAIL_VERIFICATION = "mandatory"
73 settings.ACCOUNT_RATE_LIMITS = {"confirm_email": "1/m/key"}
74 email = "[email protected]"
75 user_factory(email=email, email_verified=False, password=user_password)
76 resp = client.post(
77 headless_reverse("headless:account:login"),
78 data={
79 "email": email,
80 "password": user_password,
81 },
82 content_type="application/json",
83 )
84 assert resp.status_code == HTTPStatus.UNAUTHORIZED
85 flow = [flow for flow in resp.json()["data"]["flows"] if flow.get("is_pending")][0]
86 assert flow["id"] == Flow.VERIFY_EMAIL
87
88 for i in range(app_settings.EMAIL_VERIFICATION_BY_CODE_MAX_ATTEMPTS):
89 if method == "GET":
90 resp = client.get(
91 headless_reverse("headless:account:verify_email"),
92 HTTP_X_EMAIL_VERIFICATION_KEY="123",
93 )
94 else:
95 resp = client.post(
96 headless_reverse("headless:account:verify_email"),
97 data={
98 "key": "123",
99 },
100 content_type="application/json",
101 )
102 if i < app_settings.EMAIL_VERIFICATION_BY_CODE_MAX_ATTEMPTS:
103 assert resp.json() == {
104 "status": HTTPStatus.BAD_REQUEST,
105 "errors": [
106 {
107 "message": "Incorrect code.",
108 "code": "incorrect_code",
109 "param": "key",
110 }
111 ],
112 }
113 assert resp.status_code == HTTPStatus.BAD_REQUEST
114 else:
115 assert resp.status_code == HTTPStatus.CONFLICT
116
117
118 def test_add_email(
119 auth_client,
120 user,
121 email_factory,
122 headless_reverse,
123 settings,
124 get_last_email_verification_code,
125 mailoutbox,
126 ):
127 settings.ACCOUNT_AUTHENTICATION_METHOD = "email"
128 settings.ACCOUNT_EMAIL_VERIFICATION_BY_CODE_ENABLED = True
129 settings.ACCOUNT_CHANGE_EMAIL = True
130 new_email = email_factory()
131
132 # Let's add an email...
133 resp = auth_client.post(
134 headless_reverse("headless:account:manage_email"),
135 data={"email": new_email},
136 content_type="application/json",
137 )
138 assert resp.status_code == HTTPStatus.OK
139
140 assertTemplateNotUsed(resp, "account/email/email_confirmation_signup_message.txt")
141 assertTemplateUsed(resp, "account/email/email_confirmation_message.txt")
142
143 # It's in the response, albeit unverified.
144 assert len(resp.json()["data"]) == 2
145 email_map = {addr["email"]: addr for addr in resp.json()["data"]}
146 assert not email_map[new_email]["verified"]
147
148 # Verify the email with an invalid code.
149 resp = auth_client.post(
150 headless_reverse("headless:account:verify_email"),
151 data={"key": "key"},
152 content_type="application/json",
153 )
154 assert resp.status_code == HTTPStatus.BAD_REQUEST
155 assert resp.json() == {
156 "status": HTTPStatus.BAD_REQUEST,
157 "errors": [
158 {"message": "Incorrect code.", "code": "incorrect_code", "param": "key"}
159 ],
160 }
161
162 # And with the valid code...
163 code = get_last_email_verification_code(auth_client, mailoutbox)
164 resp = auth_client.post(
165 headless_reverse("headless:account:verify_email"),
166 data={"key": code},
167 content_type="application/json",
168 )
169 assert resp.status_code == HTTPStatus.OK
170 assert resp.json()["data"]["user"]["email"] == new_email
171
172 # ACCOUNT_CHANGE_EMAIL = True, so the other one is gone.
173 assert EmailAddress.objects.filter(user=user).count() == 1
174
175 # Re-verification won't work...
176 resp = auth_client.post(
177 headless_reverse("headless:account:verify_email"),
178 data={"key": code},
179 content_type="application/json",
180 )
181 assert resp.status_code == HTTPStatus.CONFLICT
182
183
184 @pytest.mark.parametrize("login_on_email_verification", [False, True])
185 def test_signup_with_email_verification(
186 db,
187 client,
188 email_factory,
189 password_factory,
190 settings,
191 headless_reverse,
192 headless_client,
193 get_last_email_verification_code,
194 login_on_email_verification,
195 mailoutbox,
196 ):
197 settings.ACCOUNT_EMAIL_VERIFICATION = "mandatory"
198 settings.ACCOUNT_USERNAME_REQUIRED = False
199 # This setting should have no affect:
200 settings.ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = login_on_email_verification
201 settings.ACCOUNT_EMAIL_VERIFICATION_BY_CODE_ENABLED = True
202 email = email_factory()
203 resp = client.post(
204 headless_reverse("headless:account:signup"),
205 data={
206 "email": email,
207 "password": password_factory(),
208 },
209 content_type="application/json",
210 )
211 assertTemplateUsed(resp, "account/email/email_confirmation_signup_message.txt")
212
213 assert resp.status_code == HTTPStatus.UNAUTHORIZED
214 assert User.objects.filter(email=email).exists()
215 data = resp.json()
216 flow = next(f for f in data["data"]["flows"] if f.get("is_pending"))
217 assert flow["id"] == "verify_email"
218
219 code = get_last_email_verification_code(client, mailoutbox)
220 resp = client.get(
221 headless_reverse("headless:account:verify_email"),
222 HTTP_X_EMAIL_VERIFICATION_KEY=code,
223 )
224 assert resp.status_code == HTTPStatus.OK
225 assert resp.json() == {
226 "data": {
227 "email": email,
228 "user": ANY,
229 },
230 "meta": {"is_authenticating": True},
231 "status": HTTPStatus.OK,
232 }
233 resp = client.post(
234 headless_reverse("headless:account:verify_email"),
235 data={"key": code},
236 content_type="application/json",
237 )
238 addr = EmailAddress.objects.get(email=email)
239 assert addr.verified
240
241 assert resp.status_code == HTTPStatus.OK
242 data = resp.json()
243 assert data["meta"]["is_authenticated"]
244
245
246 @pytest.mark.parametrize("rate_limit_enabled", [(False,), (True,)])
247 def test_resend_at_signup(
248 db,
249 client,
250 email_factory,
251 password_factory,
252 settings,
253 headless_reverse,
254 headless_client,
255 get_last_email_verification_code,
256 mailoutbox,
257 rate_limit_enabled,
258 request,
259 ):
260 if rate_limit_enabled:
261 request.getfixturevalue("enable_cache")
262 settings.ACCOUNT_EMAIL_VERIFICATION = "mandatory"
263 settings.ACCOUNT_USERNAME_REQUIRED = False
264 # This setting should have no affect:
265 settings.ACCOUNT_EMAIL_VERIFICATION_SUPPORTS_RESEND = True
266 settings.ACCOUNT_EMAIL_VERIFICATION_BY_CODE_ENABLED = True
267 email = email_factory()
268 resp = client.post(
269 headless_reverse("headless:account:signup"),
270 data={
271 "email": email,
272 "password": password_factory(),
273 },
274 content_type="application/json",
275 )
276 assert resp.status_code == HTTPStatus.UNAUTHORIZED
277 assert User.objects.filter(email=email).exists()
278 data = resp.json()
279 flow = next(f for f in data["data"]["flows"] if f.get("is_pending"))
280 assert flow["id"] == "verify_email"
281
282 code = get_last_email_verification_code(client, mailoutbox)
283 resp = client.get(
284 headless_reverse("headless:account:verify_email"),
285 HTTP_X_EMAIL_VERIFICATION_KEY=code,
286 )
287 assert resp.status_code == HTTPStatus.OK
288 assert resp.json() == {
289 "data": {
290 "email": email,
291 "user": ANY,
292 },
293 "meta": {"is_authenticating": True},
294 "status": HTTPStatus.OK,
295 }
296 resp = client.post(
297 headless_reverse("headless:account:resend_email_verification_code"),
298 )
299 if rate_limit_enabled:
300 assert resp.status_code == HTTPStatus.TOO_MANY_REQUESTS
301 else:
302 assert resp.status_code == HTTPStatus.OK
303
304 new_code = get_last_email_verification_code(client, mailoutbox)
305 assert code != new_code
306
307
308 def test_add_resend_verify_email(
309 auth_client,
310 user,
311 email_factory,
312 headless_reverse,
313 settings_impacting_urls,
314 get_last_email_verification_code,
315 mailoutbox,
316 ):
317 with settings_impacting_urls(
318 ACCOUNT_EMAIL_VERIFICATION_BY_CODE_ENABLED=True,
319 ACCOUNT_EMAIL_VERIFICATION_SUPPORTS_RESEND=True,
320 ):
321 new_email = email_factory()
322 resp = auth_client.post(
323 headless_reverse("headless:account:manage_email"),
324 data={"email": new_email},
325 content_type="application/json",
326 )
327 assert resp.status_code == HTTPStatus.OK
328 assert len(resp.json()["data"]) == 2
329 assert len(mailoutbox) == 1
330 assert not EmailAddress.objects.filter(email=new_email, verified=False).exists()
331 code = get_last_email_verification_code(auth_client, mailoutbox)
332 resp = auth_client.put(
333 headless_reverse("headless:account:manage_email"),
334 data={"email": new_email},
335 content_type="application/json",
336 )
337 assert resp.status_code == HTTPStatus.OK
338 assert len(mailoutbox) == 2
339
340 code2 = get_last_email_verification_code(auth_client, mailoutbox)
341 assert code != code2
342 resp = auth_client.post(
343 headless_reverse("headless:account:verify_email"),
344 data={"key": code2},
345 content_type="application/json",
346 )
347 assert EmailAddress.objects.filter(email=new_email, verified=True).exists()
348
349
350 def test_remove_unverified_email(
351 auth_client,
352 user,
353 email_factory,
354 headless_reverse,
355 settings,
356 get_last_email_verification_code,
357 mailoutbox,
358 ):
359 settings.ACCOUNT_AUTHENTICATION_METHOD = "email"
360 settings.ACCOUNT_EMAIL_VERIFICATION_BY_CODE_ENABLED = True
361 settings.ACCOUNT_CHANGE_EMAIL = True
362 new_email = email_factory()
363
364 # Let's add an email...
365 resp = auth_client.post(
366 headless_reverse("headless:account:manage_email"),
367 data={"email": new_email},
368 content_type="application/json",
369 )
370 assert resp.status_code == HTTPStatus.OK
371
372 # It's in the response, albeit unverified.
373 assert len(resp.json()["data"]) == 2
374 email_map = {addr["email"]: addr for addr in resp.json()["data"]}
375 assert not email_map[new_email]["verified"]
376
377 # Delete the pending email.
378 resp = auth_client.delete(
379 headless_reverse("headless:account:manage_email"),
380 data={"email": new_email},
381 content_type="application/json",
382 )
383 assert resp.status_code == HTTPStatus.OK
384 assert len(resp.json()["data"]) == 1
385 assert new_email not in {addr["email"] for addr in resp.json()["data"]}