Python rest_framework.permissions.IsAuthenticated() Examples

The following are 30 code examples for showing how to use rest_framework.permissions.IsAuthenticated(). 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.permissions , or try the search function .

Example 1
Project: drf-json-api   Author: kevin-brown   File: test_errors.py    License: MIT License 6 votes vote down vote up
def test_auth_required(rf):
    class RestrictedPersonViewSet(PersonViewSet):
        permission_classes = [IsAuthenticated]

    data = dump_json({"people": {"name": "Jason Api"}})

    request = rf.post(
        reverse("person-list"), data=data,
        content_type="application/vnd.api+json")
    view = RestrictedPersonViewSet.as_view({'post': 'create'})
    response = view(request)
    response.render()

    assert response.status_code == 403, response.content
    assert not models.Person.objects.exists()

    results = {
        "errors": [{
            "status": "403",
            "title": "Authentication credentials were not provided."
        }]
    }
    assert response.content == dump_json(results) 
Example 2
Project: cmdb   Author: open-cmdb   File: initialize.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def add_viewset(table):
    data_index = table.name
    record_data_index = "{}.".format(table.name)
    deleted_data_index = "{}..".format(table.name)

    def retrieve(self, request, *args, **kwargs):
        try:
            res = es.search(index=record_data_index, doc_type="record-data", body={"query": {"term": {"S-data-id": kwargs["pk"]}}}, sort="S-update-time:desc")
        except NotFoundError as exc:
            raise exceptions.NotFound("Document {} was not found in Type data of Index {}".format(kwargs["pk"], record_data_index))
        except TransportError as exc:
            return Response([])
        return Response(res["hits"])
    viewset = type(table.name, (mixins.RetrieveModelMixin, viewsets.GenericViewSet), dict(
        permission_classes=(permissions.IsAuthenticated, ), retrieve=retrieve))
    setattr(views, table.name, viewset)
    return viewset 
Example 3
Project: djangochannel   Author: DJWOMS   File: api_views.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get(self, request):
        """Get"""
        quest = Question.objects.filter(test_id=request.GET.get("pk", None)).order_by("-id")
        counter = CompleteQuestion().get_counter(request.user, request.GET.get("pk", None))
        serializer = QuestionSerializer(quest, many=True)
        return JsonResponse(serializer.data, safe=False)


# class QuestionsInTest(BlankGetAPIView):
#     """
#     Вывод вопросов в отдельном тесте,
#     параметр: pk, значение: id теста, вопросы которого нужны
#     """
#     permission_classes = [permissions.IsAuthenticated]
#     model = Question
#     serializer = QuestionSerializer
#     filter_name = 'test_id'
#     order_params = 'id' 
Example 4
def test_bearer_authentication(self):
        @api_view(['GET'])
        @permission_classes([IsAuthenticated])
        @authentication_classes([BearerAuthentication])
        def my_view(request):
            return Response({})

        request = self.factory.get('/')
        response = my_view(request)
        self.assertEqual(response.status_code, 401)

        token = self._obtain_auth_token()
        request = self.factory.get('/', HTTP_AUTHORIZATION=f'Bearer {token}')
        response = my_view(request)
        self.assertEqual(response.status_code, 200) 
Example 5
Project: cride-platzi   Author: pablotrinidad   File: rides.py    License: MIT License 5 votes vote down vote up
def get_permissions(self):
        """Assign permission based on action."""
        permissions = [IsAuthenticated, IsActiveCircleMember]
        if self.action in ['update', 'partial_update', 'finish']:
            permissions.append(IsRideOwner)
        if self.action == 'join':
            permissions.append(IsNotRideOwner)
        return [p() for p in permissions] 
Example 6
Project: cride-platzi   Author: pablotrinidad   File: memberships.py    License: MIT License 5 votes vote down vote up
def get_permissions(self):
        """Assign permissions based on action."""
        permissions = [IsAuthenticated]
        if self.action != 'create':
            permissions.append(IsActiveCircleMember)
        if self.action == 'invitations':
            permissions.append(IsSelfMember)
        return [p() for p in permissions] 
Example 7
Project: cride-platzi   Author: pablotrinidad   File: circles.py    License: MIT License 5 votes vote down vote up
def get_permissions(self):
        """Assign permissions based on action."""
        permissions = [IsAuthenticated]
        if self.action in ['update', 'partial_update']:
            permissions.append(IsCircleAdmin)
        return [permission() for permission in permissions] 
