#Can't I use the OR operator in permission classes?

19 messages · Page 1 of 1 (latest)

wooden ravine
#

If I want to use an OR operation in permission classes, do I need to create a custom permission class that handles both options on its own?

#

I have something like IsOwnerUserOrIsAdminUser because I'm not sure how to use the OR operator in this case. Is it possible? How can I do it? I'm using DRF and not applying decorators to my views.

young forum
#

I achieved this with
class GetPatientVitalsView(APIView):
permission_classes = [IsDoctorUser | IsNurseUser]

where IsDoctoUser and IsNurseUser are custom permission classes

wooden ravine
#

Interesting. I’ve done this using decorators in a project at my work, also with ApiView, but I couldn’t find an example of this working with ModelViewSet.

#

How would I adapt this in this case? Does anyone know?

young forum
#

I think same could be implemented

permission_classes = [IsAuthenticatedIsOwnerUserOrIsAdminUser]
return [permission() for permission in permission_classes]

#

how about you merge them into one and you work on it separately

wooden ravine
#

What I want to do is break down this IsOwnerUserOrIsAdminUser into two different classes: IsOwnerUser, which I implemented myself, and IsAdminUser, which is already built-in in DRF

young forum
#

and how do you want to use it

wooden ravine
#

In this case, it should be verified if the user is authenticated AND if they are the owner of that instance in the table OR if they are a superuser.

young forum
#

so you are looking at
authenticated & owner

or

authenticated & superuser

wooden ravine
#

Exactly

young forum
#

then you could have
IsOwner or IsSuperUser

all implementing isAuthenticated

#

something like this should work

class IsAuthenticatedAndOwnerOrSuperUser(BasePermission):
def has_permission(self, request, view):
# Check is authenticated
# Check is owner or superuser

    return False
#

then use it in your permission classes

wooden ravine
#

Actually, my idea is to do the opposite of this. Instead of combining everything into one permission, I want to separate each one into its own class. I wanted to do something like: [IsAuthenticated AND (IsOwnerUser OR IsAdminUser)]. But I don't know what the correct syntax would be to make this work in my case. With decorators, it would be something like: [IsAuthenticated & (IsOwnerUser | IsAdminUser)].

young forum
#

yh this works too
[IsAuthenticated & (IsOwnerUser | IsAdminUser)].

inner grove
#

Official docs says you can

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

...

class ExampleView(APIView):
    permission_classes = [IsAuthenticated|ReadOnly]
...