Python rest_framework.status.HTTP_401_UNAUTHORIZED Examples

The following are 30 code examples for showing how to use rest_framework.status.HTTP_401_UNAUTHORIZED(). 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: resolwe   Author: genialis   File: mixins.py    License: Apache License 2.0 6 votes vote down vote up
def slug_exists(self, request):
        """Check if given url slug exists.

        Check if slug given in query parameter ``name`` exists. Return
        ``True`` if slug already exists and ``False`` otherwise.

        """
        if not request.user.is_authenticated:
            return Response(status=status.HTTP_401_UNAUTHORIZED)

        if "name" not in request.query_params:
            return Response(
                {"error": "Query parameter `name` must be given."},
                status=status.HTTP_400_BAD_REQUEST,
            )

        queryset = self.get_queryset()
        slug_name = request.query_params["name"]
        return Response(queryset.filter(slug__iexact=slug_name).exists()) 
Example 2
def test_delegate_jwti_inactive_user(self):
        data = {
            'client_id': 'gandolf',
            'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
            'refresh_token': self.token1.key,
            'api_type': 'app',
        }
        self.user1.is_active = False
        self.user1.save()
        response = self.client.post(self.delegate_url,
                                    data=data,
                                    format='json')
        self.assertEqual(
            response.status_code,
            status.HTTP_401_UNAUTHORIZED,
            (response.status_code, response.content)
        ) 
Example 3
Project: safe-relay-service   Author: gnosis   File: test_views.py    License: MIT License 6 votes vote down vote up
def test_api_token_auth(self):
        username, password = 'admin', 'mypass'

        # No user created
        response = self.client.post(reverse('v1:api-token-auth'), format='json', data={'username': username,
                                                                                       'password': password})
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        # Create user
        User.objects.create_superuser(username, 'admin@admin.com', password)
        response = self.client.post(reverse('v1:api-token-auth'), format='json', data={'username': username,
                                                                                       'password': password})
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        token = response.json()['token']

        # Test protected endpoint
        response = self.client.get(reverse('v1:private-safes'))
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

        response = self.client.get(reverse('v1:private-safes'), HTTP_AUTHORIZATION='Token ' + token)
        self.assertEqual(response.status_code, status.HTTP_200_OK) 
Example 4
Project: server   Author: project-travel-mate   File: views.py    License: MIT License 6 votes vote down vote up
def get_feedback(request, feedback_id):
    """
    Returns the feedback pertaining to a certain feedback id
    :param request:
    :return: 401 if authorization failed
    :return: 404 if not found
    :return: 200 successful
    """

    try:
        user_feedback = Feedback.objects.get(pk=feedback_id)
        if request.user is not user_feedback.user:
            return Response(status=status.HTTP_401_UNAUTHORIZED)
    except Feedback.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    serializer = FeedbackCondensedSerializer(user_feedback)
    return Response(serializer.data) 
Example 5
Project: server   Author: project-travel-mate   File: views.py    License: MIT License 6 votes vote down vote up
def get_trip(request, trip_id):
    """
    Returns a trip using 'trip_id'
    :param request:
    :param trip_id:
    :return: 401 if user is not a member of this specific trip and trip is private
    :return: 404 if invalid trip id is sent
    :return: 200 successful
    """
    try:
        trip = Trip.objects.get(pk=trip_id)
        if request.user not in trip.users.all() and not trip.is_public:
            return Response(status=status.HTTP_401_UNAUTHORIZED)
    except Trip.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    serializer = TripSerializer(trip)
    return Response(serializer.data) 
