from django.contrib.auth import get_user_model from django.db.models import Q from rest_framework.response import Response from rest_framework.status import HTTP_201_CREATED, HTTP_400_BAD_REQUEST from rest_framework.views import APIView from rest_framework.permissions import AllowAny from .serializers import UserLoginSerializer from django.contrib.auth.backends import ModelBackend User = get_user_model() class CustomBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): try: user = User.objects.get(Q(username=username)|Q(email=username)) if user.check_password(password): return user except Exception as e: return None class UserLoginAPIView(APIView): permission_classes = [AllowAny] serializer_class = UserLoginSerializer def post(self, request, *args, **kwargs): data = request.data serializer = UserLoginSerializer(data=data) if serializer.is_valid(raise_exception=True): login_data = serializer.data return Response(login_data, HTTP_201_CREATED) else: return Response(serializer.errors, HTTP_400_BAD_REQUEST)