示例#1
0
class TestAccountDeactivation(TestCase):
    """
    Tests the account deactivation endpoint.
    """
    def setUp(self):
        super(TestAccountDeactivation, self).setUp()
        self.superuser = SuperuserFactory()
        self.staff_user = AdminFactory()
        self.test_user = UserFactory()
        self.url = reverse('accounts_deactivation',
                           kwargs={'username': self.test_user.username})

    def assert_activation_status(self,
                                 expected_status=status.HTTP_200_OK,
                                 expected_activation_status=False):
        """
        Helper function for making a request to the deactivation endpoint, and asserting the status.

        Args:
            expected_status(int): Expected request's response status.
            expected_activation_status(bool): Expected user has_usable_password attribute value.
        """
        response = self.client.post(self.url)
        self.assertEqual(response.status_code, expected_status)
        self.test_user.refresh_from_db()  # pylint: disable=no-member
        self.assertEqual(self.test_user.has_usable_password(),
                         expected_activation_status)  # pylint: disable=no-member

    def test_superuser_deactivates_user(self):
        """
        Verify a user is deactivated when a superuser posts to the deactivation endpoint.
        """
        self.client.login(username=self.superuser.username,
                          password=TEST_PASSWORD)
        self.assertTrue(self.test_user.has_usable_password())  # pylint: disable=no-member
        self.assert_activation_status()

    def test_user_with_permission_deactivates_user(self):
        """
        Verify a user is deactivated when a user with permission posts to the deactivation endpoint.
        """
        user = UserFactory()
        permission = PermissionFactory(
            codename='can_deactivate_users',
            content_type=ContentTypeFactory(app_label='student'))
        user.user_permissions.add(permission)  # pylint: disable=no-member
        self.client.login(username=user.username, password=TEST_PASSWORD)
        self.assertTrue(self.test_user.has_usable_password())  # pylint: disable=no-member
        self.assert_activation_status()

    def test_unauthorized_rejection(self):
        """
        Verify unauthorized users cannot deactivate accounts.
        """
        self.client.login(username=self.test_user.username,
                          password=TEST_PASSWORD)
        self.assertTrue(self.test_user.has_usable_password())  # pylint: disable=no-member
        self.assert_activation_status(
            expected_status=status.HTTP_403_FORBIDDEN,
            expected_activation_status=True)
示例#2
0
class TestAccountDeactivation(TestCase):
    """
    Tests the account deactivation endpoint.
    """
    def setUp(self):
        super(TestAccountDeactivation, self).setUp()
        self.test_user = UserFactory()
        self.url = reverse('accounts_deactivation',
                           kwargs={'username': self.test_user.username})

    def build_jwt_headers(self, user):
        """
        Helper function for creating headers for the JWT authentication.
        """
        token = JwtBuilder(user).build_token([])
        headers = {'HTTP_AUTHORIZATION': 'JWT ' + token}
        return headers

    def assert_activation_status(self,
                                 headers,
                                 expected_status=status.HTTP_200_OK,
                                 expected_activation_status=False):
        """
        Helper function for making a request to the deactivation endpoint, and asserting the status.

        Args:
            expected_status(int): Expected request's response status.
            expected_activation_status(bool): Expected user has_usable_password attribute value.
        """
        self.assertTrue(self.test_user.has_usable_password())  # pylint: disable=no-member
        response = self.client.post(self.url, **headers)
        self.assertEqual(response.status_code, expected_status)
        self.test_user.refresh_from_db()  # pylint: disable=no-member
        self.assertEqual(self.test_user.has_usable_password(),
                         expected_activation_status)  # pylint: disable=no-member

    def test_superuser_deactivates_user(self):
        """
        Verify a user is deactivated when a superuser posts to the deactivation endpoint.
        """
        superuser = SuperuserFactory()
        headers = self.build_jwt_headers(superuser)
        self.assert_activation_status(headers)

    def test_user_with_permission_deactivates_user(self):
        """
        Verify a user is deactivated when a user with permission posts to the deactivation endpoint.
        """
        user = UserFactory()
        permission = PermissionFactory(
            codename='can_deactivate_users',
            content_type=ContentTypeFactory(app_label='student'))
        user.user_permissions.add(permission)  # pylint: disable=no-member
        headers = self.build_jwt_headers(user)
        self.assertTrue(self.test_user.has_usable_password())  # pylint: disable=no-member
        self.assert_activation_status(headers)

    def test_unauthorized_rejection(self):
        """
        Verify unauthorized users cannot deactivate accounts.
        """
        headers = self.build_jwt_headers(self.test_user)
        self.assert_activation_status(
            headers,
            expected_status=status.HTTP_403_FORBIDDEN,
            expected_activation_status=True)

    def test_on_jwt_headers_rejection(self):
        """
        Verify users who are not JWT authenticated are rejected.
        """
        user = UserFactory()
        self.assert_activation_status(
            {},
            expected_status=status.HTTP_401_UNAUTHORIZED,
            expected_activation_status=True)