Example 6
Project: server   Author: project-travel-mate   File: views.py    License: MIT License 6 votes vote down vote up
def update_trip_name(request, trip_id, trip_name):
    """
    :param request:
    :param trip_id:
    :param trip_name:
    :return: 400 if user not present in the trip
    :return: 404 if trip or user does not exist
    :return: 200 successful
    """
    try:
        trip = Trip.objects.get(id=trip_id)
        if request.user not in trip.users.all():
            return Response(status=status.HTTP_401_UNAUTHORIZED)

        trip.trip_name = trip_name
        trip.save(update_fields=['trip_name'])

    except Trip.DoesNotExist:
        error_message = "Trip does not exist"
        return Response(error_message, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        return Response(str(e), status=status.HTTP_400_BAD_REQUEST)

    return Response(status=status.HTTP_200_OK) 
Example 7
Project: server   Author: project-travel-mate   File: views.py    License: MIT License 6 votes vote down vote up
def update_trip_public(request, trip_id):
    """
    Makes given trip public
    :param request:
    :param trip_id:
    :return: 400 if user not present in the trip
    :return: 404 if trip or user does not exist
    :return: 200 successful
    """
    try:
        trip = Trip.objects.get(pk=trip_id)

        # if signed-in user not associated with requested trip
        if request.user not in trip.users.all():
            error_message = "User not a part of trip"
            return Response(error_message, status=status.HTTP_401_UNAUTHORIZED)
        trip.is_public = True
        trip.save()
    except Trip.DoesNotExist:
        error_message = "Trip does not exist"
        return Response(error_message, status=status.HTTP_404_NOT_FOUND)

    return Response(status=status.HTTP_200_OK) 
Example 8
Project: server   Author: project-travel-mate   File: views.py    License: MIT License 6 votes vote down vote up
def update_trip_private(request, trip_id):
    """
    Makes given trip private
    :param request:
    :param trip_id:
    :return: 400 if user not present in the trip
    :return: 404 if trip or user does not exist
    :return: 200 successful
    """
    try:
        trip = Trip.objects.get(pk=trip_id)

        # if signed-in user not associated with requested trip
        if request.user not in trip.users.all():
            error_message = "User not a part of trip"
            return Response(error_message, status=status.HTTP_401_UNAUTHORIZED)
        trip.is_public = False
        trip.save()
    except Trip.DoesNotExist:
        error_message = "Trip does not exist"
        return Response(error_message, status=status.HTTP_404_NOT_FOUND)

    return Response(status=status.HTTP_200_OK) 
Example 9
Project: server   Author: project-travel-mate   File: views.py    License: MIT License 6 votes vote down vote up
def mark_notification_as_read(request, notification_id):
    """
    Mark notification as read
    :param request:
    :param notification_id:
    :return 200 successful
    """
    try:
        notification = Notification.objects.get(id=notification_id)
        if request.user != notification.destined_user:
            return Response(status=status.HTTP_401_UNAUTHORIZED)
        notification.is_read = True
        notification.save()

    except Notification.DoesNotExist:
        error_message = "Notification does not exist"
        return Response(error_message, status=status.HTTP_404_NOT_FOUND)

    success_message = "Successfully marked notification as read."
    return Response(success_message, status=status.HTTP_200_OK) 
Example 10
Project: substra-backend   Author: SubstraFoundation   File: tests_utils.py    License: Apache License 2.0 6 votes vote down vote up
def with_requests_mock(allowed):
    def inner(f):
        @functools.wraps(f)
        def wrapper(*args, **kwargs):
            tmp_file = kwargs['tmp_file']
            filename = kwargs['filename']

            requests_response = requests.Response()
            if allowed:
                requests_response.raw = tmp_file
                requests_response.headers['Content-Disposition'] = f'attachment; filename="{filename}"'
                requests_response.status_code = status.HTTP_200_OK
            else:
                requests_response._content = b'{"message": "nope"}'
                requests_response.status_code = status.HTTP_401_UNAUTHORIZED

            kwargs['requests_response'] = requests_response

            with mock.patch('substrapp.views.utils.authenticate_outgoing_request',
                            return_value=HTTPBasicAuth('foo', 'bar')), \
                    mock.patch('substrapp.utils.requests.get', return_value=requests_response):
                f(*args, **kwargs)
        return wrapper
    return inner 
Example 11
Project: bennedetto   Author: arecker   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def password(self, request, **kwargs):
        user = request.user

        old = request.data.get('old', None)
        new1 = request.data.get('new1', None)
        new2 = request.data.get('new2', None)

        try:
            user = request.user.change_password(old=old, new=(new1, new2))
        except user.IncorrectPassword:
            return Response('Incorrect password',
                            status=status.HTTP_401_UNAUTHORIZED)
        except user.PasswordsDontMatch:
            return Response('Passwords do not match',
                            status=status.HTTP_400_BAD_REQUEST)

        update_session_auth_hash(request, user)
        return Response('password updated') 
Example 12
Project: hummer   Author: wangtaoking1   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def is_authenticated(request):
    """
    Determine whether the user is authenticated.
    Return user_name and status HTTP_200_OK if authenticated, else return
    status HTTP_401_UNAUTHORIZED.
    """
    if request.user and request.user.is_authenticated():
        data = [request.user.username, request.user.is_staff]
        return Response(data=data, status=status.HTTP_200_OK)
    return Response(status=status.HTTP_401_UNAUTHORIZED) 
Example 13
Project: resolwe   Author: genialis   File: relation.py    License: Apache License 2.0 5 votes vote down vote up
def update(self, request, *args, **kwargs):
        """Update the ``Relation`` object.

        Reject the update if user doesn't have ``EDIT`` permission on
        the collection referenced in the ``Relation``.
        """
        instance = self.get_object()
        if (
            not request.user.has_perm("edit_collection", instance.collection)
            and not request.user.is_superuser
        ):
            return Response(status=status.HTTP_401_UNAUTHORIZED)

        return super().update(request, *args, **kwargs) 
Example 14
Project: resolwe   Author: genialis   File: relation.py    License: Apache License 2.0 5 votes vote down vote up
def destroy(self, request, *args, **kwargs):
        """Delete the ``Relation`` object.

        Reject the delete if user doesn't have ``EDIT`` permission on
        the collection referenced in the ``Relation``.
        """
        instance = self.get_object()

        if (
            not request.user.has_perm("edit_collection", instance.collection)
            and not request.user.is_superuser
        ):
            return Response(status=status.HTTP_401_UNAUTHORIZED)

        return super().destroy(request, *args, **kwargs) 
Example 15
def test_requires_auth(self):
        response = self.client.get(self.list_url)
        self.assertEqual(
            response.status_code,
            status.HTTP_401_UNAUTHORIZED,
            (response.status_code, response.content)
        )

        response = self.client.get(self.detail_url)
        self.assertEqual(
            response.status_code,
            status.HTTP_401_UNAUTHORIZED,
            (response.status_code, response.content)
        )

        response = self.client.delete(self.detail_url)
        self.assertEqual(
            response.status_code,
            status.HTTP_401_UNAUTHORIZED,
            (response.status_code, response.content)
        )

        response = self.client.post(self.list_url)
        self.assertEqual(
            response.status_code,
            status.HTTP_401_UNAUTHORIZED,
            (response.status_code, response.content)
        ) 
Example 16
def test_delegate_jwti_wrong_token(self):
        data = {
            'client_id': 'gandolf',
            'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
            'refresh_token': 'nope',
            'api_type': 'app',
        }
        response = self.client.post(self.delegate_url,
                                    data=data,
                                    format='json')
        self.assertEqual(
            response.status_code,
            status.HTTP_401_UNAUTHORIZED,
            (response.status_code, response.content)
        ) 
Example 17
Project: desec-stack   Author: desec-io   File: test_rrsets.py    License: MIT License 5 votes vote down vote up
def test_unauthorized_access(self):
        url = self.reverse('v1:rrsets', name='example.com')
        for method in [
            self.client.get, 
            self.client.post, 
            self.client.put, 
            self.client.delete, 
            self.client.patch
        ]:
            response = method(url)
            self.assertStatus(response, status.HTTP_401_UNAUTHORIZED) 
Example 18
Project: desec-stack   Author: desec-io   File: test_user_management.py    License: MIT License 5 votes vote down vote up
def assert401InvalidPasswordResponse(self, response):
        return self.assertContains(
            response=response,
            text="Invalid password.",
            status_code=status.HTTP_401_UNAUTHORIZED
        ) 
Example 19
Project: desec-stack   Author: desec-io   File: test_replication.py    License: MIT License 5 votes vote down vote up
def test_serials(self):
        url=self.reverse('v1:serial')
        zones = [
            {'name': 'test.example.', 'edited_serial': 12345},
            {'name': 'example.org.', 'edited_serial': 54321},
        ]
        serials = {zone['name']: zone['edited_serial'] for zone in zones}
        pdns_requests = [{
            'method': 'GET',
            'uri': self.get_full_pdns_url(r'/zones', ns='MASTER'),
            'status': 200,
            'body': json.dumps(zones),
        }]

        # Run twice to make sure cache output varies on remote address
        for i in range(2):
            response = self.client.get(path=url, REMOTE_ADDR='123.8.0.2')
            self.assertStatus(response, status.HTTP_401_UNAUTHORIZED)

            with self.assertPdnsRequests(pdns_requests):
                response = self.client.get(path=url, REMOTE_ADDR='10.8.0.2')
            self.assertStatus(response, status.HTTP_200_OK)
            self.assertEqual(response.data, serials)

            # Do not expect pdns request in next iteration (result will be cached)
            pdns_requests = [] 
Example 20
Project: desec-stack   Author: desec-io   File: test_domains.py    License: MIT License 5 votes vote down vote up
def test_unauthorized_access(self):
        for url in [
            self.reverse('v1:domain-list'),
            self.reverse('v1:domain-detail', name='example.com.')
        ]:
            for method in [self.client.put, self.client.delete]:
                self.assertStatus(method(url), status.HTTP_401_UNAUTHORIZED) 
Example 21
Project: desec-stack   Author: desec-io   File: test_authentication.py    License: MIT License 5 votes vote down vote up
def test_username_password(self):
        # noinspection PyPep8Naming
        def assertDynDNS12AuthenticationStatus(username, token, code):
            self.client.set_credentials_basic_auth(username, token)
            self.assertDynDNS12Status(code)

        assertDynDNS12AuthenticationStatus('', self.token.plain, HTTP_200_OK)
        assertDynDNS12AuthenticationStatus(self.owner.get_username(), self.token.plain, HTTP_200_OK)
        assertDynDNS12AuthenticationStatus(self.my_domain.name, self.token.plain, HTTP_200_OK)
        assertDynDNS12AuthenticationStatus(' ' + self.my_domain.name, self.token.plain, HTTP_401_UNAUTHORIZED)
        assertDynDNS12AuthenticationStatus('wrong', self.token.plain, HTTP_401_UNAUTHORIZED)
        assertDynDNS12AuthenticationStatus('', 'wrong', HTTP_401_UNAUTHORIZED)
        assertDynDNS12AuthenticationStatus(self.user.get_username(), 'wrong', HTTP_401_UNAUTHORIZED) 
Example 22
Project: desec-stack   Author: desec-io   File: test_authentication.py    License: MIT License 5 votes vote down vote up
def test_token_case_sensitive(self):
        self.assertAuthenticationStatus(HTTP_200_OK, self.token.plain)
        self.assertAuthenticationStatus(HTTP_401_UNAUTHORIZED, self.token.plain.upper())
        self.assertAuthenticationStatus(HTTP_401_UNAUTHORIZED, self.token.plain.lower()) 
Example 23
Project: desec-stack   Author: desec-io   File: test_dyndns12update.py    License: MIT License 5 votes vote down vote up
def test_identification_by_domain_name(self):
        self.client.set_credentials_basic_auth(self.my_domain.name + '.invalid', self.token.plain)
        response = self.assertDynDNS12NoUpdate(mock_remote_addr='10.5.5.6')
        self.assertStatus(response, status.HTTP_401_UNAUTHORIZED) 
Example 24
Project: timed-backend   Author: adfinis-sygroup   File: test_authentication.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_authentication(
    db,
    user,
    rf,
    authentication_header,
    authenticated,
    error,
    is_id_token,
    requests_mock,
    settings,
):
    userinfo = {"preferred_username": "1"}
    requests_mock.get(settings.OIDC_OP_USER_ENDPOINT, text=json.dumps(userinfo))

    if not is_id_token:
        userinfo = {"client_id": "test_client", "preferred_username": "1"}
        requests_mock.get(
            settings.OIDC_OP_USER_ENDPOINT, status_code=status.HTTP_401_UNAUTHORIZED
        )
        requests_mock.post(
            settings.OIDC_OP_INTROSPECT_ENDPOINT, text=json.dumps(userinfo)
        )

    request = rf.get("/openid", HTTP_AUTHORIZATION=authentication_header)
    try:
        result = OIDCAuthentication().authenticate(request)
    except exceptions.AuthenticationFailed:
        assert error
    else:
        if result:
            key = "userinfo" if is_id_token else "introspection"
            user, auth = result
            assert user.is_authenticated
            assert (
                cache.get(f"auth.{key}.{hashlib.sha256(b'Token').hexdigest()}")
                == userinfo
            ) 
Example 25
Project: timed-backend   Author: adfinis-sygroup   File: test_authentication.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_authentication_no_client(db, rf, requests_mock, settings):
    requests_mock.get(
        settings.OIDC_OP_USER_ENDPOINT, status_code=status.HTTP_401_UNAUTHORIZED
    )
    requests_mock.post(
        settings.OIDC_OP_INTROSPECT_ENDPOINT,
        text=json.dumps({"preferred_username": "1"}),
    )

    request = rf.get("/openid", HTTP_AUTHORIZATION="Bearer Token")
    with pytest.raises(AuthenticationFailed):
        OIDCAuthentication().authenticate(request) 
Example 26
Project: REST-API   Author: codingforentrepreneurs   File: tests.py    License: MIT License 5 votes vote down vote up
def test_login_user_api_fail(self):
        url = api_reverse('api-auth:login')
        data = {
            'username': 'cfe.abc', # does not exist
            'password': 'yeahhhcfe',
        }
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) # 400
        token = response.data.get("token", 0)
        token_len = 0
        if token != 0:
            token_len = len(token)
        self.assertEqual(token_len, 0) 
Example 27
Project: REST-API   Author: codingforentrepreneurs   File: tests.py    License: MIT License 5 votes vote down vote up
def test_status_no_token_create(self):
        url = api_reverse('api-status:list')
        data = {
            'content': "some cool test content"
        }
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) 
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_unauthenticated_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)

        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) 
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_unauthenticated_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)

        response = self.client.put(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) 
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_unauthenticated_user_delete_public_event_denied(self):
        url = reverse('event-detail', kwargs={'pk': self.event_4.id})

        response = self.client.delete(url)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)