infrasynth-backend-kit/infrasynth/security/auth/backends.py
2026-08-28 14:38:47 -05:00

21 lines
780 B
Python

from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
class EmailOrUsernameBackend(ModelBackend):
"""Authenticate with email or username."""
def authenticate(self, request, username=None, password=None, **kwargs):
user_model = get_user_model()
if username is None:
username = kwargs.get(user_model.USERNAME_FIELD)
if not username or not password:
return None
try:
user = user_model.objects.get(Q(email=username) | Q(username=username))
except user_model.DoesNotExist:
return None
if user.check_password(password) and self.user_can_authenticate(user):
return user
return None