Python rest_framework.status.HTTP_403_FORBIDDEN Examples

The following are 30 code examples for showing how to use rest_framework.status.HTTP_403_FORBIDDEN(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module rest_framework.status , or try the search function .

Example 1
Project: normandy   Author: mozilla   File: views.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def add_user(self, request, pk=None):
        group = self.get_object()

        if not request.data.get("user_id"):
            return Response(
                {"user_id": "This field is required."}, status=status.HTTP_400_BAD_REQUEST
            )

        try:
            user = User.objects.get(pk=request.data.get("user_id"))
        except User.DoesNotExist:
            return Response({"user_id": "Invalid user ID."}, status=status.HTTP_400_BAD_REQUEST)

        if request.user == user:
            return Response(status=status.HTTP_403_FORBIDDEN)

        user.groups.add(group)

        return Response(status=status.HTTP_204_NO_CONTENT) 
Example 2
Project: normandy   Author: mozilla   File: views.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def approve(self, request, pk=None):
        approval_request = self.get_object()

        if not request.data.get("comment"):
            return Response(
                {"comment": "This field is required."}, status=status.HTTP_400_BAD_REQUEST
            )

        try:
            approval_request.approve(approver=request.user, comment=request.data.get("comment"))
        except ApprovalRequest.NotActionable:
            return Response(
                {"error": "This approval request has already been approved or rejected."},
                status=status.HTTP_400_BAD_REQUEST,
            )
        except ApprovalRequest.CannotActOnOwnRequest:
            return Response(
                {"error": "You cannot approve your own approval request."},
                status=status.HTTP_403_FORBIDDEN,
            )

        return Response(ApprovalRequestSerializer(approval_request).data) 
Example 3
Project: normandy   Author: mozilla   File: views.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def reject(self, request, pk=None):
        approval_request = self.get_object()

        if not request.data.get("comment"):
            return Response(
                {"comment": "This field is required."}, status=status.HTTP_400_BAD_REQUEST
            )

        try:
            approval_request.reject(approver=request.user, comment=request.data.get("comment"))
        except ApprovalRequest.NotActionable:
            return Response(
                {"error": "This approval request has already been approved or rejected."},
                status=status.HTTP_400_BAD_REQUEST,
            )
        except ApprovalRequest.CannotActOnOwnRequest:
            return Response(
                {"error": "You cannot reject your own approval request."},
                status=status.HTTP_403_FORBIDDEN,
            )

        return Response(ApprovalRequestSerializer(approval_request).data) 
Example 4
Project: resolwe   Author: genialis   File: test_permissions.py    License: Apache License 2.0 6 votes vote down vote up
def test_public_user(self):
        """Public user cannot create/edit anything"""
        assign_perm("view_collection", self.user1, self.collection)
        assign_perm("share_collection", self.user1, self.collection)

        data = {"public": {"add": ["view"]}}
        resp = self._detail_permissions(self.collection.pk, data, self.user1)
        self.assertEqual(resp.status_code, status.HTTP_200_OK)

        data = {"public": {"add": ["edit"]}}
        resp = self._detail_permissions(self.collection.pk, data, self.user1)
        self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)

        data = {"public": {"remove": ["edit"]}}
        resp = self._detail_permissions(self.collection.pk, data, self.user1)
        self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) 
Example 5
Project: REST-API   Author: codingforentrepreneurs   File: tests.py    License: MIT License 6 votes vote down vote up
def test_token_register_api(self):
        url = api_reverse('api-auth:login')
        data = {
            'username': 'cfe',
            'password': 'yeahhhcfe',
        }
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK) # 400
        token = response.data.get("token", None)
        self.client.credentials(HTTP_AUTHORIZATION='JWT ' + token)

        url2 = api_reverse('api-auth:register')
        data2 = {
            'username': 'cfe.doe',
            'email': 'cfe.doe@gmail.com',
            'password': 'learncode',
            'password2': 'learncode'
        }
        response = self.client.post(url2, data2, format='json')
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) # 403 
Example 6
Project: REST-API   Author: codingforentrepreneurs   File: tests.py    License: MIT License 6 votes vote down vote up
def test_other_user_permissions_api(self):
        data            = self.create_item()
        data_id         = data.get("id")
        user            = User.objects.create(username='testjmitch')
        payload         = jwt_payload_handler(user)
        token           = jwt_encode_handler(payload)
        self.client.credentials(HTTP_AUTHORIZATION='JWT ' + token)
        rud_url         = api_reverse('api-status:detail', kwargs={"id": data_id})
        rud_data        = {
                            'content': "smashing"
                        }
        get_            = self.client.get(rud_url, format='json')
        put_            = self.client.put(rud_url, rud_data, format='json')
        delete_         = self.client.delete(rud_url, format='json')
        self.assertEqual(get_.status_code, status.HTTP_200_OK)
        self.assertEqual(put_.status_code, status.HTTP_403_FORBIDDEN)
        self.assertEqual(delete_.status_code, status.HTTP_403_FORBIDDEN) 
