from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model

from django.db.models import Q

from .models import User

class EmailOrPhoneNoAuthBackend(ModelBackend):
    def authenticate(email=None, password=None, **kwargs):

        user = User.objects.filter(Q(email__iexact=email) | Q(phone_no=email)).filter(is_active=True).first()

        if user and user.check_password(password):
            return user

        return None


    def get_user(self, user_id):
        """
        Overrides the get_user method to allow users to log in using their email address.
        """
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None