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?
Django Rest Framework makes it easy to use your Django Server as an REST API. REST stands for "representational state transfer" and API stands for application programming interface. Note that with DRF you easily have list and create views as well as authentication.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With