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):
    """
    Authentication backend for UUID-primary-key users.

    Must be the ONLY entry in AUTHENTICATION_BACKENDS.  Listing the base
    ModelBackend alongside it causes Django to call ModelBackend.get_user()
    which does not guard against invalid UUID strings and raises ValueError
    on stale / pre-migration session data (fatal in Python 3.13).

    Both get_user() and authenticate() catch all exceptions so that rows with
    malformed UUID primary keys (legacy integer IDs left over from before the
    UUID migration) never crash the request.  Those rows are simply treated as
    "not found".
    """

    def get_user(self, user_id):
        """
        Called by Django's AuthenticationMiddleware on every request to restore
        the logged-in user from the session.  user_id is whatever string was
        stored in _auth_user_id — may be a non-UUID value from an old session.
        """
        try:
            return UserModel._default_manager.get(pk=user_id)
        except Exception:
            # Catches DoesNotExist, ValueError / AttributeError from uuid.UUID()
            # coercion on bad values, and anything else the ORM might raise.
            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:
            user = UserModel._default_manager.get(
                Q(username=username) |
                Q(email=username) |
                Q(phone_number=username)
            )
        except UserModel.DoesNotExist:
            # Constant-time dummy hash to avoid timing attacks (#20760).
            UserModel().set_password(password)
            return None
        except Exception:
            return None
        else:
            if user.check_password(password) and self.user_can_authenticate(user):
                return user
        return None