Example 8
Project: karrot-backend   Author: yunity   File: api.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def get_permissions(self):
        if self.action == 'image':
            permission_classes = ()
        elif self.action in ('list', 'retrieve', 'conversation'):
            permission_classes = (IsAuthenticated, )
        else:
            permission_classes = (IsAuthenticated, IsOfferUser)
        return [permission() for permission in permission_classes] 
Example 9
Project: django-aws-template   Author: dkarchmer   File: api_views.py    License: MIT License 5 votes vote down vote up
def get_permissions(self):

        if self.request.method in permissions.SAFE_METHODS:
            return (permissions.IsAuthenticated(),)

        if self.request.method == 'POST':
            return (permissions.AllowAny(),)

        return (permissions.IsAuthenticated(), IsAccountOwner(),) 
Example 10
Project: opencraft   Author: open-craft   File: views.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def get_permissions(self):
        """
        Instantiates and returns the list of permissions that this view requires.
        """
        if self.action == "create":
            # Allow any user to create an account, but limit other actions to logged-in users.
            permission_classes = [AllowAny]
        else:
            permission_classes = [IsAuthenticated]
        return [permission() for permission in permission_classes] 
Example 11
Project: opencraft   Author: open-craft   File: views.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def get_permissions(self):
        """
        Instantiates and returns the list of permissions that this view requires.
        """
        if self.action == "validate":
            # Allow validating instance configuration without an account
            permission_classes = [AllowAny]
        else:
            permission_classes = [IsAuthenticated]
        return [permission() for permission in permission_classes] 
Example 12
Project: CTF_AWD_Platform   Author: xuchaoa   File: views.py    License: MIT License 5 votes vote down vote up
def get_permissions(self):
        if self.action == 'create':
            return []
        elif self.action == 'update':
            return [permissions.IsAuthenticated()]
        return [permissions.IsAuthenticated()] 
Example 13
Project: graphene-django-extras   Author: eamigo86   File: views.py    License: MIT License 5 votes vote down vote up
def as_view(cls, *args, **kwargs):
        view = super(AuthenticatedGraphQLView, cls).as_view(*args, **kwargs)
        view = permission_classes((IsAuthenticated,))(view)
        view = authentication_classes(api_settings.DEFAULT_AUTHENTICATION_CLASSES)(view)
        view = throttle_classes(api_settings.DEFAULT_THROTTLE_CLASSES)(view)
        view = api_view(["GET", "POST"])(view)
        view = csrf_exempt(view)

        return view 
Example 14
Project: iguana   Author: iguana-project   File: views.py    License: Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def get_permissions(self):
        if self.action == 'list' or self.action == 'create':
            return [permissions.IsAuthenticated(), ]
        if self.action == 'retrieve':
            return [permissions.IsAuthenticated(), UserIsMemberInProject()]
        if self.action in ('update', 'partial_update', 'destroy'):
            return [permissions.IsAuthenticated(), UserIsManagerInProject()]
        return [permissions.IsAuthenticated(), UserIsManagerInProject()] 
Example 15
Project: iguana   Author: iguana-project   File: views.py    License: Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def get_permissions(self):
        if self.action in ('list', 'retrieve', 'create'):
            return [permissions.IsAuthenticated(), UserIsMemberInProject()]
        if self.action in ('update', 'partial_update', 'destroy'):
            return [permissions.IsAuthenticated(), UserIsOwnerOrManager()]
        return [permissions.IsAuthenticated(), UserIsOwnerOrManager()] 
Example 16
Project: iguana   Author: iguana-project   File: views.py    License: Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def get_permissions(self):
        if self.action in ('list', 'retrieve', 'create'):
            return [permissions.IsAuthenticated(), UserIsMemberInProject()]
        if self.action in ('update', 'partial_update', 'destroy'):
            return [permissions.IsAuthenticated(), UserIsOwnerOrManager()]
        return [permissions.IsAuthenticated(), UserIsOwnerOrManager()] 
Example 17
Project: silver   Author: silverapp   File: test_payment_method.py    License: Apache License 2.0 5 votes vote down vote up
def test_permissions(self):
        self.assertEqual(PaymentMethodList.permission_classes,
                         (permissions.IsAuthenticated,))
        self.assertEqual(PaymentMethodDetail.permission_classes,
                         (permissions.IsAuthenticated,)) 
