def test_excluded_application_ids(self):
     settings.OAUTH2_PROVIDER['REFRESH_TOKEN_EXPIRE_SECONDS'] = 3600
     expires = timezone.now() - timedelta(days=1)
     application = factories.ApplicationFactory()
     access_token = factories.AccessTokenFactory(user=application.user,
                                                 application=application,
                                                 expires=expires)
     factories.RefreshTokenFactory(user=application.user,
                                   application=application,
                                   access_token=access_token)
     with LogCapture(LOGGER_NAME) as log:
         call_command('edx_clear_expired_tokens',
                      sleep_time=0,
                      excluded_application_ids=str(application.id))
         log.check(
             (LOGGER_NAME, 'INFO', 'Cleaning {} rows from {} table'.format(
                 0, RefreshToken.__name__)), (
                     LOGGER_NAME,
                     'INFO',
                     'Cleaning {} rows from {} table'.format(
                         0, AccessToken.__name__),
                 ), (
                     LOGGER_NAME,
                     'INFO',
                     'Cleaning 0 rows from Grant table',
                 ))
     self.assertTrue(
         RefreshToken.objects.filter(application=application).exists())
 def test_clear_expired_tokens(self):
     settings.OAUTH2_PROVIDER['REFRESH_TOKEN_EXPIRE_SECONDS'] = 3600
     initial_count = 5
     now = timezone.now()
     expires = now - timedelta(days=1)
     users = UserFactory.create_batch(initial_count)
     for user in users:
         application = factories.ApplicationFactory(user=user)
         factories.AccessTokenFactory(user=user,
                                      application=application,
                                      expires=expires)
     self.assertEqual(
         AccessToken.objects.filter(refresh_token__isnull=True,
                                    expires__lt=now).count(), initial_count)
     original_delete = QuerySet.delete
     QuerySet.delete = counter(QuerySet.delete)
     try:
         call_command('edx_clear_expired_tokens',
                      batch_size=1,
                      sleep_time=0)
         self.assertEqual(QuerySet.delete.invocations, initial_count)
         self.assertEqual(
             AccessToken.objects.filter(refresh_token__isnull=True,
                                        expires__lt=now).count(), 0)
     finally:
         QuerySet.delete = original_delete
Exemple #3
0
    def test_delete_dot_models(self):
        user = UserFactory.create()
        app = factories.ApplicationFactory(user=user)
        access_token = factories.AccessTokenFactory(user=user, application=app)
        factories.RefreshTokenFactory(
            user=user,
            application=app,
            access_token=access_token,
        )
        DOTGrant.objects.create(
            user=user,
            application=app,
            expires=datetime.datetime(2018, 1, 1),
        )

        retire_dot_oauth2_models(user)

        applications = DOTApplication.objects.filter(user_id=user.id)
        access_tokens = DOTAccessToken.objects.filter(user_id=user.id)
        refresh_tokens = DOTRefreshToken.objects.filter(user_id=user.id)
        grants = DOTGrant.objects.filter(user=user)

        query_sets = [applications, access_tokens, refresh_tokens, grants]

        for query_set in query_sets:
            self.assertFalse(query_set.exists())
    def test_reset_password_email(self, body_type, expected_output):
        """Tests contents of reset password email, and that user is not active"""
        good_req = self.request_factory.post('/password_reset/',
                                             {'email': self.user.email})
        good_req.user = self.user
        good_req.site = Mock(domain='example.com')
        dot_application = dot_factories.ApplicationFactory(user=self.user)
        dot_access_token = dot_factories.AccessTokenFactory(
            user=self.user, application=dot_application)
        dot_factories.RefreshTokenFactory(user=self.user,
                                          application=dot_application,
                                          access_token=dot_access_token)
        good_resp = password_reset(good_req)
        assert good_resp.status_code == 200
        assert not dot_models.AccessToken.objects.filter(
            user=self.user).exists()
        assert not dot_models.RefreshToken.objects.filter(
            user=self.user).exists()
        obj = json.loads(good_resp.content.decode('utf-8'))
        assert obj['success']
        assert 'e-mailed you instructions for setting your password' in obj[
            'value']

        from_email = configuration_helpers.get_value(
            'email_from_address', settings.DEFAULT_FROM_EMAIL)
        sent_message = mail.outbox[0]

        bodies = {
            'plain_text': sent_message.body,
            'html': sent_message.alternatives[0][0],
        }

        body = bodies[body_type]

        if django.VERSION >= (3, 0) and body_type == 'html':
            expected_output = "You're receiving this e-mail because you requested a password reset"

        assert 'Password reset' in sent_message.subject
        assert expected_output in body
        assert sent_message.from_email == from_email
        assert len(sent_message.to) == 1
        assert self.user.email in sent_message.to

        self.assert_event_emitted(
            SETTING_CHANGE_INITIATED,
            user_id=self.user.id,
            setting='password',
            old=None,
            new=None,
        )

        # Test that the user is not active
        self.user = User.objects.get(pk=self.user.pk)
        assert not self.user.is_active

        assert 'password_reset_confirm/' in body
        re.search(
            r'password_reset_confirm/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/',
            body).groupdict()