示例#3
0
class TestRemoveSocialAuthUsersCommand(TestCase):
    """
    Test django management command
    """
    @classmethod
    def setUpClass(cls):
        super(TestRemoveSocialAuthUsersCommand, cls).setUpClass()
        cls.command = remove_social_auth_users.Command()

    def setUp(self):
        super(TestRemoveSocialAuthUsersCommand, self).setUp()
        self.provider_hogwarts = SAMLProviderConfigFactory.create(
            slug='hogwarts')
        self.provider_durmstrang = SAMLProviderConfigFactory.create(
            slug='durmstrang')

        self.user_fleur = UserFactory(username='******')  # no social auth
        self.user_harry = UserFactory(
            username='******')  # social auth for Hogwarts
        self.user_viktor = UserFactory(
            username='******')  # social auth for Durmstrang

        self.create_social_auth_entry(self.user_harry, self.provider_hogwarts)
        self.create_social_auth_entry(self.user_viktor,
                                      self.provider_durmstrang)

    @contextmanager
    def _replace_stdin(self, text):
        orig = sys.stdin
        sys.stdin = StringIO(text)
        yield
        sys.stdin = orig

    def create_social_auth_entry(self, user, provider):
        external_id = uuid4()
        UserSocialAuth.objects.create(
            user=user,
            uid='{0}:{1}'.format(provider.slug, external_id),
            provider=provider.slug,
        )

    def find_user_social_auth_entry(self, username):
        UserSocialAuth.objects.get(user__username=username)

    @override_settings(FEATURES=FEATURES_WITH_ENABLED)
    def test_remove_users(self):
        call_command(self.command, self.provider_hogwarts.slug, force=True)

        # user with input idp is removed, along with social auth entries
        with self.assertRaises(User.DoesNotExist):
            User.objects.get(username='******')
        with self.assertRaises(UserSocialAuth.DoesNotExist):
            self.find_user_social_auth_entry('harry')

        # other users intact
        self.user_fleur.refresh_from_db()
        self.user_viktor.refresh_from_db()
        self.assertIsNotNone(self.user_fleur)
        self.assertIsNotNone(self.user_viktor)

        # other social auth intact
        self.find_user_social_auth_entry(self.user_viktor.username)

    @override_settings(FEATURES=FEATURES_WITH_ENABLED)
    def test_invalid_idp(self):
        invalid_slug = 'jedi-academy'
        err_string = u'No SAML provider found for slug {}'.format(invalid_slug)
        with self.assertRaisesRegexp(CommandError, err_string):
            call_command(self.command, invalid_slug)

    @override_settings(FEATURES=FEATURES_WITH_ENABLED)
    def test_confirmation_required(self):
        """ By default this command will require user input to confirm """
        with self._replace_stdin('confirm'):
            call_command(self.command, self.provider_hogwarts.slug)

        with self.assertRaises(User.DoesNotExist):
            User.objects.get(username='******')
        with self.assertRaises(UserSocialAuth.DoesNotExist):
            self.find_user_social_auth_entry('harry')

    @override_settings(FEATURES=FEATURES_WITH_ENABLED)
    def test_confirmation_failure(self):
        err_string = 'User confirmation required.  No records have been modified'
        with self.assertRaisesRegexp(CommandError, err_string):
            with self._replace_stdin('no'):
                call_command(self.command, self.provider_hogwarts.slug)

        # no users should be removed
        self.assertEqual(len(User.objects.all()), 3)
        self.assertEqual(len(UserSocialAuth.objects.all()), 2)

    def test_feature_default_disabled(self):
        """ By default this command should not be enabled """
        err_string = 'ENABLE_ENROLLMENT_RESET feature not enabled on this enviroment'
        with self.assertRaisesRegexp(CommandError, err_string):
            call_command(self.command, self.provider_hogwarts.slug, force=True)
示例#4
0
class TestAccountDeactivation(TestCase):
    """
    Tests the account deactivation endpoint.
    """

    def setUp(self):
        super(TestAccountDeactivation, self).setUp()
        self.test_user = UserFactory()
        self.url = reverse('accounts_deactivation', kwargs={'username': self.test_user.username})

    def build_jwt_headers(self, user):
        """
        Helper function for creating headers for the JWT authentication.
        """
        token = JwtBuilder(user).build_token([])
        headers = {
            'HTTP_AUTHORIZATION': 'JWT ' + token
        }
        return headers

    def assert_activation_status(self, headers, expected_status=status.HTTP_200_OK, expected_activation_status=False):
        """
        Helper function for making a request to the deactivation endpoint, and asserting the status.

        Args:
            expected_status(int): Expected request's response status.
            expected_activation_status(bool): Expected user has_usable_password attribute value.
        """
        self.assertTrue(self.test_user.has_usable_password())  # pylint: disable=no-member
        response = self.client.post(self.url, **headers)
        self.assertEqual(response.status_code, expected_status)
        self.test_user.refresh_from_db()  # pylint: disable=no-member
        self.assertEqual(self.test_user.has_usable_password(), expected_activation_status)  # pylint: disable=no-member

    def test_superuser_deactivates_user(self):
        """
        Verify a user is deactivated when a superuser posts to the deactivation endpoint.
        """
        superuser = SuperuserFactory()
        headers = self.build_jwt_headers(superuser)
        self.assert_activation_status(headers)

    def test_user_with_permission_deactivates_user(self):
        """
        Verify a user is deactivated when a user with permission posts to the deactivation endpoint.
        """
        user = UserFactory()
        permission = PermissionFactory(
            codename='can_deactivate_users',
            content_type=ContentTypeFactory(
                app_label='student'
            )
        )
        user.user_permissions.add(permission)  # pylint: disable=no-member
        headers = self.build_jwt_headers(user)
        self.assertTrue(self.test_user.has_usable_password())  # pylint: disable=no-member
        self.assert_activation_status(headers)

    def test_unauthorized_rejection(self):
        """
        Verify unauthorized users cannot deactivate accounts.
        """
        headers = self.build_jwt_headers(self.test_user)
        self.assert_activation_status(
            headers,
            expected_status=status.HTTP_403_FORBIDDEN,
            expected_activation_status=True
        )

    def test_on_jwt_headers_rejection(self):
        """
        Verify users who are not JWT authenticated are rejected.
        """
        user = UserFactory()
        self.assert_activation_status(
            {},
            expected_status=status.HTTP_401_UNAUTHORIZED,
            expected_activation_status=True
        )