HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux spn-python 5.15.0-89-generic #99-Ubuntu SMP Mon Oct 30 20:42:41 UTC 2023 x86_64
User: arjun (1000)
PHP: 8.1.2-1ubuntu2.20
Disabled: NONE
Upload Files
File: //home/arjun/projects/aigenerator/AI-LG-backend/Ai_logo_generation/authorization/backends.py
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model

User = get_user_model()

class EmailBackend(ModelBackend):
    """
    Custom authentication backend to authenticate users based on email and password.
    Only active users are considered for authentication.
    """
    def authenticate(self, request, username=None, password=None, **kwargs):
        # Use email instead of username
        email = kwargs.get('email')
        if email is None:
            return None
        
        # Get the first active user found by email
        try:
            user = User.objects.get(email=email, is_active=True)
        except User.DoesNotExist:
            return None
        except User.MultipleObjectsReturned:
            # If multiple active users are found, take the first one
            user = User.objects.filter(email=email, is_active=True).first()

        # Check if the password matches
        if user.check_password(password) and self.user_can_authenticate(user):
            return user
        
        return None