Example 18
Project: Dailyfresh-B2C   Author: BeanWei   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def get_serializer_class(self):
        if self.action == "retrieve":
            return UserDetailSerializer
        elif self.action == "create":
            return UserRegSerializer

        return UserDetailSerializer

    # permission_classes = (permissions.IsAuthenticated, ) 
Example 19
Project: Dailyfresh-B2C   Author: BeanWei   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def get_permissions(self):
        if self.action == "retrieve":
            return [permissions.IsAuthenticated()]
        elif self.action == "create":
            return []

        return [] 
Example 20
Project: website   Author: fengjinqi   File: views.py    License: MIT License 5 votes vote down vote up
def get_permissions(self):
        if self.action == 'list':
            return []
        elif self.action == 'retrieve':
            return []
        else:
            return [IsAuthenticated(), IsOwnerOr()] 
Example 21
Project: website   Author: fengjinqi   File: views.py    License: MIT License 5 votes vote down vote up
def get_permissions(self):
        if self.action == 'list':
            return []
        elif self.action == 'retrieve':
            return []
        else:
            return [IsAuthenticated(), IsOwnerOr()] 
Example 22
Project: website   Author: fengjinqi   File: views.py    License: MIT License 5 votes vote down vote up
def get_permissions(self):
        if self.action == 'list':
            return []
        elif self.action == 'retrieve':
            return []
        else:
            return [IsAuthenticated(), IsOwnerOrReadOnly()] 
Example 23
Project: website   Author: fengjinqi   File: views.py    License: MIT License 5 votes vote down vote up
def get_permissions(self):
        if self.action=='destroy':
            return [IsAuthenticated()]
        else:
            return [] 
Example 24
Project: website   Author: fengjinqi   File: views.py    License: MIT License 5 votes vote down vote up
def get_permissions(self):
        if self.action == 'list':
            return []
        elif self.action =='retrieve':
            return []
        else:
            return [IsAuthenticated(),IsOwnerOrReadOnly()] 
Example 25
Project: website   Author: fengjinqi   File: views.py    License: MIT License 5 votes vote down vote up
def get_permissions(self):
        if self.action == 'list':
            return []
        elif self.action == 'retrieve':
            return []
        else:
            return [IsAuthenticated(),IsOwnerOrReadOnly()] 
Example 26
Project: timestrap   Author: overshard   File: views.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_permissions(self):
        # Prevent rest_framework from checking for the "view" perm.
        return (permissions.IsAuthenticated(),) 
Example 27
Project: timestrap   Author: overshard   File: views.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_permissions(self):
        # Prevent rest_framework from checking for the "view" perm.
        return (permissions.IsAuthenticated(),) 
Example 28
Project: train-ai-with-django-swagger-jwt   Author: jay-johnson   File: user.py    License: Apache License 2.0 5 votes vote down vote up
def get_permissions(self):
        if self.request.method == 'POST':
            return (permissions.AllowAny(),)
        elif self.request.method == 'GET':
            return (permissions.IsAuthenticated(),)
        elif self.request.method == 'PUT':
            return (permissions.IsAuthenticated(),)
        elif self.request.method == 'DELETE':
            return (permissions.IsAuthenticated(),)

        return (permissions.IsAuthenticated(),)
    # end of get_permissions 
Example 29
Project: train-ai-with-django-swagger-jwt   Author: jay-johnson   File: ml.py    License: Apache License 2.0 5 votes vote down vote up
def get_permissions(self):
        if self.request.method == 'POST':
            return (permissions.IsAuthenticated(),)
        elif self.request.method == 'GET':
            return (permissions.IsAuthenticated(),)
        elif self.request.method == 'PUT':
            return (permissions.IsAuthenticated(),)
        elif self.request.method == 'DELETE':
            return (permissions.IsAuthenticated(),)

        return (permissions.IsAuthenticated(),)
    # end of get_permissions 
Example 30
Project: train-ai-with-django-swagger-jwt   Author: jay-johnson   File: ml.py    License: Apache License 2.0 5 votes vote down vote up
def get_permissions(self):
        if self.request.method == 'POST':
            return (permissions.IsAuthenticated(),)
        elif self.request.method == 'GET':
            return (permissions.IsAuthenticated(),)
        elif self.request.method == 'PUT':
            return (permissions.IsAuthenticated(),)
        elif self.request.method == 'DELETE':
            return (permissions.IsAuthenticated(),)

        return (permissions.IsAuthenticated(),)
    # end of get_permissions