Python rest_framework.status.HTTP_401_UNAUTHORIZED Examples

The following are 30 code examples of rest_framework.status.HTTP_401_UNAUTHORIZED(). 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 also want to check out all available functions/classes of the module rest_framework.status , or try the search function .
Example #1
Source File: tests_utils.py    From substra-backend with 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 #2
Source File: test_long_refresh_token_views.py    From django-rest-framework-jwt-refresh-token with MIT License 6 votes vote down vote up
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
Source File: mixins.py    From resolwe with 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 #4
Source File: views.py    From bennedetto with 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 #5
Source File: test_views.py    From safe-relay-service with 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 #6
Source File: views.py    From server with 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 #7
Source File: views.py    From server with 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 #8
Source File: views.py    From server with 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 #9
Source File: views.py    From server with 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 #10
Source File: views.py    From server with 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 #11
Source File: views.py    From server with 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 #12
Source File: test_api_polls.py    From lego with MIT License 5 votes vote down vote up
def test_detailed_poll_unauthenticated(self):
        """A user with no permissions should not be able to retrive the detailed poll view"""
        response = self.client.get(_get_detail_url(2))
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) 
Example #13
Source File: test_token_destroy.py    From djoser with MIT License 5 votes vote down vote up
def test_post_should_deny_logging_out_when_user_not_logged_in(self):
        create_user()
        response = self.client.post(self.base_url)

        self.assert_status_equal(response, status.HTTP_401_UNAUTHORIZED) 
Example #14
Source File: test_views.py    From lego with MIT License 5 votes vote down vote up
def test_get_token_no_auth(self):
        """Return 401 on invalid token"""
        response = self.client.get(f"{self.url}1/token/?auth=invalid")
        self.assertEquals(status.HTTP_401_UNAUTHORIZED, response.status_code) 
Example #15
Source File: test_views.py    From lego with MIT License 5 votes vote down vote up
def test_delete(self):
        """Try to delete follow items"""
        response = self.client.delete(f"{self.url}1/")
        self.assertEquals(response.status_code, status.HTTP_401_UNAUTHORIZED)

        denied_user = User.objects.get(id=2)
        self.client.force_authenticate(denied_user)
        response = self.client.delete(f"{self.url}1/")
        self.assertEquals(response.status_code, status.HTTP_404_NOT_FOUND)

        self.client.force_authenticate(self.user)
        response = self.client.delete(f"{self.url}1/")
        self.assertEquals(response.status_code, status.HTTP_204_NO_CONTENT) 
Example #16
Source File: test_views.py    From drf-tutorial with MIT License 5 votes vote down vote up
def test_anonymous_cannot_delete_a_product(self):
        url = reverse('product-detail', kwargs={'product_id': 1})

        # Logout so the user is anonymous
        self.client.logout()

        response = self.client.delete(url)

        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
        self.assertEqual(Product.objects.count(), 8) 
Example #17
Source File: relation.py    From resolwe with 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 #18
Source File: test_views.py    From lego with MIT License 5 votes vote down vote up
def test_list(self):
        """Try to list the follower apis with and without auth."""
        response = self.client.get(self.url)
        self.assertEquals(response.status_code, status.HTTP_401_UNAUTHORIZED)

        self.client.force_authenticate(self.user)
        response = self.client.get(self.url)
        self.assertEquals(response.status_code, status.HTTP_200_OK) 
Example #19
Source File: test_views.py    From lego with MIT License 5 votes vote down vote up
def test_delete(self):
        """Try to delete follow items"""
        response = self.client.delete(f"{self.url}1/")
        self.assertEquals(response.status_code, status.HTTP_401_UNAUTHORIZED)

        denied_user = User.objects.get(id=2)
        self.client.force_authenticate(denied_user)
        response = self.client.delete(f"{self.url}1/")
        self.assertEquals(response.status_code, status.HTTP_404_NOT_FOUND)

        self.client.force_authenticate(self.user)
        response = self.client.delete(f"{self.url}1/")
        self.assertEquals(response.status_code, status.HTTP_204_NO_CONTENT) 
Example #20
Source File: test_views.py    From lego with MIT License 5 votes vote down vote up
def test_create(self):
        """Try to follow a user, we should always store the follower as request.user"""
        response = self.client.post(self.url, {"target": 1})
        self.assertEquals(response.status_code, status.HTTP_401_UNAUTHORIZED)

        self.client.force_authenticate(self.user)
        response = self.client.post(self.url, {"target": 1})
        self.assertEquals(response.status_code, status.HTTP_201_CREATED)

        # Always use request.user to set the follower
        response = self.client.post(self.url, {"target": 2, "follower": 2})
        self.assertEquals(response.status_code, status.HTTP_201_CREATED)
        result_id = response.json()["id"]
        self.assertEquals(FollowUser.objects.get(id=result_id).follower, self.user) 
