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

# Custom authentication backend to allow login with either username or email
class UsernameOrEmailBackend(ModelBackend):
    """Allow users to log in with either username or email"""
    
    def authenticate(self, request, username=None, password=None, **kwargs):
        """Authenticate using username or email (case insensitive)"""
        try:
            # Use filter().first() to avoid MultipleObjectsReturned exception
            user = User.objects.filter(
                Q(username__iexact=username) | Q(email__iexact=username)
            ).first()
            
            if user and user.check_password(password) and self.user_can_authenticate(user):
                return user
        except Exception:
            pass
        
        return None
