Reputation: 19
We are using Django 1.11 with Django Rest Framework and trying to implement some advanced permissioning system.
Currently, we have some tehnical issues and one of them is: return linked permissions for currently logged in user (by request.user) on every request.
Example: endpoint http://localhost:8000/articles/1/ should return information about that article and linked permissions to the user. Something like this:
{'title': 'Article Title', 'pages': 50, 'permissions': ['can_read_article', 'can_update_article'] ...}
Those permissions should be managed inside Django Admin > Users & Groups system.
Thanks a lot, any help will be appreciated
Upvotes: 0
Views: 150
Reputation: 1966
You can try to achieve this by using Serializer Method Field to grab that information:
class ArticleSerializer(serializers.ModelSerializer):
permissions = serializers.SerializerMethodField()
def get_permissions(self, obj):
user = self.context['request'].user
# compute permissions
#permissions = user.get_all_permissions() # if you are using Django's permissions, see note below
permissions = get_perms(user, obj) # if you are using django-guardian
return permissions
Note that if you are using Django's permissions from django.contrib.auth
which has no object level permissions, I do not thing your approach is the optimal one: Instead of returning all the permissions on each request, it would be more efficient to grab all user's permissions by a separate call and store that somewhere in your frontend to use it later.
On the other hand, if you are using object level permissions, like with django-guardian
then this approach seems suitable.
Upvotes: 0