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