Example 7
Project: linkedevents   Author: City-of-Helsinki   File: test_event_auth_api.py    License: MIT License 6 votes vote down vote up
def test_regular_user_bulk_create(self):
        self.org_1.regular_users.add(self.user)
        url = reverse('event-list')
        location_id = reverse('place-detail', kwargs={'pk': self.place.id})
        data_1 = self.make_complex_event_dict(self.system_data_source, self.org_1, location_id, self.languages)
        data_1['name']['fi'] = 'event-data-1'
        data_1['publication_status'] = 'public'
        data_2 = deepcopy(data_1)
        data_2['name']['fi'] = 'event-data-2'
        data_2['publication_status'] = 'draft'

        self.client.force_authenticate(self.user)
        response = self.client.post(url, [data_1, data_2], format='json')
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

        # test creating multiple draft events
        data_1['publication_status'] = 'draft'
        self.client.force_authenticate(self.user)
        response = self.client.post(url, [data_1, data_2], format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        qs = Event.objects.filter(name_fi__in=['event-data-1', 'event-data-2'])
        self.assertEqual(qs.count(), 2) 
Example 8
def test_cannot_get_conversation_as_nonmember(self):
        self.client.force_login(user=self.user)

        # cannot get via activity
        response = self.client.get(self.conversation_url)
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

        # cannot get via conversation info
        conversation_id = self.activity.conversation.id
        response = self.client.get('/api/conversations/{}/'.format(conversation_id))
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

        # cannot write a message
        conversation_id = self.activity.conversation.id
        response = self.client.post('/api/messages/', {
            'conversation': conversation_id,
            'content': 'hey',
        })
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, response.data)
        self.assertEqual(response.data['detail'], 'You are not in this conversation') 
Example 9
Project: normandy   Author: mozilla   File: views.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def destroy(self, request, *args, **kwargs):
        instance = self.get_object()

        # Should not be able to delete self
        if request.user == instance:
            return Response(status=status.HTTP_403_FORBIDDEN)

        return super().destroy(request, *args, **kwargs) 
Example 10
Project: django-rest-registration   Author: apragacz   File: test_logout.py    License: MIT License 5 votes vote down vote up
def test_not_logged_in(self):
        request = self.create_post_request()
        self.add_session_to_request(request)
        response = self.view_func(request)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) 
Example 11
Project: django-rest-registration   Author: apragacz   File: test_change_password.py    License: MIT License 5 votes vote down vote up
def test_forbidden(self):
        request = self.create_post_request({})
        response = self.view_func(request)
        self.assert_invalid_response(response, status.HTTP_403_FORBIDDEN) 
Example 12
Project: resolwe   Author: genialis   File: test_collection.py    License: Apache License 2.0 5 votes vote down vote up
def test_patch_public_user(self):
        data = {"name": "New collection"}
        resp = self._patch(3, data)
        self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
        p = Collection.objects.get(pk=3)
        self.assertEqual(p.name, "Test collection 3") 
Example 13
Project: resolwe   Author: genialis   File: test_collection.py    License: Apache License 2.0 5 votes vote down vote up
def test_delete_public_user(self):
        resp = self._delete(3)
        self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
        collection_exists = Collection.objects.filter(pk=3).exists()
        self.assertTrue(collection_exists) 
Example 14
Project: resolwe   Author: genialis   File: test_data.py    License: Apache License 2.0 5 votes vote down vote up
def test_post_no_perms(self):
        collection = Collection.objects.get(pk=1)
        remove_perm("edit_collection", self.user2, collection)

        data_count = Data.objects.count()
        resp = self._post(self.data, self.user2)
        self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
        self.assertEqual(Data.objects.count(), data_count) 
Example 15
Project: resolwe   Author: genialis   File: test_data.py    License: Apache License 2.0 5 votes vote down vote up
def test_post_public_user(self):
        data_count = Data.objects.count()
        resp = self._post(self.data)
        # User has no permission to add Data object to the collection.
        self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
        self.assertEqual(Data.objects.count(), data_count) 
Example 16
Project: django-channels-chat   Author: narrowfail   File: test_api.py    License: MIT License 5 votes vote down vote up
def test_send_message_unauth(self):
        url = reverse('message-api-list')
        message = {'recipient': 'u1', 'body': 'No auth!'}
        response = self.client.post(url, message, format='json')
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) 
Example 17
Project: desec-stack   Author: desec-io   File: test_rrsets.py    License: MIT License 5 votes vote down vote up
def test_retrieve_my_rr_sets_restricted_types(self):
        for type_ in self.RESTRICTED_TYPES:
            response = self.client.get_rr_sets(self.my_domain.name, type=type_)
            self.assertStatus(response, status.HTTP_403_FORBIDDEN)
            response = self.client.get_rr_sets(self.my_domain.name, type=type_, subname='')
            self.assertStatus(response, status.HTTP_403_FORBIDDEN) 
