-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
tests.py
1548 lines (1370 loc) · 56.6 KB
/
tests.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import absolute_import
import json
import uuid
from datetime import timedelta
from django import forms
from django.conf import settings
from django.contrib.auth.models import AbstractUser, AnonymousUser
from django.contrib.sites.models import Site
from django.core import mail, validators
from django.core.exceptions import ValidationError
from django.db import models
from django.http import HttpResponseRedirect
from django.template import Context, Template
from django.test.client import Client, RequestFactory
from django.test.utils import override_settings
from django.urls import reverse
from django.utils.timezone import now
from allauth.account.forms import BaseSignupForm, ResetPasswordForm, SignupForm
from allauth.account.models import (
EmailAddress,
EmailConfirmation,
EmailConfirmationHMAC,
)
from allauth.tests import Mock, TestCase, patch
from allauth.utils import get_user_model, get_username_max_length
from . import app_settings
from .adapter import get_adapter
from .auth_backends import AuthenticationBackend
from .signals import user_logged_in, user_logged_out
from .utils import (
filter_users_by_username,
url_str_to_user_pk,
user_pk_to_url_str,
user_username,
)
test_username_validators = [
validators.RegexValidator(regex=r"^[a-c]+$", message="not abc", flags=0)
]
@override_settings(
ACCOUNT_DEFAULT_HTTP_PROTOCOL="https",
ACCOUNT_EMAIL_VERIFICATION=app_settings.EmailVerificationMethod.MANDATORY,
ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.USERNAME,
ACCOUNT_SIGNUP_FORM_CLASS=None,
ACCOUNT_EMAIL_SUBJECT_PREFIX=None,
LOGIN_REDIRECT_URL="/accounts/profile/",
ACCOUNT_SIGNUP_REDIRECT_URL="/accounts/welcome/",
ACCOUNT_ADAPTER="allauth.account.adapter.DefaultAccountAdapter",
ACCOUNT_USERNAME_REQUIRED=True,
)
class AccountTests(TestCase):
def setUp(self):
if "allauth.socialaccount" in settings.INSTALLED_APPS:
# Otherwise ImproperlyConfigured exceptions may occur
from ..socialaccount.models import SocialApp
sa = SocialApp.objects.create(name="testfb", provider="facebook")
sa.sites.add(Site.objects.get_current())
@override_settings(
ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.USERNAME_EMAIL
)
def test_username_containing_at(self):
user = get_user_model().objects.create(username="@raymond.penners")
user.set_password("psst")
user.save()
EmailAddress.objects.create(
user=user,
email="raymond.penners@example.com",
primary=True,
verified=True,
)
resp = self.client.post(
reverse("account_login"),
{"login": "@raymond.penners", "password": "psst"},
)
self.assertRedirects(
resp, settings.LOGIN_REDIRECT_URL, fetch_redirect_response=False
)
def test_signup_same_email_verified_externally(self):
user = self._test_signup_email_verified_externally(
"john@example.com", "john@example.com"
)
self.assertEqual(EmailAddress.objects.filter(user=user).count(), 1)
EmailAddress.objects.get(
verified=True, email="john@example.com", user=user, primary=True
)
def test_signup_other_email_verified_externally(self):
"""
John is invited on john@example.org, but signs up via john@example.com.
E-mail verification is by-passed, their home e-mail address is
used as a secondary.
"""
user = self._test_signup_email_verified_externally(
"john@example.com", "john@example.org"
)
self.assertEqual(EmailAddress.objects.filter(user=user).count(), 2)
EmailAddress.objects.get(
verified=False, email="john@example.com", user=user, primary=False
)
EmailAddress.objects.get(
verified=True, email="john@example.org", user=user, primary=True
)
def _test_signup_email_verified_externally(self, signup_email, verified_email):
username = "johndoe"
request = RequestFactory().post(
reverse("account_signup"),
{
"username": username,
"email": signup_email,
"password1": "johndoe",
"password2": "johndoe",
},
)
# Fake stash_verified_email
from django.contrib.messages.middleware import MessageMiddleware
from django.contrib.sessions.middleware import SessionMiddleware
SessionMiddleware(lambda request: None).process_request(request)
MessageMiddleware(lambda request: None).process_request(request)
request.user = AnonymousUser()
request.session["account_verified_email"] = verified_email
from .views import signup
resp = signup(request)
self.assertEqual(resp.status_code, 302)
self.assertEqual(
resp["location"], get_adapter().get_signup_redirect_url(request)
)
self.assertEqual(len(mail.outbox), 0)
return get_user_model().objects.get(username=username)
@override_settings(
ACCOUNT_USERNAME_REQUIRED=True,
ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE=True,
)
def test_signup_password_twice_form_error(self):
resp = self.client.post(
reverse("account_signup"),
data={
"username": "johndoe",
"email": "john@example.org",
"password1": "johndoe",
"password2": "janedoe",
},
)
self.assertFormError(
resp,
"form",
"password2",
"You must type the same password each time.",
)
@override_settings(
ACCOUNT_USERNAME_REQUIRED=True, ACCOUNT_SIGNUP_EMAIL_ENTER_TWICE=True
)
def test_signup_email_twice(self):
request = RequestFactory().post(
reverse("account_signup"),
{
"username": "johndoe",
"email": "john@example.org",
"email2": "john@example.org",
"password1": "johndoe",
"password2": "johndoe",
},
)
from django.contrib.messages.middleware import MessageMiddleware
from django.contrib.sessions.middleware import SessionMiddleware
SessionMiddleware(lambda request: None).process_request(request)
MessageMiddleware(lambda request: None).process_request(request)
request.user = AnonymousUser()
from .views import signup
signup(request)
user = get_user_model().objects.get(username="johndoe")
self.assertEqual(user.email, "john@example.org")
def _create_user(self, username="john", password="doe", **kwargs):
user = get_user_model().objects.create(
username=username, is_active=True, **kwargs
)
if password:
user.set_password(password)
else:
user.set_unusable_password()
user.save()
return user
def _create_user_and_login(self, usable_password=True):
password = "doe" if usable_password else False
user = self._create_user(password=password)
self.client.force_login(user)
return user
def test_redirect_when_authenticated(self):
self._create_user_and_login()
c = self.client
resp = c.get(reverse("account_login"))
self.assertRedirects(resp, "/accounts/profile/", fetch_redirect_response=False)
def test_password_reset_get(self):
resp = self.client.get(reverse("account_reset_password"))
self.assertTemplateUsed(resp, "account/password_reset.html")
def test_password_set_redirect(self):
resp = self._password_set_or_change_redirect("account_set_password", True)
self.assertRedirects(
resp,
reverse("account_change_password"),
fetch_redirect_response=False,
)
def test_set_password_not_allowed(self):
user = self._create_user_and_login(True)
pwd = "!*123i1uwn12W23"
self.assertFalse(user.check_password(pwd))
resp = self.client.post(
reverse("account_set_password"),
data={"password1": pwd, "password2": pwd},
)
user.refresh_from_db()
self.assertFalse(user.check_password(pwd))
self.assertTrue(user.has_usable_password())
self.assertEqual(resp.status_code, 302)
def test_password_change_no_redirect(self):
resp = self._password_set_or_change_redirect("account_change_password", True)
self.assertEqual(resp.status_code, 200)
def test_password_set_no_redirect(self):
resp = self._password_set_or_change_redirect("account_set_password", False)
self.assertEqual(resp.status_code, 200)
def test_password_change_redirect(self):
resp = self._password_set_or_change_redirect("account_change_password", False)
self.assertRedirects(
resp,
reverse("account_set_password"),
fetch_redirect_response=False,
)
def _password_set_or_change_redirect(self, urlname, usable_password):
self._create_user_and_login(usable_password)
return self.client.get(reverse(urlname))
def test_ajax_password_change(self):
self._create_user_and_login()
resp = self.client.post(
reverse("account_change_password"),
data={
"oldpassword": "doe",
"password1": "AbCdEf!123",
"password2": "AbCdEf!123456",
},
HTTP_X_REQUESTED_WITH="XMLHttpRequest",
)
self.assertEqual(resp["content-type"], "application/json")
data = json.loads(resp.content.decode("utf8"))
assert "same password" in data["form"]["fields"]["password2"]["errors"][0]
def test_password_forgotten_username_hint(self):
user = self._request_new_password()
body = mail.outbox[0].body
assert user.username in body
@override_settings(
ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.EMAIL
)
def test_password_forgotten_no_username_hint(self):
user = self._request_new_password()
body = mail.outbox[0].body
assert user.username not in body
def _request_new_password(self):
user = get_user_model().objects.create(
username="john", email="john@example.org", is_active=True
)
user.set_password("doe")
user.save()
self.client.post(
reverse("account_reset_password"),
data={"email": "john@example.org"},
)
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].to, ["john@example.org"])
return user
def test_password_reset_flow_with_empty_session(self):
"""
Test the password reset flow when the session is empty:
requesting a new password, receiving the reset link via email,
following the link, getting redirected to the
new link (without the token)
Copying the link and using it in a DIFFERENT client (Browser/Device).
"""
# Request new password
self._request_new_password()
body = mail.outbox[0].body
self.assertGreater(body.find("https://"), 0)
# Extract URL for `password_reset_from_key` view
url = body[body.find("/password/reset/") :].split()[0]
resp = self.client.get(url)
reset_pass_url = resp.url
# Accesing the url via a different session
resp = self.client_class().get(reset_pass_url)
# We should receive the token_fail context_data
self.assertTemplateUsed(
resp,
"account/password_reset_from_key.%s" % app_settings.TEMPLATE_EXTENSION,
)
self.assertTrue(resp.context_data["token_fail"])
def test_password_reset_flow(self):
"""
Tests the password reset flow: requesting a new password,
receiving the reset link via email and finally resetting the
password to a new value.
"""
# Request new password
user = self._request_new_password()
body = mail.outbox[0].body
self.assertGreater(body.find("https://"), 0)
# Extract URL for `password_reset_from_key` view and access it
url = body[body.find("/password/reset/") :].split()[0]
resp = self.client.get(url)
# Follow the redirect the actual password reset page with the key
# hidden.
url = resp.url
resp = self.client.get(url)
self.assertTemplateUsed(
resp,
"account/password_reset_from_key.%s" % app_settings.TEMPLATE_EXTENSION,
)
self.assertFalse("token_fail" in resp.context_data)
# Reset the password
resp = self.client.post(
url, {"password1": "newpass123", "password2": "newpass123"}
)
self.assertRedirects(resp, reverse("account_reset_password_from_key_done"))
# Check the new password is in effect
user = get_user_model().objects.get(pk=user.pk)
self.assertTrue(user.check_password("newpass123"))
# Trying to reset the password against the same URL (or any other
# invalid/obsolete URL) returns a bad token response
resp = self.client.post(
url, {"password1": "newpass123", "password2": "newpass123"}
)
self.assertTemplateUsed(
resp,
"account/password_reset_from_key.%s" % app_settings.TEMPLATE_EXTENSION,
)
self.assertTrue(resp.context_data["token_fail"])
# Same should happen when accessing the page directly
response = self.client.get(url)
self.assertTemplateUsed(
response,
"account/password_reset_from_key.%s" % app_settings.TEMPLATE_EXTENSION,
)
self.assertTrue(response.context_data["token_fail"])
# When in XHR views, it should respond with a 400 bad request
# code, and the response body should contain the JSON-encoded
# error from the adapter
response = self.client.post(
url,
{"password1": "newpass123", "password2": "newpass123"},
HTTP_X_REQUESTED_WITH="XMLHttpRequest",
)
self.assertEqual(response.status_code, 400)
data = json.loads(response.content.decode("utf8"))
assert "invalid" in data["form"]["errors"][0]
@override_settings(
ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.EMAIL
)
def test_password_reset_flow_with_another_user_logged_in(self):
"""
Tests the password reset flow: if User B requested a password
reset earlier and now User A is logged in, User B now clicks on
the link, ensure User A is logged out before continuing.
"""
# Request new password
self._request_new_password()
body = mail.outbox[0].body
self.assertGreater(body.find("https://"), 0)
user2 = self._create_user(username="john2", email="john2@example.com")
EmailAddress.objects.create(
user=user2, email=user2.email, primary=True, verified=True
)
resp = self.client.post(
reverse("account_login"),
{
"login": user2.email,
"password": "doe",
},
)
self.assertEqual(user2, resp.context["user"])
# Extract URL for `password_reset_from_key` view and access it
url = body[body.find("/password/reset/") :].split()[0]
resp = self.client.get(url)
# Follow the redirect the actual password reset page with the key
# hidden.
url = resp.url
resp = self.client.get(url)
self.assertTemplateUsed(
resp, "account/password_reset_from_key.%s" % app_settings.TEMPLATE_EXTENSION
)
self.assertFalse("token_fail" in resp.context_data)
# Reset the password
resp = self.client.post(
url, {"password1": "newpass123", "password2": "newpass123"}, follow=True
)
self.assertRedirects(resp, reverse("account_reset_password_from_key_done"))
self.assertNotEqual(user2, resp.context["user"])
self.assertEqual(AnonymousUser(), resp.context["user"])
def test_password_reset_flow_with_email_changed(self):
"""
Test that the password reset token is invalidated if
the user email address was changed.
"""
user = self._request_new_password()
body = mail.outbox[0].body
self.assertGreater(body.find("https://"), 0)
EmailAddress.objects.create(user=user, email="other@email.org")
# Extract URL for `password_reset_from_key` view
url = body[body.find("/password/reset/") :].split()[0]
resp = self.client.get(url)
self.assertTemplateUsed(
resp,
"account/password_reset_from_key.%s" % app_settings.TEMPLATE_EXTENSION,
)
self.assertTrue("token_fail" in resp.context_data)
@override_settings(ACCOUNT_LOGIN_ON_PASSWORD_RESET=True)
def test_password_reset_ACCOUNT_LOGIN_ON_PASSWORD_RESET(self):
user = self._request_new_password()
body = mail.outbox[0].body
url = body[body.find("/password/reset/") :].split()[0]
resp = self.client.get(url)
# Follow the redirect the actual password reset page with the key
# hidden.
resp = self.client.post(
resp.url, {"password1": "newpass123", "password2": "newpass123"}
)
self.assertTrue(user.is_authenticated)
# EmailVerificationMethod.MANDATORY sends us to the confirm-email page
self.assertRedirects(resp, "/confirm-email/")
@override_settings(ACCOUNT_EMAIL_CONFIRMATION_HMAC=False)
def test_email_verification_mandatory(self):
c = Client()
# Signup
resp = c.post(
reverse("account_signup"),
{
"username": "johndoe",
"email": "john@example.com",
"password1": "johndoe",
"password2": "johndoe",
},
follow=True,
)
self.assertEqual(resp.status_code, 200)
self.assertEqual(mail.outbox[0].to, ["john@example.com"])
self.assertGreater(mail.outbox[0].body.find("https://"), 0)
self.assertEqual(len(mail.outbox), 1)
self.assertTemplateUsed(
resp,
"account/verification_sent.%s" % app_settings.TEMPLATE_EXTENSION,
)
# Attempt to login, unverified
for attempt in [1, 2]:
resp = c.post(
reverse("account_login"),
{"login": "johndoe", "password": "johndoe"},
follow=True,
)
# is_active is controlled by the admin to manually disable
# users. I don't want this flag to flip automatically whenever
# users verify their email adresses.
self.assertTrue(
get_user_model()
.objects.filter(username="johndoe", is_active=True)
.exists()
)
self.assertTemplateUsed(
resp,
"account/verification_sent." + app_settings.TEMPLATE_EXTENSION,
)
# Attempt 1: no mail is sent due to cool-down ,
# but there was already a mail in the outbox.
self.assertEqual(len(mail.outbox), attempt)
self.assertEqual(
EmailConfirmation.objects.filter(
email_address__email="john@example.com"
).count(),
attempt,
)
# Wait for cooldown
EmailConfirmation.objects.update(sent=now() - timedelta(days=1))
# Verify, and re-attempt to login.
confirmation = EmailConfirmation.objects.filter(
email_address__user__username="johndoe"
)[:1].get()
resp = c.get(reverse("account_confirm_email", args=[confirmation.key]))
self.assertTemplateUsed(
resp, "account/email_confirm.%s" % app_settings.TEMPLATE_EXTENSION
)
c.post(reverse("account_confirm_email", args=[confirmation.key]))
resp = c.post(
reverse("account_login"),
{"login": "johndoe", "password": "johndoe"},
)
self.assertRedirects(
resp, settings.LOGIN_REDIRECT_URL, fetch_redirect_response=False
)
def test_email_escaping(self):
site = Site.objects.get_current()
site.name = '<enc&"test>'
site.save()
u = get_user_model().objects.create(username="test", email="user@example.com")
request = RequestFactory().get("/")
EmailAddress.objects.add_email(request, u, u.email, confirm=True)
self.assertTrue(mail.outbox[0].subject[1:].startswith(site.name))
@override_settings(
ACCOUNT_EMAIL_VERIFICATION=app_settings.EmailVerificationMethod.OPTIONAL
)
def test_login_unverified_account_optional(self):
"""Tests login behavior when email verification is optional."""
user = get_user_model().objects.create(username="john")
user.set_password("doe")
user.save()
EmailAddress.objects.create(
user=user, email="user@example.com", primary=True, verified=False
)
resp = self.client.post(
reverse("account_login"), {"login": "john", "password": "doe"}
)
self.assertRedirects(
resp, settings.LOGIN_REDIRECT_URL, fetch_redirect_response=False
)
@override_settings(
ACCOUNT_EMAIL_VERIFICATION=app_settings.EmailVerificationMethod.OPTIONAL,
ACCOUNT_LOGIN_ATTEMPTS_LIMIT=3,
)
def test_login_failed_attempts_exceeded(self):
user = get_user_model().objects.create(username="john")
user.set_password("doe")
user.save()
EmailAddress.objects.create(
user=user, email="user@example.com", primary=True, verified=False
)
for i in range(5):
is_valid_attempt = i == 4
is_locked = i >= 3
resp = self.client.post(
reverse("account_login"),
{
"login": ["john", "John", "JOHN", "JOhn", "joHN"][i],
"password": ("doe" if is_valid_attempt else "wrong"),
},
)
self.assertFormError(
resp,
"form",
None,
"Too many failed login attempts. Try again later."
if is_locked
else "The username and/or password you specified are not correct.",
)
@override_settings(
ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.EMAIL,
ACCOUNT_EMAIL_VERIFICATION=app_settings.EmailVerificationMethod.MANDATORY,
ACCOUNT_LOGIN_ATTEMPTS_LIMIT=1,
)
def test_login_failed_attempts_exceeded_cleared_on_password_reset(self):
# Ensure that login attempts, once they hit the limit,
# can use the password reset mechanism to regain access.
user = get_user_model().objects.create(
username="john", email="john@example.org", is_active=True
)
user.set_password("doe")
user.save()
EmailAddress.objects.create(
user=user, email="john@example.org", primary=True, verified=True
)
resp = self.client.post(
reverse("account_login"), {"login": user.email, "password": "bad"}
)
self.assertFormError(
resp,
"form",
None,
"The e-mail address and/or password you specified" " are not correct.",
)
resp = self.client.post(
reverse("account_login"), {"login": user.email, "password": "bad"}
)
self.assertFormError(
resp,
"form",
None,
"Too many failed login attempts. Try again later.",
)
self.client.post(reverse("account_reset_password"), data={"email": user.email})
body = mail.outbox[0].body
self.assertGreater(body.find("https://"), 0)
# Extract URL for `password_reset_from_key` view and access it
url = body[body.find("/password/reset/") :].split()[0]
resp = self.client.get(url)
# Follow the redirect the actual password reset page with the key
# hidden.
url = resp.url
resp = self.client.get(url)
self.assertTemplateUsed(
resp,
"account/password_reset_from_key.%s" % app_settings.TEMPLATE_EXTENSION,
)
self.assertFalse("token_fail" in resp.context_data)
new_password = "newpass123"
# Reset the password
resp = self.client.post(
url, {"password1": new_password, "password2": new_password}
)
self.assertRedirects(resp, reverse("account_reset_password_from_key_done"))
# Check the new password is in effect
user = get_user_model().objects.get(pk=user.pk)
self.assertTrue(user.check_password(new_password))
resp = self.client.post(
reverse("account_login"),
{"login": user.email, "password": new_password},
)
self.assertRedirects(
resp, settings.LOGIN_REDIRECT_URL, fetch_redirect_response=False
)
@override_settings(
ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.EMAIL,
ACCOUNT_EMAIL_VERIFICATION=app_settings.EmailVerificationMethod.MANDATORY,
ACCOUNT_LOGIN_ATTEMPTS_LIMIT=1,
)
def test_login_using_unverified_email_address_is_prohibited(self):
user = get_user_model().objects.create(
username="john", email="john@example.org", is_active=True
)
user.set_password("doe")
user.save()
EmailAddress.objects.create(
user=user, email="john@example.org", primary=True, verified=True
)
EmailAddress.objects.create(
user=user, email="john@example.com", primary=True, verified=False
)
resp = self.client.post(
reverse("account_login"), {"login": "john@example.com", "password": "doe"}
)
self.assertRedirects(
resp,
reverse("account_email_verification_sent"),
fetch_redirect_response=False,
)
self.assertEqual(len(mail.outbox), 1)
assert mail.outbox[0].to == ["john@example.com"]
def test_login_unverified_account_mandatory(self):
"""Tests login behavior when email verification is mandatory."""
user = get_user_model().objects.create(username="john")
user.set_password("doe")
user.save()
EmailAddress.objects.create(
user=user, email="user@example.com", primary=True, verified=False
)
resp = self.client.post(
reverse("account_login"), {"login": "john", "password": "doe"}
)
self.assertRedirects(resp, reverse("account_email_verification_sent"))
def test_login_inactive_account(self):
"""
Tests login behavior with inactive accounts.
Inactive user accounts should be prevented from performing any actions,
regardless of their verified state.
"""
# Inactive and verified user account
user = get_user_model().objects.create(username="john", is_active=False)
user.set_password("doe")
user.save()
EmailAddress.objects.create(
user=user, email="john@example.com", primary=True, verified=True
)
resp = self.client.post(
reverse("account_login"), {"login": "john", "password": "doe"}
)
self.assertRedirects(resp, reverse("account_inactive"))
# Inactive and unverified user account
user = get_user_model().objects.create(username="doe", is_active=False)
user.set_password("john")
user.save()
EmailAddress.objects.create(
user=user, email="user@example.com", primary=True, verified=False
)
resp = self.client.post(
reverse("account_login"), {"login": "doe", "password": "john"}
)
self.assertRedirects(resp, reverse("account_inactive"))
def test_ajax_password_reset(self):
get_user_model().objects.create(
username="john", email="john@example.org", is_active=True
)
resp = self.client.post(
reverse("account_reset_password"),
data={"email": "john@example.org"},
HTTP_X_REQUESTED_WITH="XMLHttpRequest",
)
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].to, ["john@example.org"])
self.assertEqual(resp["content-type"], "application/json")
def test_ajax_login_fail(self):
resp = self.client.post(
reverse("account_login"),
{},
HTTP_X_REQUESTED_WITH="XMLHttpRequest",
)
self.assertEqual(resp.status_code, 400)
json.loads(resp.content.decode("utf8"))
# TODO: Actually test something
@override_settings(
ACCOUNT_EMAIL_VERIFICATION=app_settings.EmailVerificationMethod.OPTIONAL
)
def test_ajax_login_success(self):
user = get_user_model().objects.create(username="john", is_active=True)
user.set_password("doe")
user.save()
resp = self.client.post(
reverse("account_login"),
{"login": "john", "password": "doe"},
HTTP_X_REQUESTED_WITH="XMLHttpRequest",
)
self.assertEqual(resp.status_code, 200)
data = json.loads(resp.content.decode("utf8"))
self.assertEqual(data["location"], "/accounts/profile/")
def test_email_view(self):
self._create_user_and_login()
self.client.get(reverse("account_email"))
# TODO: Actually test something
@override_settings(ACCOUNT_LOGOUT_ON_GET=True)
def test_logout_view_on_get(self):
c, resp = self._logout_view("get")
self.assertTemplateUsed(resp, "account/messages/logged_out.txt")
@override_settings(ACCOUNT_LOGOUT_ON_GET=False)
def test_logout_view_on_post(self):
c, resp = self._logout_view("get")
self.assertTemplateUsed(
resp, "account/logout.%s" % app_settings.TEMPLATE_EXTENSION
)
receiver_mock = Mock()
user_logged_out.connect(receiver_mock)
resp = c.post(reverse("account_logout"))
self.assertTemplateUsed(resp, "account/messages/logged_out.txt")
receiver_mock.assert_called_once_with(
sender=get_user_model(),
request=resp.wsgi_request,
user=get_user_model().objects.get(username="john"),
signal=user_logged_out,
)
user_logged_out.disconnect(receiver_mock)
def _logout_view(self, method):
c = Client()
user = get_user_model().objects.create(username="john", is_active=True)
user.set_password("doe")
user.save()
c = Client()
c.login(username="john", password="doe")
return c, getattr(c, method)(reverse("account_logout"))
@override_settings(
ACCOUNT_EMAIL_VERIFICATION=app_settings.EmailVerificationMethod.OPTIONAL,
ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE=False,
)
def test_optional_email_verification(self):
c = Client()
# Signup
c.get(reverse("account_signup"))
resp = c.post(
reverse("account_signup"),
{
"username": "johndoe",
"email": "john@example.com",
"password1": "johndoe",
},
)
# Logged in
self.assertRedirects(
resp, settings.ACCOUNT_SIGNUP_REDIRECT_URL, fetch_redirect_response=False
)
self.assertEqual(mail.outbox[0].to, ["john@example.com"])
self.assertEqual(len(mail.outbox), 1)
# Logout & login again
c.logout()
# Wait for cooldown
EmailConfirmation.objects.update(sent=now() - timedelta(days=1))
# Signup
resp = c.post(
reverse("account_login"),
{"login": "johndoe", "password": "johndoe"},
)
self.assertRedirects(
resp, settings.LOGIN_REDIRECT_URL, fetch_redirect_response=False
)
self.assertEqual(mail.outbox[0].to, ["john@example.com"])
# There was an issue that we sent out email confirmation mails
# on each login in case of optional verification. Make sure
# this is not the case:
self.assertEqual(len(mail.outbox), 1)
@override_settings(ACCOUNT_AUTHENTICATED_LOGIN_REDIRECTS=False)
def test_account_authenticated_login_redirects_is_false(self):
self._create_user_and_login()
resp = self.client.get(reverse("account_login"))
self.assertEqual(resp.status_code, 200)
@override_settings(
AUTH_PASSWORD_VALIDATORS=[
{
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
"OPTIONS": {
"min_length": 9,
},
}
]
)
def test_django_password_validation(self):
resp = self.client.post(
reverse("account_signup"),
{
"username": "johndoe",
"email": "john@example.com",
"password1": "johndoe",
"password2": "johndoe",
},
)
self.assertFormError(resp, "form", None, [])
self.assertFormError(
resp,
"form",
"password1",
["This password is too short." " It must contain at least 9 characters."],
)
@override_settings(ACCOUNT_EMAIL_CONFIRMATION_HMAC=True)
def test_email_confirmation_hmac_falls_back(self):
user = self._create_user()
email = EmailAddress.objects.create(
user=user, email="a@b.com", verified=False, primary=True
)
confirmation = EmailConfirmation.create(email)
confirmation.sent = now()
confirmation.save()
self.client.post(reverse("account_confirm_email", args=[confirmation.key]))
email = EmailAddress.objects.get(pk=email.pk)
self.assertTrue(email.verified)
@override_settings(ACCOUNT_EMAIL_CONFIRMATION_HMAC=True)
def test_email_confirmation_hmac(self):
user = self._create_user()
email = EmailAddress.objects.create(
user=user, email="a@b.com", verified=False, primary=True
)
confirmation = EmailConfirmationHMAC(email)
confirmation.send()
self.assertEqual(len(mail.outbox), 1)
self.client.post(reverse("account_confirm_email", args=[confirmation.key]))
email = EmailAddress.objects.get(pk=email.pk)
self.assertTrue(email.verified)
@override_settings(
ACCOUNT_EMAIL_CONFIRMATION_HMAC=True,
ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS=0,
)
def test_email_confirmation_hmac_timeout(self):
user = self._create_user()
email = EmailAddress.objects.create(
user=user, email="a@b.com", verified=False, primary=True
)
confirmation = EmailConfirmationHMAC(email)
confirmation.send()
self.assertEqual(len(mail.outbox), 1)
self.client.post(reverse("account_confirm_email", args=[confirmation.key]))
email = EmailAddress.objects.get(pk=email.pk)
self.assertFalse(email.verified)
@override_settings(
ACCOUNT_USERNAME_VALIDATORS="allauth.account.tests" ".test_username_validators"
)
def test_username_validator(self):
get_adapter().clean_username("abc")
self.assertRaises(ValidationError, lambda: get_adapter().clean_username("def"))
@override_settings(
ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.EMAIL
)
def test_confirm_email_with_another_user_logged_in(self):
"""Test the email confirmation view. If User B clicks on an email
verification link while logged in as User A, ensure User A gets
logged out."""
user = get_user_model().objects.create_user(
username="john", email="john@example.org", password="doe"
)
self.client.force_login(user)
self.client.post(
reverse("account_email"), {"email": user.email, "action_send": ""}
)
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].to, [user.email])
self.client.logout()
body = mail.outbox[0].body
self.assertGreater(body.find("https://"), 0)
user2 = self._create_user(username="john2", email="john2@example.com")
EmailAddress.objects.create(
user=user2, email=user2.email, primary=True, verified=True
)
resp = self.client.post(
reverse("account_login"),
{
"login": user2.email,
"password": "doe",
},
)
self.assertEqual(user2, resp.context["user"])
url = body[body.find("/confirm-email/") :].split()[0]
resp = self.client.post(url)
self.assertTemplateUsed(resp, "account/messages/logged_out.txt")
self.assertTemplateUsed(resp, "account/messages/email_confirmed.txt")
self.assertRedirects(resp, settings.LOGIN_URL, fetch_redirect_response=False)
@override_settings(
ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.EMAIL