Reputation: 2009
I would like to create a custom permission that return true / flase depending on whether the user is the author of a story or not and pass this information via the restAPI. So when the author is requesting a story where he is not author the permission returns "false" and i can access these information IsStoryOwner: "False"
via my API. Something like this should be the result:
"user": {
"id": 35,
"username": "HII",
"user_permissions": [
IsStoryOwner: "False",
]
}
However i struggle to implement that. I wrote the following permission:
class IsStoryOwner(permissions.BasePermission):
"""
Check if authenticated user is story author
"""
def has_object_permission(self,request,obj,**kwargs):
if request.user.id == story.author:
return True
return False
Than i integrated the permission in my UserAPI
class UserAPI(generics.RetrieveAPIView):
permission_classes = [
permissions.IsAuthenticated, IsStoryOwner
]
serializer_class = UserSerializer
def get_object(self):
return self.request.user
However the permission is not appearing in my API and the "user_permissions": []
remains empty.
Upvotes: 0
Views: 225
Reputation: 1117
You can use SerializerMethodField. Don't forget this, Django send 403 status code to client when your IsStoryOwner return False.
class UserSerializer(ModelSerializer):
user_permissions = SerializerMethodField()
class Meta:
fields = ('user_permissions', 'other_fields')
model = YourUserModel
def get_user_permissions(self, obj):
request = self.context['request'] #
return request.user.id == obj.story.author
Upvotes: 1