Example 18
Project: desec-stack   Author: desec-io   File: test_domains.py    License: MIT License 5 votes vote down vote up
def test_domain_limit(self):
        url = self.reverse('v1:domain-list')
        user_quota = settings.LIMIT_USER_DOMAIN_COUNT_DEFAULT - self.NUM_OWNED_DOMAINS

        for i in range(user_quota):
            name = self.random_domain_name(self.AUTO_DELEGATION_DOMAINS)
            with self.assertPdnsRequests(self.requests_desec_domain_creation_auto_delegation(name)):
                response = self.client.post(url, {'name': name})
                self.assertStatus(response, status.HTTP_201_CREATED)

        response = self.client.post(url, {'name': self.random_domain_name(self.AUTO_DELEGATION_DOMAINS)})
        self.assertContains(response, 'Domain limit', status_code=status.HTTP_403_FORBIDDEN)
        self.assertFalse(mail.outbox)  # do not send email 
Example 19
Project: desec-stack   Author: desec-io   File: test_dyndns12update.py    License: MIT License 5 votes vote down vote up
def test_honor_minimum_ttl(self):
        self.my_domain.minimum_ttl = 61
        self.my_domain.save()
        response = self.assertDynDNS12NoUpdate(self.my_domain.name)
        self.assertStatus(response, status.HTTP_403_FORBIDDEN)
        self.assertEqual(response.data['detail'], 'Domain not eligible for dynamic updates, please contact support.') 
Example 20
Project: koku   Author: project-koku   File: test_views.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_endpoint_rbac_no_ous(self):
        """Test limited access results in only the account that the user can see."""
        url = reverse("aws-org-unit")
        response = self.client.get(url, **self.headers)
        accounts, ous = _calculate_accounts_and_subous(response.data.get("data"))
        self.assertEqual(ous, [])
        self.assertEqual(accounts, [])
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        # test that filtering on a specific ou that we don't have access to results
        # in a 403 error
        qs = "?filter[org_unit_id]=OU_001"
        url = reverse("aws-org-unit") + qs
        response = self.client.get(url, **self.headers)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) 
Example 21
Project: koku   Author: project-koku   File: test_views.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_execute_query_w_group_by_rbac_restricted_org_access(self):
        """Test that total account access/restricted org results in all accounts/ accessible orgs."""
        ou_to_account_subou_map = {
            "R_001": {"accounts": ["9999999999990"], "org_units": []},
            "OU_002": {"accounts": [], "org_units": ["OU_003"]},
            "OU_003": {"accounts": ["9999999999993"], "org_units": []},
            "OU_004": {"accounts": [], "org_units": []},
            "OU_005": {"accounts": [], "org_units": []},
        }
        for org_unit in list(ou_to_account_subou_map):
            qs = f"?group_by[org_unit_id]={org_unit}"
            url = reverse("reports-aws-costs") + qs
            response = self.client.get(url, **self.headers)
            accounts, sub_ous = _calculate_accounts_and_subous(response.data.get("data"))
            # These accounts are tied to this org unit inside of the
            # aws_org_tree.yml that populates the data for tests
            for account in ou_to_account_subou_map.get(org_unit).get("accounts"):
                self.assertIn(account, accounts)
            for ou in ou_to_account_subou_map.get(org_unit).get("org_units"):
                self.assertIn(ou, sub_ous)
            self.assertEqual(response.status_code, status.HTTP_200_OK)

        # test that OU_001 raises a 403
        qs = "?group_by[org_unit_id]=OU_001"
        url = reverse("reports-aws-costs") + qs
        response = self.client.get(url, **self.headers)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) 
Example 22
Project: koku   Author: project-koku   File: test_views.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_execute_query_w_group_by_rbac_no_accounts_or_orgs(self):
        """Test that no access to relevant results in a 403."""
        for org in ["R_001", "OU_001", "OU_002", "OU_003", "OU_004", "OU_005"]:
            qs = f"?group_by[org_unit_id]={org}"
            url = reverse("reports-aws-costs") + qs
            response = self.client.get(url, **self.headers)
            self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
            # test filters
            qs = f"?filter[org_unit_id]={org}"
            url = reverse("reports-aws-costs") + qs
            response = self.client.get(url, **self.headers)
            self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) 