Exemple #5
0
    def _create_dot_tokens(self, user=None):
        """Create dop access token for given user if user provided else for default user."""
        if not user:
            user = User.objects.get(email=self.OLD_EMAIL)

        application = dot_factories.ApplicationFactory(user=user)
        access_token = dot_factories.AccessTokenFactory(user=user, application=application)
        dot_factories.RefreshTokenFactory(user=user, application=application, access_token=access_token)
 def _create_dot_access_token(self, grant_type='Client credentials'):
     """
     Create dot based access token
     """
     dot_application = dot_factories.ApplicationFactory(
         user=self.user, authorization_grant_type=grant_type)
     return dot_factories.AccessTokenFactory(user=self.user,
                                             application=dot_application)
Exemple #7
0
 def test_refresh_token_factory(self):
     application = factories.ApplicationFactory(user=self.user)
     access_token = factories.AccessTokenFactory(user=self.user, application=application)
     actual_refresh_token = factories.RefreshTokenFactory(
         user=self.user, application=application, access_token=access_token
     )
     expected_refresh_token = RefreshToken.objects.get(user=self.user, access_token=access_token)
     self.assertEqual(actual_refresh_token, expected_refresh_token)
    def test_reset_password_email(self, body_type, expected_output):
        """Tests contents of reset password email, and that user is not active"""
        good_req = self.request_factory.post('/password_reset/',
                                             {'email': self.user.email})
        good_req.user = self.user
        good_req.site = Mock(domain='example.com')
        dot_application = dot_factories.ApplicationFactory(user=self.user)
        dot_access_token = dot_factories.AccessTokenFactory(
            user=self.user, application=dot_application)
        dot_factories.RefreshTokenFactory(user=self.user,
                                          application=dot_application,
                                          access_token=dot_access_token)
        good_resp = password_reset(good_req)
        self.assertEqual(good_resp.status_code, 200)
        self.assertFalse(
            dot_models.AccessToken.objects.filter(user=self.user).exists())
        self.assertFalse(
            dot_models.RefreshToken.objects.filter(user=self.user).exists())
        obj = json.loads(good_resp.content.decode('utf-8'))
        self.assertTrue(obj['success'])
        self.assertIn('e-mailed you instructions for setting your password',
                      obj['value'])

        from_email = configuration_helpers.get_value(
            'email_from_address', settings.DEFAULT_FROM_EMAIL)
        sent_message = mail.outbox[0]

        bodies = {
            'plain_text': sent_message.body,
            'html': sent_message.alternatives[0][0],
        }

        body = bodies[body_type]

        self.assertIn("Password reset", sent_message.subject)
        self.assertIn(expected_output, body)
        self.assertEqual(sent_message.from_email, from_email)
        self.assertEqual(len(sent_message.to), 1)
        self.assertIn(self.user.email, sent_message.to)

        self.assert_event_emitted(
            SETTING_CHANGE_INITIATED,
            user_id=self.user.id,
            setting=u'password',
            old=None,
            new=None,
        )

        # Test that the user is not active
        self.user = User.objects.get(pk=self.user.pk)
        self.assertFalse(self.user.is_active)

        self.assertIn('password_reset_confirm/', body)
        re.search(
            r'password_reset_confirm/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/',
            body).groupdict()
Exemple #9
0
    def test_reset_password_email(self, send_email):
        """
        Tests contents of reset password email, and that user is not active
        """

        good_req = self.request_factory.post('/password_reset/', {'email': self.user.email})
        good_req.user = self.user
        dop_client = ClientFactory()
        dop_access_token = AccessTokenFactory(user=self.user, client=dop_client)
        RefreshTokenFactory(user=self.user, client=dop_client, access_token=dop_access_token)
        dot_application = dot_factories.ApplicationFactory(user=self.user)
        dot_access_token = dot_factories.AccessTokenFactory(user=self.user, application=dot_application)
        dot_factories.RefreshTokenFactory(user=self.user, application=dot_application, access_token=dot_access_token)
        good_resp = password_reset(good_req)
        self.assertEquals(good_resp.status_code, 200)
        self.assertFalse(dop_models.AccessToken.objects.filter(user=self.user).exists())
        self.assertFalse(dop_models.RefreshToken.objects.filter(user=self.user).exists())
        self.assertFalse(dot_models.AccessToken.objects.filter(user=self.user).exists())
        self.assertFalse(dot_models.RefreshToken.objects.filter(user=self.user).exists())
        obj = json.loads(good_resp.content)
        self.assertEquals(obj, {
            'success': True,
            'value': "('registration/password_reset_done.html', [])",
        })

        (subject, msg, from_addr, to_addrs) = send_email.call_args[0]
        self.assertIn("Password reset", subject)
        self.assertIn("You're receiving this e-mail because you requested a password reset", msg)
        self.assertEquals(from_addr, configuration_helpers.get_value('email_from_address', settings.DEFAULT_FROM_EMAIL))
        self.assertEquals(len(to_addrs), 1)
        self.assertIn(self.user.email, to_addrs)

        self.assert_event_emitted(
            SETTING_CHANGE_INITIATED, user_id=self.user.id, setting=u'password', old=None, new=None,
        )

        #test that the user is not active
        self.user = User.objects.get(pk=self.user.pk)
        self.assertFalse(self.user.is_active)
        re.search(r'password_reset_confirm/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/', msg).groupdict()
Exemple #10
0
 def test_access_token_client_factory(self):
     application = factories.ApplicationFactory(user=self.user)
     actual_access_token = factories.AccessTokenFactory(
         user=self.user, application=application)
     expected_access_token = AccessToken.objects.get(user=self.user)
     self.assertEqual(actual_access_token, expected_access_token)