How to use Django User Groups and Permissions on a React Frontend with Django Rest Framework
Asked Answered
C

1

10

I am using Django Rest Framework with React on the Frontend. I am using Token Athentication and its all working fine. I now have a requirement of making sure different users can access different things depending on their rights. This is possible using Django admin but my users will be using the React frontend.

I looked through Django Rest permissions but I didnt see how I can use this on my React Frontend. I also looked at Django guardian but I am not sure if its what I need for my requirement. I have looked through many tutorials and articles but I can't seem to find any straight forward way to achieve this.

Here is the approach I have used sofar: Created a Serializer for the inbuilt User Model, then Created a ViewSet and I can now access the list of users through the api.

from django.contrib.auth.models import User

class UserSerializer(SerializerExtensionsMixin,serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

class UserViewSet(SerializerExtensionsAPIViewMixin, viewsets.ModelViewSet):
    serializer_class = UserSerializer
    queryset = User.objects.all()

router = DefaultRouter()
router.register(r'user', UserViewSet, basename='user')

Using this I am able to access a user with the groups and permissions as shown in the picture below. I am now going ahead to call the api url on my React frontend and somehow use the permissions and groups associated with the user to control what the users can see.

Is there a better way to achieve this requirement? Am I doing this the right way? Has someone done this and may be I can borrow from their experience?

enter image description here

Celestina answered 1/2, 2019 at 12:44 Comment(2)
You can serialize groups and permissions too, and use that serializer inside user serialzer. Save that groups and permissions of the user in your redux store(i guess you are using redux for managing state). Then you can check permissions with group/permission name instead of relying on id, as id can change on dev and prod environment. In react write a custom component which will get what groups and permissions can view it by props. It can connect to redux store and check if user belongs to that group or not, and render the children or redirect. Then wrap your stuff inside that componentSix
Did you solve this problem, if how?Carcassonne
P
1

DRF provides permission classes, Also if you need some customization you can do so by creating custom permission classes. Refer https://www.django-rest-framework.org/api-guide/permissions/#api-reference.

On React side if you are using React router you can guard each route on some roles /permissions received from backend. Refer https://hackernoon.com/role-based-authorization-in-react-c70bb7641db4 This might help you

Polariscope answered 1/2, 2019 at 12:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.