Example 23
Project: koku   Author: project-koku   File: tests_views.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_rbacpermissions_invalid(self):
        """Test that endpoints reject invalid permissions."""
        for endpoint in self.ENDPOINTS:
            with self.subTest(endpoint=endpoint):
                url = reverse(endpoint)
                response = self.client.get(url, **self.headers)
                self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) 
Example 24
Project: koku   Author: project-koku   File: view.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self):
        """Initialize with status code 403."""
        self.status_code = status.HTTP_403_FORBIDDEN
        self.detail = {"detail": force_text(self.default_detail)} 
Example 25
Project: koku   Author: project-koku   File: tests_view.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_cost_model_rate_rbac_access(self):
        """Test GET /cost-models/{uuid} with an rbac user."""
        # Remove all sources with test cost model first.
        self.deassociate_sources_from_test_cost_model()

        # create a cost model
        user_data = self._create_user_data()
        customer = self._create_customer_data()

        admin_request_context = self._create_request_context(customer, user_data, create_customer=True, is_admin=True)

        url = reverse("cost-models-list")
        client = APIClient()
        with patch("masu.processor.tasks.update_cost_model_costs.delay"):
            response = client.post(url, data=self.fake_data, format="json", **admin_request_context["request"].META)
        cost_model_uuid = response.data.get("uuid")
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        user_data = self._create_user_data()

        request_context = self._create_request_context(customer, user_data, create_customer=False, is_admin=False)

        self.initialize_request(context={"request_context": request_context, "user_data": user_data})

        test_matrix = [
            {"access": {"rate": {"read": [], "write": []}}, "expected_response": status.HTTP_403_FORBIDDEN},
            {"access": {"rate": {"read": ["*"], "write": []}}, "expected_response": status.HTTP_200_OK},
            {
                "access": {"rate": {"read": [str(cost_model_uuid)], "write": []}},
                "expected_response": status.HTTP_200_OK,
            },
        ]
        client = APIClient()

        for test_case in test_matrix:
            with patch.object(RbacService, "get_access_for_user", return_value=test_case.get("access")):
                url = reverse("cost-models-detail", kwargs={"uuid": cost_model_uuid})
                caches["rbac"].clear()
                response = client.get(url, **request_context["request"].META)
                self.assertEqual(response.status_code, test_case.get("expected_response")) 
Example 26
Project: REST-API   Author: codingforentrepreneurs   File: tests.py    License: MIT License 5 votes vote down vote up
def test_token_login_api(self):
        url = api_reverse('api-auth:login')
        data = {
            'username': 'cfe',
            'password': 'yeahhhcfe',
        }
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK) # 400
        token = response.data.get("token", None)
        self.client.credentials(HTTP_AUTHORIZATION='JWT ' + token)
        response2 = self.client.post(url, data, format='json')
        self.assertEqual(response2.status_code, status.HTTP_403_FORBIDDEN) 
Example 27
Project: linkedevents   Author: City-of-Helsinki   File: test_event_auth_api.py    License: MIT License 5 votes vote down vote up
def test_random_user_create_event_denied(self):
        url = reverse('event-list')
        location_id = reverse('place-detail', kwargs={'pk': self.place.id})
        data = self.make_minimal_event_dict(self.system_data_source, self.org_1, location_id)

        self.client.force_authenticate(self.user)
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) 
Example 28
Project: linkedevents   Author: City-of-Helsinki   File: test_event_auth_api.py    License: MIT License 5 votes vote down vote up
def test_random_user_update_public_event_denied(self):
        url = reverse('event-detail', kwargs={'pk': self.event_4.id})
        location_id = reverse('place-detail', kwargs={'pk': self.place.id})
        data = self.make_minimal_event_dict(self.system_data_source, self.org_3, location_id)

        self.client.force_authenticate(self.user)
        response = self.client.put(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) 
Example 29
Project: linkedevents   Author: City-of-Helsinki   File: test_event_auth_api.py    License: MIT License 5 votes vote down vote up
def test_random_user_delete_public_event_denied(self):
        url = reverse('event-detail', kwargs={'pk': self.event_4.id})

        self.client.force_authenticate(self.user)
        response = self.client.delete(url)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) 
Example 30
Project: linkedevents   Author: City-of-Helsinki   File: test_event_auth_api.py    License: MIT License 5 votes vote down vote up
def test_random_user_bulk_create(self):
        url = reverse('event-list')
        location_id = reverse('place-detail', kwargs={'pk': self.place.id})
        data_1 = self.make_complex_event_dict(self.system_data_source, self.org_1, location_id, self.languages)
        data_1['name']['fi'] = 'event-data-1'
        data_2 = deepcopy(data_1)
        data_2['name']['fi'] = 'event-data-2'

        self.client.force_authenticate(self.user)
        response = self.client.post(url, [data_1, data_2], format='json')
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)