Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get OR permissions instead of AND in REST framework

It seems that permission classes are ANDed when REST framework checks permissions. That is every permission class needs to return True for permission to be granted. This makes things like "if you are a superuser, you can access anything, but if you are a regular user you need explicit permissions" a bit hard to implement, you cannot just return False, it will fail the whole stack. Is there a way to maybe short-circuit permissions? Something like "if this permission is granted, stop checking?" or some other way to deal with cases like that?

like image 845
Mad Wombat Avatar asked Feb 22 '16 15:02

Mad Wombat


People also ask

How do we use permissions in REST framework?

Permissions are used to grant or deny access for different classes of users to different parts of the API. The simplest style of permission would be to allow access to any authenticated user, and deny access to any unauthenticated user. This corresponds to the IsAuthenticated class in REST framework.

What is DjangoModelPermissions?

DjangoModelPermissions allows us to set any combination of permissions to each of the users separately. The permission then checks if the user is authenticated and if they have add , change , or delete user permissions on the model.

How do I update user details in Django REST framework?

Open auth/urls.py and add update profile endpoint. we should send a PUT request to API for checking update profile endpoint. We must add username, first_name, last_name and email. If fields passed validations, user profile will be changed.


1 Answers

Now DRF allows permissions to be composed using bitwise operators: & -and- and | -or-.

From the docs:

Provided they inherit from rest_framework.permissions.BasePermission, permissions can be composed using standard Python bitwise operators. For example, IsAuthenticatedOrReadOnly could be written:

from rest_framework.permissions import BasePermission, IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView  class ReadOnly(BasePermission):     def has_permission(self, request, view):         return request.method in SAFE_METHODS  class ExampleView(APIView):     permission_classes = (IsAuthenticated|ReadOnly,)      def get(self, request, format=None):         content = {             'status': 'request was permitted'         }         return Response(content) 

Edited: Please note there is a comma after IsAuthenticated|ReadOnly.

like image 171
mehamasum Avatar answered Sep 30 '22 20:09

mehamasum