How best can I access content while the user is not logged in. For example, I have the View which handles both Listing and posting blog posts , though I want someone to access content even without being logged In, though the person shouldn't create a blog post, unless logged In.
Below is my current implementation :
class PostList(generics.ListCreateAPIView):
"""Blog post lists"""
queryset = Post.objects.all()
serializer_class = serializers.PostSerializer
authentication_classes = (JWTAuthentication,)
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data, context=request)
if serializer.is_valid():
serializer.save()
return response.Response(serializer.data,
status=status.HTTP_201_CREATED, )
return response.Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
So how best can I play with these lines :
authentication_classes = (JWTAuthentication,)
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
EDIT :
because when I remove this line :
authentication_classes = (JWTAuthentication,)
I can't access the lists of blogs, I get this response :
{
"detail": "You do not have permission to perform this action."
}
though I will need an endpoint of creating a blog posts to be protected, how best can this be achieved
CodePudding user response:
Create a custom permission by inheriting the permissions.BasePermission
class and override the has_permission
method according to your requirements.
class PostsProtectOrReadOnly(permissions.BasePermission):
def has_permission(self, request, view):
if request.method not in permissions.SAFE_METHODS\
and not request.user.is_authenticated:
return False
return True
The permissions.SAFE_METHODS
is a tuple containing GET
, HEAD
& OPTIONS
methods which are basically read-only methods. So if a user requests to create a new entry then the method used will be POST
method which is not considered as safe method. And to check if the user is loggedIn or not use request.user.is_authenticated
.
And now use the custom permission for you api view.
class PostList(generics.ListCreateAPIView):
"""Blog post lists"""
serializer_class = serializers.PostSerializer
authentication_classes = (JWTAuthentication,)
permission_classes = (PostsProtectOrReadOnly,)
queryset = Post.objects.all()