Debian Codegraph @

tests/apps/account/test_email_verification_by_code.py

raw
1 from http import HTTPStatus
2 from unittest.mock import patch
3
4 from django.conf import settings
5 from django.contrib.auth import get_user_model
6 from django.test import Client
7 from django.urls import reverse
8
9 import pytest
10
11 from allauth.account.models import EmailAddress
12
13
14 @pytest.fixture(autouse=True)
15 def email_verification_settings(settings):
16 settings.ACCOUNT_EMAIL_VERIFICATION_BY_CODE_ENABLED = True
17 settings.ACCOUNT_EMAIL_VERIFICATION = "mandatory"
18 settings.ACCOUNT_AUTHENTICATION_METHOD = "email"
19 return settings
20
21
22 @pytest.mark.parametrize(
23 "query,expected_url",
24 [
25 ("", settings.LOGIN_REDIRECT_URL),
26 ("?next=/foo", "/foo"),
27 ],
28 )
29 def test_signup(
30 client,
31 db,
32 settings,
33 password_factory,
34 get_last_email_verification_code,
35 query,
36 expected_url,
37 mailoutbox,
38 ):
39 password = password_factory()
40 resp = client.post(
41 reverse("account_signup") + query,
42 {
43 "username": "johndoe",
44 "email": "[email protected]",
45 "password1": password,
46 "password2": password,
47 },
48 )
49 assert get_user_model().objects.filter(username="johndoe").count() == 1
50 code = get_last_email_verification_code(client, mailoutbox)
51 assert resp.status_code == HTTPStatus.FOUND
52 assert resp["location"] == reverse("account_email_verification_sent")
53 resp = client.get(reverse("account_email_verification_sent"))
54 assert resp.status_code == HTTPStatus.OK
55 # Test wrong code
56 with patch(
57 "allauth.account.signals.email_verification_code_rejected"
58 ) as code_rejected_signal:
59 resp = client.post(
60 reverse("account_email_verification_sent"), data={"code": "WRONG"}
61 )
62 assert resp.status_code == HTTPStatus.OK
63 assert code_rejected_signal.send.called
64 signal_kwargs = code_rejected_signal.send.call_args[1]
65 assert signal_kwargs["user"].username == "johndoe"
66 assert signal_kwargs["last_attempt"] is False
67 # Test proper code
68 resp = client.post(reverse("account_email_verification_sent"), data={"code": code})
69 assert resp.status_code == HTTPStatus.FOUND
70 assert resp["location"] == expected_url
71
72
73 def test_signup_prevent_enumeration(
74 client, db, settings, password_factory, user, mailoutbox
75 ):
76 password = password_factory()
77 resp = client.post(
78 reverse("account_signup"),
79 {
80 "username": "johndoe",
81 "email": user.email,
82 "password1": password,
83 "password2": password,
84 },
85 )
86 assert resp.status_code == HTTPStatus.FOUND
87 assert resp["location"] == reverse("account_email_verification_sent")
88 assert not get_user_model().objects.filter(username="johndoe").exists()
89 assert mailoutbox[0].subject == "[example.com] Account Already Exists"
90 resp = client.get(reverse("account_email_verification_sent"))
91 assert resp.status_code == HTTPStatus.OK
92 resp = client.post(reverse("account_email_verification_sent"), data={"code": ""})
93 assert resp.status_code == HTTPStatus.OK
94 assert resp.context["form"].errors == {"code": ["This field is required."]}
95 resp = client.post(reverse("account_email_verification_sent"), data={"code": "123"})
96 assert resp.status_code == HTTPStatus.OK
97 assert resp.context["form"].errors == {"code": ["Incorrect code."]}
98 # Max attempts
99 resp = client.post(reverse("account_email_verification_sent"), data={"code": "456"})
100 assert resp.status_code == HTTPStatus.FOUND
101 assert resp["location"] == reverse("account_login")
102
103
104 @pytest.mark.parametrize("change_email", (False, True))
105 def test_add_or_change_email(
106 auth_client,
107 user,
108 get_last_email_verification_code,
109 change_email,
110 settings,
111 mailoutbox,
112 ):
113 settings.ACCOUNT_CHANGE_EMAIL = change_email
114 settings.ACCOUNT_EMAIL_VERIFICATION_SUPPORTS_RESEND = True
115 email = "[email protected]"
116 assert EmailAddress.objects.filter(user=user).count() == 1
117 with patch("allauth.account.signals.email_added") as email_added_signal:
118 with patch("allauth.account.signals.email_changed") as email_changed_signal:
119 resp = auth_client.post(
120 reverse("account_email"), {"action_add": "", "email": email}
121 )
122 assert resp["location"] == reverse("account_email_verification_sent")
123 assert not email_added_signal.send.called
124 assert not email_changed_signal.send.called
125 assert EmailAddress.objects.filter(email=email).count() == 0
126 code = get_last_email_verification_code(auth_client, mailoutbox)
127 resp = auth_client.get(reverse("account_email_verification_sent"))
128 assert resp.status_code == HTTPStatus.OK
129 resp = auth_client.post(
130 reverse("account_email_verification_sent"), {"action": "resend"}
131 )
132 assert EmailAddress.objects.filter(email=email).count() == 0
133 assert resp.status_code == HTTPStatus.FOUND
134 code2 = get_last_email_verification_code(auth_client, mailoutbox)
135 assert code != code2
136 with patch("allauth.account.signals.email_added") as email_added_signal:
137 with patch("allauth.account.signals.email_changed") as email_changed_signal:
138 with patch(
139 "allauth.account.signals.email_confirmed"
140 ) as email_confirmed_signal:
141 resp = auth_client.post(
142 reverse("account_email_verification_sent"), data={"code": code2}
143 )
144 assert resp.status_code == HTTPStatus.FOUND
145 assert resp["location"] == settings.LOGIN_REDIRECT_URL
146 assert email_added_signal.send.called
147 assert email_confirmed_signal.send.called
148 assert email_changed_signal.send.called == change_email
149 assert EmailAddress.objects.filter(email=email, verified=True).count() == 1
150 assert EmailAddress.objects.filter(user=user).count() == (1 if change_email else 2)
151
152
153 def test_email_verification_login_redirect(
154 client, db, settings, password_factory, email_verification_settings
155 ):
156 password = password_factory()
157 resp = client.post(
158 reverse("account_signup"),
159 {
160 "username": "johndoe",
161 "email": "[email protected]",
162 "password1": password,
163 "password2": password,
164 },
165 )
166 assert resp.status_code == HTTPStatus.FOUND
167 assert resp["location"] == reverse("account_email_verification_sent")
168 resp = client.get(reverse("account_login"))
169 assert resp["location"] == reverse("account_email_verification_sent")
170
171
172 def test_email_verification_rate_limits(
173 db,
174 user_password,
175 email_verification_settings,
176 settings,
177 user_factory,
178 password_factory,
179 enable_cache,
180 ):
181 settings.ACCOUNT_RATE_LIMITS = {"confirm_email": "1/m/key"}
182 email = "[email protected]"
183 user_factory(email=email, email_verified=False, password=user_password)
184 for attempt in range(2):
185 resp = Client().post(
186 reverse("account_login"),
187 {
188 "login": email,
189 "password": user_password,
190 },
191 )
192 if attempt == 0:
193 assert resp.status_code == HTTPStatus.FOUND
194 assert resp["location"] == reverse("account_email_verification_sent")
195 else:
196 assert resp.status_code == HTTPStatus.OK
197 assert resp.context["form"].errors == {
198 "__all__": ["Too many failed login attempts. Try again later."]
199 }
200
201
202 def test_change_email_vs_enumeration_prevention(
203 client,
204 db,
205 settings,
206 password_factory,
207 get_last_email_verification_code,
208 mailoutbox,
209 messagesoutbox,
210 user,
211 ):
212 settings.ACCOUNT_EMAIL_VERIFICATION_SUPPORTS_RESEND = True
213 password = password_factory()
214 resp = client.post(
215 reverse("account_signup"),
216 {
217 "username": "johndoe",
218 "email": user.email,
219 "password1": password,
220 "password2": password,
221 },
222 )
223 # No user signed up.
224 assert get_user_model().objects.filter(username="johndoe").count() == 0
225 assert resp.status_code == HTTPStatus.FOUND
226 assert resp["location"] == reverse("account_email_verification_sent")
227 assert len(mailoutbox) == 1
228 assert mailoutbox[0].subject == "[example.com] Account Already Exists"
229 assert len(messagesoutbox) == 1
230 assert (
231 messagesoutbox[-1]["message_template"]
232 == "account/messages/email_confirmation_sent.txt"
233 )
234
235 # Resend
236 resp = client.post(reverse("account_email_verification_sent"), {"action": "resend"})
237 assert len(mailoutbox) == 1
238 assert resp.status_code == HTTPStatus.FOUND
239 assert resp["location"] == reverse("account_email_verification_sent")
240 # No new emails sent.
241 assert len(mailoutbox) == 1
242 # Yet, pretend we did.
243 assert len(messagesoutbox) == 2
244 assert (
245 messagesoutbox[-1]["message_template"]
246 == "account/messages/email_confirmation_sent.txt"
247 )
248
249
250 def test_change_to_already_existing_email(
251 client,
252 db,
253 settings,
254 password_factory,
255 get_last_email_verification_code,
256 mailoutbox,
257 messagesoutbox,
258 user,
259 ):
260 settings.ACCOUNT_EMAIL_VERIFICATION_SUPPORTS_RESEND = True
261 settings.ACCOUNT_EMAIL_VERIFICATION_SUPPORTS_CHANGE = True
262 password = password_factory()
263 resp = client.post(
264 reverse("account_signup"),
265 {
266 "username": "johndoe",
267 "email": "[email protected]",
268 "password1": password,
269 "password2": password,
270 },
271 )
272 # A user signed up.
273 new_user = get_user_model().objects.get(username="johndoe")
274 assert resp.status_code == HTTPStatus.FOUND
275 assert resp["location"] == reverse("account_email_verification_sent")
276 assert len(mailoutbox) == 1
277 assert mailoutbox[0].subject == "[example.com] Please Confirm Your Email Address"
278 assert len(messagesoutbox) == 1
279 assert (
280 messagesoutbox[-1]["message_template"]
281 == "account/messages/email_confirmation_sent.txt"
282 )
283
284 # Change to a conflicting email
285 resp = client.post(
286 reverse("account_email_verification_sent"),
287 {"action": "change", "email": user.email},
288 )
289 assert resp.status_code == HTTPStatus.FOUND
290 assert resp["location"] == reverse("account_email_verification_sent")
291 assert len(mailoutbox) == 2
292 assert mailoutbox[1].subject == "[example.com] Account Already Exists"
293 assert len(messagesoutbox) == 2
294 assert (
295 messagesoutbox[-1]["message_template"]
296 == "account/messages/email_confirmation_sent.txt"
297 )
298 new_user.refresh_from_db()
299 assert new_user.email == "[email protected]"
300
301 # Change back to new email
302 resp = client.post(
303 reverse("account_email_verification_sent"),
304 {"action": "change", "email": "[email protected]"},
305 )
306 assert len(mailoutbox) == 3
307 assert resp.status_code == HTTPStatus.FOUND
308 assert resp["location"] == reverse("account_email_verification_sent")
309 assert mailoutbox[2].subject == "[example.com] Please Confirm Your Email Address"
310 assert len(messagesoutbox) == 3
311 assert (
312 messagesoutbox[-1]["message_template"]
313 == "account/messages/email_confirmation_sent.txt"
314 )
315 new_user.refresh_from_db()
316 assert new_user.email == "[email protected]"
317
318 code = get_last_email_verification_code(client, mailoutbox)
319 resp = client.post(reverse("account_email_verification_sent"), data={"code": code})
320 assert resp.status_code == HTTPStatus.FOUND
321 email_address = EmailAddress.objects.filter(user=new_user).get()
322 assert email_address.verified
323 assert email_address.email == "[email protected]"
324
325
326 def test_verified_email_decorator__unverified(
327 auth_client, mailoutbox, get_last_email_verification_code
328 ):
329 EmailAddress.objects.all().update(verified=False)
330 resp = auth_client.get(reverse("tests_account_check_verified_email"))
331 assert resp.status_code == HTTPStatus.FOUND
332 assert resp["location"].startswith(reverse("account_email_verification_sent"))
333 code = get_last_email_verification_code(auth_client, mailoutbox)
334 resp = auth_client.post(
335 reverse("account_email_verification_sent"),
336 data={"code": code, "next": reverse("tests_account_check_verified_email")},
337 follow=True,
338 )
339 assert resp.status_code == HTTPStatus.OK
340 assert resp.content == b"VERIFIED"