Example #21
Source File: test_views.py    From lego with MIT License 5 votes vote down vote up
def test_list(self):
        """Try to list the follower apis with and without auth."""
        response = self.client.get(self.url)
        self.assertEquals(response.status_code, status.HTTP_401_UNAUTHORIZED)

        self.client.force_authenticate(self.user)
        response = self.client.get(self.url)
        self.assertEquals(response.status_code, status.HTTP_200_OK) 
Example #22
Source File: test_views.py    From lego with MIT License 5 votes vote down vote up
def test_delete(self):
        """Try to delete follow items"""
        response = self.client.delete(f"{self.url}1/")
        self.assertEquals(response.status_code, status.HTTP_401_UNAUTHORIZED)

        denied_user = User.objects.get(id=2)
        self.client.force_authenticate(denied_user)
        response = self.client.delete(f"{self.url}1/")
        self.assertEquals(response.status_code, status.HTTP_404_NOT_FOUND)

        self.client.force_authenticate(self.user)
        response = self.client.delete(f"{self.url}1/")
        self.assertEquals(response.status_code, status.HTTP_204_NO_CONTENT) 
Example #23
Source File: test_views.py    From lego with MIT License 5 votes vote down vote up
def test_list(self):
        """Try to list the follower apis with and without auth."""
        response = self.client.get(self.url)
        self.assertEquals(response.status_code, status.HTTP_401_UNAUTHORIZED)

        self.client.force_authenticate(self.user)
        response = self.client.get(self.url)
        self.assertEquals(response.status_code, status.HTTP_200_OK) 
Example #24
Source File: test_views.py    From lego with MIT License 5 votes vote down vote up
def test_delete_picture_no_user(self, mock_signer):
        """Non logged i user is not able to delete pictures."""
        response = self.client.delete(f"{self.url}1/pictures/1/")
        self.assertEqual(status.HTTP_401_UNAUTHORIZED, response.status_code) 
Example #25
Source File: test_views.py    From lego with MIT License 5 votes vote down vote up
def test_add_picture_no_user(self, mock_signer):
        """Non logged in user is not be able to add images."""
        response = self.client.post(f"{self.url}1/pictures/", self.add_picture_data)
        self.assertEqual(status.HTTP_401_UNAUTHORIZED, response.status_code) 
Example #26
Source File: test_views.py    From lego with MIT License 5 votes vote down vote up
def test_add_picture_no_user(self, mock_signer):
        response = self.client.post(f"{self.url}1/pictures/", self.add_picture_data)
        self.assertEqual(status.HTTP_401_UNAUTHORIZED, response.status_code) 
Example #27
Source File: test_views.py    From lego with MIT License 5 votes vote down vote up
def test_no_auth(self):
        response = self.client.get(self.url)
        self.assertEquals(response.status_code, status.HTTP_401_UNAUTHORIZED)

        response = self.client.post(
            self.url,
            {"notificationType": "weekly_mail", "enabled": True, "channels": ["email"]},
        )
        self.assertEquals(response.status_code, status.HTTP_401_UNAUTHORIZED) 
Example #28
Source File: test_views.py    From scale with Apache License 2.0 5 votes vote down vote up
def test_get_current_user_unauthorized(self):
        """Tests calling the GetUser view without being authenticated."""

        url = rest_util.get_url('/accounts/profile/')
        response = self.client.get(url)

        self.assertIn(response.status_code, [status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN], response.content) 
Example #29
Source File: views.py    From scale with Apache License 2.0 5 votes vote down vote up
def get(self, request):
        """
        Return details of a specific user.
        """

        if request.user and request.user.is_anonymous:
            return Response(status=status.HTTP_401_UNAUTHORIZED)

        serializer = UserAccountSerializer(request.user)
        return Response(serializer.data) 
Example #30
Source File: test_user_detail.py    From djoser with MIT License 5 votes vote down vote up
def test_unauthenticated_user_cannot_get_user_detail(self):
        response = self.client.get(reverse("user-detail", args=[self.user.pk]))

        self.assert_status_equal(response, status.HTTP_401_UNAUTHORIZED)