tests.py 42.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
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.test.client import Client, RequestFactory
from django.test.utils import override_settings
16
from django.urls import reverse
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
from django.utils.timezone import now

from allauth.account.forms import BaseSignupForm, 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_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_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().process_request(request)
        MessageMiddleware().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_login_redirect_url(request))
        self.assertEqual(len(mail.outbox), 0)
        return get_user_model().objects.get(username=username)

    @override_settings(
        ACCOUNT_USERNAME_REQUIRED=True,
137
        ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE=True)
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
    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().process_request(request)
        MessageMiddleware().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'):
        user = get_user_model().objects.create(
            username=username,
            is_active=True)
        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)
187
        self.client.force_login(user)
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
        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)

211 212 213 214 215 216 217 218 219 220 221 222 223
    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)

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
    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

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
    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'])

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
    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]

381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
    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)

401 402 403 404 405 406 407 408 409 410 411 412
    @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'})
413
        self.assertTrue(user.is_authenticated)
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
        # 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',
                 '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.')

    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)
    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',
                       'password2': 'johndoe'})
        # Logged in
        self.assertRedirects(resp,
                             settings.LOGIN_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'))


class EmailFormTests(TestCase):

    def setUp(self):
        User = get_user_model()
        self.user = User.objects.create(username='john',
                                        email="john1@example.org")
        self.user.set_password('doe')
        self.user.save()
        self.email_address = EmailAddress.objects.create(
            user=self.user,
            email=self.user.email,
            verified=True,
            primary=True)
        self.email_address2 = EmailAddress.objects.create(
            user=self.user,
            email="john2@example.org",
            verified=False,
            primary=False)
        self.client.login(username='john', password='doe')

    def test_add(self):
        resp = self.client.post(
            reverse('account_email'),
            {'action_add': '',
             'email': 'john3@example.org'})
        EmailAddress.objects.get(
            email="john3@example.org",
            user=self.user,
            verified=False,
            primary=False)
        self.assertTemplateUsed(resp,
                                'account/messages/email_confirmation_sent.txt')

    def test_ajax_get(self):
        resp = self.client.get(
            reverse('account_email'),
            HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        data = json.loads(resp.content.decode('utf8'))
        assert data['data'] == [
824 825
            {'id': self.email_address.pk,
             'email': 'john1@example.org',
826 827
             'primary': True,
             'verified': True},
828 829
            {'id': self.email_address2.pk,
             'email': 'john2@example.org',
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
             'primary': False,
             'verified': False}]

    def test_ajax_add(self):
        resp = self.client.post(
            reverse('account_email'),
            {'action_add': '',
             'email': 'john3@example.org'},
            HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        data = json.loads(resp.content.decode('utf8'))
        self.assertEqual(data['location'],
                         reverse('account_email'))

    def test_ajax_add_invalid(self):
        resp = self.client.post(
            reverse('account_email'),
            {'action_add': '',
             'email': 'john3#example.org'},
            HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        data = json.loads(resp.content.decode('utf8'))
        assert 'valid' in data['form']['fields']['email']['errors'][0]

    def test_remove_primary(self):
        resp = self.client.post(
            reverse('account_email'),
            {'action_remove': '',
             'email': self.email_address.email})
        EmailAddress.objects.get(pk=self.email_address.pk)
        self.assertTemplateUsed(
            resp,
            'account/messages/cannot_delete_primary_email.txt')

    def test_ajax_remove_primary(self):
        resp = self.client.post(
            reverse('account_email'),
            {'action_remove': '',
             'email': self.email_address.email},
            HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertTemplateUsed(
            resp,
            'account/messages/cannot_delete_primary_email.txt')
        data = json.loads(resp.content.decode('utf8'))
        self.assertEqual(data['location'],
                         reverse('account_email'))

    def test_remove_secondary(self):
        resp = self.client.post(
            reverse('account_email'),
            {'action_remove': '',
             'email': self.email_address2.email})
        self.assertRaises(EmailAddress.DoesNotExist,
                          lambda: EmailAddress.objects.get(
                              pk=self.email_address2.pk))
        self.assertTemplateUsed(
            resp,
            'account/messages/email_deleted.txt')

    def test_set_primary_unverified(self):
        resp = self.client.post(
            reverse('account_email'),
            {'action_primary': '',
             'email': self.email_address2.email})
        email_address = EmailAddress.objects.get(pk=self.email_address.pk)
        email_address2 = EmailAddress.objects.get(pk=self.email_address2.pk)
        self.assertFalse(email_address2.primary)
        self.assertTrue(email_address.primary)
        self.assertTemplateUsed(
            resp,
            'account/messages/unverified_primary_email.txt')

    def test_set_primary(self):
        email_address2 = EmailAddress.objects.get(pk=self.email_address2.pk)
        email_address2.verified = True
        email_address2.save()
        resp = self.client.post(
            reverse('account_email'),
            {'action_primary': '',
             'email': self.email_address2.email})
        email_address = EmailAddress.objects.get(pk=self.email_address.pk)
        email_address2 = EmailAddress.objects.get(pk=self.email_address2.pk)
        self.assertFalse(email_address.primary)
        self.assertTrue(email_address2.primary)
        self.assertTemplateUsed(
            resp,
            'account/messages/primary_email_set.txt')

    def test_verify(self):
        resp = self.client.post(
            reverse('account_email'),
            {'action_send': '',
             'email': self.email_address2.email})
        self.assertTemplateUsed(
            resp,
            'account/messages/email_confirmation_sent.txt')


class BaseSignupFormTests(TestCase):

    @override_settings(
        ACCOUNT_USERNAME_REQUIRED=True,
        ACCOUNT_USERNAME_BLACKLIST=['username'])
    def test_username_in_blacklist(self):
        data = {
            'username': 'username',
            'email': 'user@example.com',
        }
        form = BaseSignupForm(data, email_required=True)
        self.assertFalse(form.is_valid())

    @override_settings(
        ACCOUNT_USERNAME_REQUIRED=True,
        ACCOUNT_USERNAME_BLACKLIST=['username'])
    def test_username_not_in_blacklist(self):
        data = {
            'username': 'theusername',
            'email': 'user@example.com',
        }
        form = BaseSignupForm(data, email_required=True)
        self.assertTrue(form.is_valid())

    @override_settings(ACCOUNT_USERNAME_REQUIRED=True)
    def test_username_maxlength(self):
        data = {
            'username': 'username',
            'email': 'user@example.com',
        }
        form = BaseSignupForm(data, email_required=True)
        max_length = get_username_max_length()
        field = form.fields['username']
        self.assertEqual(field.max_length, max_length)
        widget = field.widget
        self.assertEqual(widget.attrs.get('maxlength'), str(max_length))

    @override_settings(
        ACCOUNT_USERNAME_REQUIRED=True,
        ACCOUNT_SIGNUP_EMAIL_ENTER_TWICE=True)
    def test_signup_email_verification(self):
        data = {
            'username': 'username',
            'email': 'user@example.com',
        }
        form = BaseSignupForm(data, email_required=True)
        self.assertFalse(form.is_valid())

        data = {
            'username': 'username',
            'email': 'user@example.com',
            'email2': 'user@example.com',
        }
        form = BaseSignupForm(data, email_required=True)
        self.assertTrue(form.is_valid())

        data['email2'] = 'anotheruser@example.com'
        form = BaseSignupForm(data, email_required=True)
        self.assertFalse(form.is_valid())


class CustomSignupFormTests(TestCase):

    @override_settings(
        ACCOUNT_SIGNUP_EMAIL_ENTER_TWICE=True,
        ACCOUNT_SIGNUP_PASSOWRD_ENTER_TWICE=True)
    def test_custom_form_field_order(self):

        expected_field_order = [
            'email',
            'email2',
            'password1',
            'password2',
            'username',
            'last_name',
            'first_name'
        ]

        class TestSignupForm(forms.Form):
            first_name = forms.CharField(max_length=30)
            last_name = forms.CharField(max_length=30)

            field_order = expected_field_order

        class CustomSignupForm(SignupForm, TestSignupForm):
            # ACCOUNT_SIGNUP_FORM_CLASS is only abided by when the
            # BaseSignupForm definition is loaded the first time on Django
            # startup. @override_settings() has therefore no effect.
            pass

        form = CustomSignupForm()
        self.assertEqual(list(form.fields.keys()), expected_field_order)


class AuthenticationBackendTests(TestCase):

    def setUp(self):
        user = get_user_model().objects.create(
            is_active=True,
            email='john@example.com',
            username='john')
        user.set_password(user.username)
        user.save()
        self.user = user

    @override_settings(
        ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.USERNAME)  # noqa
    def test_auth_by_username(self):
        user = self.user
        backend = AuthenticationBackend()
        self.assertEqual(
            backend.authenticate(
1038
                request=None,
1039 1040 1041 1042 1043
                username=user.username,
                password=user.username).pk,
            user.pk)
        self.assertEqual(
            backend.authenticate(
1044
                request=None,
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
                username=user.email,
                password=user.username),
            None)

    @override_settings(
        ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.EMAIL)  # noqa
    def test_auth_by_email(self):
        user = self.user
        backend = AuthenticationBackend()
        self.assertEqual(
            backend.authenticate(
1056
                request=None,
1057 1058 1059 1060 1061
                username=user.email,
                password=user.username).pk,
            user.pk)
        self.assertEqual(
            backend.authenticate(
1062
                request=None,
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
                username=user.username,
                password=user.username),
            None)

    @override_settings(
        ACCOUNT_AUTHENTICATION_METHOD=app_settings.AuthenticationMethod.USERNAME_EMAIL)  # noqa
    def test_auth_by_username_or_email(self):
        user = self.user
        backend = AuthenticationBackend()
        self.assertEqual(
            backend.authenticate(
1074
                request=None,
1075 1076 1077 1078 1079
                username=user.email,
                password=user.username).pk,
            user.pk)
        self.assertEqual(
            backend.authenticate(
1080
                request=None,
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
                username=user.username,
                password=user.username).pk,
            user.pk)


class UUIDUser(AbstractUser):
    id = models.UUIDField(
        primary_key=True, default=uuid.uuid4, editable=False
    )

    class Meta(AbstractUser.Meta):
        swappable = "AUTH_USER_MODEL"


class UtilsTests(TestCase):
    def setUp(self):
        self.user_id = uuid.uuid4().hex

    def test_url_str_to_pk_identifies_UUID_as_stringlike(self):
        with patch('allauth.account.utils.get_user_model') as mocked_gum:
            mocked_gum.return_value = UUIDUser
            self.assertEqual(url_str_to_user_pk(self.user_id),
                             self.user_id)

    def test_pk_to_url_string_identifies_UUID_as_stringlike(self):
        user = UUIDUser(
            is_active=True,
            email='john@example.com',
            username='john')
        self.assertEqual(user_pk_to_url_str(user), str(user.pk))

    @override_settings(ACCOUNT_PRESERVE_USERNAME_CASING=False)
    def test_username_lower_cased(self):
        user = get_user_model()()
        user_username(user, 'CamelCase')
        self.assertEqual(user_username(user), 'camelcase')
        # TODO: Actually test something
        filter_users_by_username('CamelCase', 'FooBar')

    @override_settings(ACCOUNT_PRESERVE_USERNAME_CASING=True)
    def test_username_case_preserved(self):
        user = get_user_model()()
        user_username(user, 'CamelCase')
        self.assertEqual(user_username(user), 'CamelCase')
        # TODO: Actually test something
        filter_users_by_username('camelcase', 'foobar')