from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend class CaseInsensitiveBackend(ModelBackend): """Usernames are one case-insensitive namespace (ADR-38): `Mario` and `mario` log in as the same account.""" def authenticate(self, request, username=None, password=None, **kwargs): User = get_user_model() if username is None or password is None: return None try: user = User.objects.get(username__iexact=username) except User.DoesNotExist: # Run the hasher anyway, so an unknown name costs as much as a wrong password (SEC-19). User().set_password(password) return None if user.check_password(password) and self.user_can_authenticate(user): return user return None