I'm using DRF and NextJS(app router) to build an application with a search feature that saves the authenticated user's search history. The search history is their search terms with a timestamp and only the authenticated User can access them.
I'm trying to figure out if I need to serialize the user's permissions from the DRF view so that NextJS can consume them and exactly how to do that?
So here is one of the class based DRF views:
class SearchHistoryListCreateAPIView(ListCreateAPIView):
permission_classes = [IsAdminUser | IsCurrentUser & IsAuthenticated, IsOwnerPermission]
serializer_class = SearchHistorySerializer
queryset = SearchHistory.objects.all()
Here is my SearchHistory serializer:
class SearchHistorySerializer(serializers.ModelSerializer):
class Meta:
model = SearchHistory
fields = ['term_id', 'account', 'term']
Do I need to serialize the permissions and if so how do I go about including them in the serializer so that NextJS can consumer them?
It is not necessary to serialize permissions directly in Django REST Framework because Permissions are handled at the view or viewset level to authorize access to actions.
Permission is different from Serialization. Permissions are for authorization, which determines if a user is allowed to perform an action whilst Serialization deals with representing data in a specific format (e.g. JSON), for output.
You should only serialize user permissions if you are required to expose user permissions in your API response.
Lastly, for the permission_classes
in your view, if you want to allow access to only authenticated users as indicated in your question, this should do:
permission_classes = [IsAuthenticated]