I created this custom permission class and it does not seem to be called when I make a request from the view. I event set it to return false and requests are still successful. Tried placing a print statement to see if there would be any output but no. Not sure what I'm doing wring.
View:
class EventEditView(RetrieveUpdateDestroyAPIView):
authentication_classes = (SessionAuthentication, JSONWebTokenAuthentication, )
permission_classes = (EventVisibilityPerm, )
serializer_class = EventEditSerializer
def get(self, request, *args, **kwargs):
event = get_object_or_404(Event, slug=kwargs['slug'])
serializer = EventSerializer(event)
return Response(serializer.data)
Permissions.py:
class EventVisibilityPerm(permissions.BasePermission):
"""
Permission class determines whether a user has access to a specific Event
"""
def has_object_permission(self, request, view, obj):
user = request.user
if obj.user == user:
return True
**Serializer: **
class EventSerializer(serializers.ModelSerializer):
class Meta:
model = Event
exclude = ('user', 'id')
Currently testing permissions for this detail view but this permission will also need to be used on a List view.
You MUST implement the has_permission(self, request, view)
method while creating the custom permission classes.
From the DRF Doc,
The instance-level
has_object_permission
method will only be called if the view-levelhas_permission
checks have already passed.
Example:
from rest_framework import permissions
class EventVisibilityPerm(permissions.BasePermission):
def has_permission(self, request, view):
"""
allowing users with specific email ids
"""
if request.user.email in EMAIL_WHITELIST:
return True
return False
def has_object_permission(self, request, view, obj):
"""
allowing users those who are the owner of the object (obj.user)
"""
return request.user == obj.user