from rest_framework import views, status
from rest_framework.response import Response
from django.contrib.auth import authenticate, login,logout
from rest_framework.permissions import AllowAny, IsAuthenticated
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
class LoginView(views.APIView):
permission_classes=[AllowAny]
def post(self, request):
username = request.data.get('username')
password = request.data.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return Response({'message': 'Logged in successfully'}, status=status.HTTP_200_OK)
return Response({'message': 'Invalid credentials'}, status=status.HTTP_400_BAD_REQUEST)
class LogoutView(views.APIView):
def post(self, request):
logout(request)
return Response({'message': 'Logged out successfully'}, status=status.HTTP_200_OK)
@csrf_exempt
def logoutView(request):
print(request.COOKIES)
logout(request)
return JsonResponse({'message': 'Logged out successfully'}, status=status.HTTP_200_OK)
class UserInfoView(views.APIView):
permission_classes=[IsAuthenticated]
def get(self, request):
user = request.user
return Response({'username': user.username}, status=status.HTTP_200_OK)
When sending request to login or userinfoview it works fine with csrf tokens. however the class LogoutView returns forbidden 403. The logoutView FUNCTION works fine ONLY when csrf_exmpt is applied. when printing request.cookies its returning:
{‘csrftoken’: ‘DdQZJC56QBSAcDqXVlrXz4mMeVWitpNV’, ‘sessionid’: ‘poul3qidl8xw4k5bp2rwazbxo76eq9sq’}
which is what it returns in all the other classes as well. i tried to csrf exmpt the class because thats what i ultimitly want to use instead of the function for the cleaner looking code but couldnt figure out how to exmpt the class. moreover, i dont want to exmpt the csrf to begin with unless its the only solution.