Search code examples
python-3.xdjangoauthenticationdjango-rest-frameworkdjango-views

Django Logout is not deleting cookie from browser and casing error while try to log in for second time


Here is code for login and logout view. When try to log in for first time cookie is set but on logout it doesn't update cookie or delete it from browser causing error in login attempt.

    @csrf_exempt
    def post(self, request):
        try:
            email = request.data.get('email')
            password = request.data.get('password')
            user = authenticate(request, username=email, password=password)
            if user is not None:
                request.session.set_expiry(86400*30) # 30 days
                login(request, user)
                user_obj = Customer.objects.get(email=email, password=password)
                return Response({'user_id': user_obj.id}, status=status.HTTP_200_OK)
            else:
                return  Response({'message': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED)
        except Exception as e:
            return Response("Internal Server Error",status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class LogoutView(APIView):
    @csrf_exempt
    def post(self, request):
        try:
            logout(request)
            # delete cookie
            response = JsonResponse({'message': 'Logout successful'}, status=status.HTTP_200_OK)
            response.delete_cookie('sessionid')
            response.delete_cookie('csrftoken')
            return response
        except Exception as e:
            print('error logout ==>',e)
            return Response("Internal Server Error",status=status.HTTP_500_INTERNAL_SERVER_ERROR)```

Solution

  • had the same issue, might not the solution you are looking for, but setting the cookie again with an empty string did the job for me.

    class LogoutAPI(APIView):
        permission_classes = [
            IsAuthenticated,
        ]
        def post(self, request):
            invalidate_user_cache(request.user)
            response = Response(
                {"msg": "Logged out successfully", "isAuthenticated": False, "user": None},
                status=status.HTTP_200_OK,
            )
            response.set_cookie(
                key="access_token",
                value="",
                expires=1,
                httponly=True,
                samesite="Strict",
                secure=True,
                path="/")
            response.set_cookie(
                key="refresh_token",
                value="",
                expires=1,
                httponly=True,
                samesite="Strict",
                secure=True,
                path="/"
            )
    
            return response