Ejemplo n.º 1
0
    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='******', is_active=False)
        user.set_password('doe')
        user.save()
        EmailAddress.objects.create(user=user,
                                    email='*****@*****.**',
                                    primary=True,
                                    verified=True)
        resp = self.client.post(reverse('account_login'),
                                {'login': '******',
                                 'password': '******'})
        self.assertRedirects(resp, reverse('account_inactive'))

        # Inactive and unverified user account
        user = get_user_model().objects.create(username='******', is_active=False)
        user.set_password('john')
        user.save()
        EmailAddress.objects.create(user=user,
                                    email='*****@*****.**',
                                    primary=True,
                                    verified=False)
        resp = self.client.post(reverse('account_login'),
                                {'login': '******',
                                 'password': '******'})
        self.assertRedirects(resp, reverse('account_inactive'))
Ejemplo n.º 2
0
 def test_ajax_password_reset(self):
     get_user_model().objects.create(
         username='******', email='*****@*****.**', is_active=True)
     resp = self.client.post(
         reverse('account_reset_password'),
         data={'email': '*****@*****.**'},
         HTTP_X_REQUESTED_WITH='XMLHttpRequest')
     self.assertEqual(len(mail.outbox), 1)
     self.assertEqual(mail.outbox[0].to, ['*****@*****.**'])
     self.assertEqual(resp['content-type'], 'application/json')
Ejemplo n.º 3
0
 def test_login(self):
     with patch('users.socialaccount.providers.persona.views'
                '.requests') as requests_mock:
         requests_mock.post.return_value.json.return_value = {
             'status': 'okay',
             'email': '*****@*****.**'
         }
         resp = self.client.post(reverse('persona_login'),
                                 dict(assertion='dummy'))
         self.assertEqual('http://testserver/accounts/profile/',
                          resp['location'])
         get_user_model().objects.get(email='*****@*****.**')
Ejemplo n.º 4
0
 def get_users_with_multiple_primary_email(self):
     user_pks = []
     for email_address_dict in EmailAddress.objects.filter(
             primary=True).values('user').annotate(
                 Count('user')).filter(user__count__gt=1):
         user_pks.append(email_address_dict['user'])
     return get_user_model().objects.filter(pk__in=user_pks)
Ejemplo n.º 5
0
 def _logout_view(self, method):
     c = Client()
     user = get_user_model().objects.create(username='******', is_active=True)
     user.set_password('doe')
     user.save()
     c = Client()
     c.login(username='******', password='******')
     return c, getattr(c, method)(reverse('account_logout'))
Ejemplo n.º 6
0
 def setUp(self):
     user = get_user_model().objects.create(
         is_active=True,
         email='*****@*****.**',
         username='******')
     user.set_password(user.username)
     user.save()
     self.user = user
Ejemplo n.º 7
0
 def test_email_escaping(self):
     site = get_current_site()
     site.name = '<enc&"test>'
     site.save()
     u = get_user_model().objects.create(
         username='******',
         email='*****@*****.**')
     request = RequestFactory().get('/')
     EmailAddress.objects.add_email(request, u, u.email, confirm=True)
     self.assertTrue(mail.outbox[0].subject[1:].startswith(site.name))
Ejemplo n.º 8
0
 def test_ajax_login_success(self):
     user = get_user_model().objects.create(username='******', is_active=True)
     user.set_password('doe')
     user.save()
     resp = self.client.post(reverse('account_login'),
                             {'login': '******',
                              'password': '******'},
                             HTTP_X_REQUESTED_WITH='XMLHttpRequest')
     self.assertEqual(resp.status_code, 200)
     data = json.loads(resp.content.decode('utf8'))
     self.assertEqual(data['location'], '/accounts/profile/')
Ejemplo n.º 9
0
    def test_email_verification_mandatory(self):
        c = Client()
        # Signup
        resp = c.post(reverse('account_signup'),
                      {'username': '******',
                       'email': '*****@*****.**',
                       'password1': 'johndoe',
                       'password2': 'johndoe'},
                      follow=True)
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(mail.outbox[0].to, ['*****@*****.**'])
        self.assertGreater(mail.outbox[0].body.find('https://'), 0)
        self.assertEqual(len(mail.outbox), 1)
        self.assertTemplateUsed(resp,
                                'account/verification_sent.html')
        # Attempt to login, unverified
        for attempt in [1, 2]:
            resp = c.post(reverse('account_login'),
                          {'login': '******',
                           'password': '******'},
                          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='******', is_active=True).exists())

            self.assertTemplateUsed(resp,
                                    'account/verification_sent.html')
            # 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='*****@*****.**').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='******')[:1] \
            .get()
        resp = c.get(reverse('account_confirm_email',
                             args=[confirmation.key]))
        self.assertTemplateUsed(resp, 'account/email_confirm.html')
        c.post(reverse('account_confirm_email',
                       args=[confirmation.key]))
        resp = c.post(reverse('account_login'),
                      {'login': '******',
                       'password': '******'})
        self.assertEqual(resp['location'],
                         'http://testserver'+settings.LOGIN_REDIRECT_URL)
