#Can't I use the OR operator in permission classes?
19 messages · Page 1 of 1 (latest)
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.
I achieved this with
class GetPatientVitalsView(APIView):
permission_classes = [IsDoctorUser | IsNurseUser]
where IsDoctoUser and IsNurseUser are custom permission classes
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?
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
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
and how do you want to use it
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.
so you are looking at
authenticated & owner
or
authenticated & superuser
Exactly
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
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)].
yh this works too
[IsAuthenticated & (IsOwnerUser | IsAdminUser)].
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]
...