from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model
from django.db.models import Q

UserModel = get_user_model()

class UUIDModelBackend(ModelBackend):
    """
    Custom authentication backend that handles UUID-based users
    """
    def get_user(self, user_id):
        try:
            return UserModel._default_manager.get(pk=user_id)
        except (UserModel.DoesNotExist, ValueError):
            return None

    def authenticate(self, request, username=None, password=None, **kwargs):
        if username is None:
            username = kwargs.get(UserModel.USERNAME_FIELD)
        if username is None or password is None:
            return None
        try:
            # Try to fetch the user by username, email, or phone number
            user = UserModel._default_manager.get(
                Q(username=username) | 
                Q(email=username) | 
                Q(phone_number=username)
            )
        except UserModel.DoesNotExist:
            # Run the default password hasher once to reduce the timing
            # difference between an existing and a nonexistent user (#20760).
            UserModel().set_password(password)
        else:
            if user.check_password(password) and self.user_can_authenticate(user):
                return user 