Ejemplo n.º 10
0
 def _request_new_password(self):
     user = get_user_model().objects.create(
         username='******', email='*****@*****.**', is_active=True)
     user.set_password('doe')
     user.save()
     self.client.post(
         reverse('account_reset_password'),
         data={'email': '*****@*****.**'})
     self.assertEqual(len(mail.outbox), 1)
     self.assertEqual(mail.outbox[0].to, ['*****@*****.**'])
     return user
Ejemplo n.º 11
0
 def test_username_containing_at(self):
     user = get_user_model().objects.create(username='******')
     user.set_password('psst')
     user.save()
     EmailAddress.objects.create(user=user,
                                 email='*****@*****.**',
                                 primary=True,
                                 verified=True)
     resp = self.client.post(reverse('account_login'),
                             {'login': '******',
                              'password': '******'})
     self.assertEqual(resp['location'],
                      'http://testserver'+settings.LOGIN_REDIRECT_URL)
Ejemplo n.º 12
0
    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)
        self.assertTemplateUsed(resp, 'account/password_reset_from_key.html')
        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.html')
        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.html')
        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'))
        self.assertTrue('form_errors' in data)
        self.assertTrue('__all__' in data['form_errors'])
Ejemplo n.º 13
0
 def test_login_unverified_account_optional(self):
     """Tests login behavior when email verification is optional."""
     user = get_user_model().objects.create(username='******')
     user.set_password('doe')
     user.save()
     EmailAddress.objects.create(user=user,
                                 email='*****@*****.**',
                                 primary=True,
                                 verified=False)
     resp = self.client.post(reverse('account_login'),
                             {'login': '******',
                              'password': '******'})
     self.assertEqual(resp['location'],
                      'http://testserver'+settings.LOGIN_REDIRECT_URL)
Ejemplo n.º 14
0
 def test_login_unverified_account_mandatory(self):
     """Tests login behavior when email verification is mandatory."""
     user = get_user_model().objects.create(username='******')
     user.set_password('doe')
     user.save()
     EmailAddress.objects.create(user=user,
                                 email='*****@*****.**',
                                 primary=True,
                                 verified=False)
     resp = self.client.post(reverse('account_login'),
                             {'login': '******',
                              'password': '******'})
     self.assertRedirects(resp, reverse('account_email_verification_sent'))
     self.assertEqual(resp['location'],
                      'http://testserver' + reverse('account_email_verification_sent'))
Ejemplo n.º 15
0
 def setUp(self):
     User = get_user_model()
     self.user = User.objects.create(username='******',
                                     email='*****@*****.**')
     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='*****@*****.**',
         verified=False,
         primary=False)
     self.client.login(username='******', password='******')
Ejemplo n.º 16
0
 def deserialize(cls, data):
     account = deserialize_instance(SocialAccount, data['account'])
     user = deserialize_instance(get_user_model(), data['user'])
     if 'token' in data:
         token = deserialize_instance(SocialToken, data['token'])
     else:
         token = None
     email_addresses = []
     for ea in data['email_addresses']:
         # email_address = deserialize_instance(EmailAddress, ea)
         email_address = deserialize_instance(user.email, ea)
         email_addresses.append(email_address)
     ret = SocialLogin()
     ret.token = token
     ret.account = account
     ret.user = user
     ret.email_addresses = email_addresses
     ret.state = data['state']
     return ret
Ejemplo n.º 17
0
 def _test_signup_email_verified_externally(self, signup_email,
                                            verified_email):
     username = '******'
     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)
Ejemplo n.º 18
0
 def test_username_conflict(self):
     User = get_user_model()
     User.objects.create(username='******')
     self.login(self.get_mocked_response())
     socialaccount = SocialAccount.objects.get(uid='630595557')
     self.assertEqual(socialaccount.user.username, 'raymond')
Ejemplo n.º 19
0
 def _create_user_and_login(self):
     user = get_user_model().objects.create(username='******', is_active=True)
     user.set_password('doe')
     user.save()
     self.client.login(username='******', password='******')
     return user