Enable login-by-email with the default User model for your Django project by making auth.User.email unique. 
"""
django-unique-user-email

Enable login-by-email with the default User model for your Django project by
making auth.User.email unique.
"""

__version__ = "23.1"

src/unique_user_email/__init__.py
carltongibson/django-unique-user-email
from django.apps import AppConfig


class UniqueUserEmailConfig(AppConfig):
    default_auto_field = "django.db.models.BigAutoField"
    name = "unique_user_email"

    def ready(self):
        from django.contrib.auth.models import User
        from django.db import models

        # Updating the field itself triggers the auto-detector
        # field = User._meta.get_field("email")
        # field._unique = True
        #
        # But setting a constraint does not...
        User.Meta.constraints = [
            models.UniqueConstraint(
                name="unique_user_email",
                fields=["email"],
                # deferrable=models.Deferrable.DEFERRED,
            ),
        ]
        User._meta.constraints = User.Meta.constraints
        # ... as long as original_attrs is not updated.
        # User._meta.original_attrs["constraints"] = User.Meta.constraints

src/unique_user_email/apps.py
carltongibson/django-unique-user-email
from django.contrib.auth.backends import BaseBackend
from django.contrib.auth.models import User


class EmailBackend(BaseBackend):
    """
    Authentication backend to allow login by email.

    - authenticate() uses email and password credentials.
    """

    def get_user(self, user_id):
        try:
            user = User.objects.get(pk=user_id, is_active=True)
        except User.DoesNotExist:
            return None
        return user

    def authenticate(self, request, email=None, password=None, **kwargs):
        if email is None or password is None:
            return

        try:
            user = User.objects.get(email=email, is_active=True)
        except User.DoesNotExist:
            # Run the default password hasher once to reduce the timing
            # difference between an existing and a non-existing user. See ModelBackend.
            User().set_password(password)
        else:
            if user.check_password(password):
                return user

src/unique_user_email/backend.py
carltongibson/django-unique-user-email
from django import forms
from django.contrib.auth import authenticate
from django.contrib.auth.forms import UsernameField
from django.core import exceptions, validators


class AuthenticationForm(forms.Form):
    """
    Form allowing login by username or email.

    - Takes login and password.
    - Maps to credentials for authentication, using email if login is an email
      address.
    - Exposes the user for use in the view.
    """

    login = UsernameField(max_length=150, label="Username or Email")
    password = forms.CharField(
        label="Password",
        widget=forms.PasswordInput(attrs={"autocomplete": "current-password"}),
    )

    def __init__(self, request=None, *args, **kwargs):
        self.request = request  # ???: Do we need this?
        self.user_cache = None
        super().__init__(*args, **kwargs)

    def get_credentials(self):
        """
        Maps the login to credentials for authentication.

        If the login is an email address, use the email kwarg, otherwise use
        the username kwarg.
        """
        credentials = {}
        login = self.cleaned_data.get("login")
        if self.is_email(login):
            credentials["email"] = login
        else:
            credentials["username"] = login
        credentials["password"] = self.cleaned_data.get("password")
        return credentials

    def is_email(self, login):
        try:
            validators.validate_email(login)
            is_email = True
        except exceptions.ValidationError:
            is_email = False
        return is_email

    def clean(self):
        super().clean()
        if self._errors:
            print(self._errors)
            return

        credentials = self.get_credentials()
        self.user_cache = authenticate(self.request, **credentials)
        if self.user_cache is None:
            raise forms.ValidationError(
                "Please enter a correct username/email and password. Note that both "
                "fields are case-sensitive."
            )
        return self.cleaned_data

    def get_user(self):
        return self.user_cache

src/unique_user_email/forms.py
carltongibson/django-unique-user-email
from django.db import migrations, models


class CustomAddConstraint(migrations.AddConstraint):
    """
    Override app_label to target auth.User
    """

    def state_forwards(self, app_label, state):
        state.add_constraint("auth", self.model_name_lower, self.constraint)

    def database_forwards(self, app_label, schema_editor, from_state, to_state):
        model = to_state.apps.get_model("auth", self.model_name)
        if self.allow_migrate_model(schema_editor.connection.alias, model):
            schema_editor.add_constraint(model, self.constraint)

    def database_backwards(self, app_label, schema_editor, from_state, to_state):
        model = to_state.apps.get_model("auth", self.model_name)
        if self.allow_migrate_model(schema_editor.connection.alias, model):
            schema_editor.remove_constraint(model, self.constraint)


class Migration(migrations.Migration):
    dependencies = [
        ("auth", "0012_alter_user_first_name_max_length"),
    ]

    operations = [
        CustomAddConstraint(
            model_name="user",
            constraint=models.UniqueConstraint(
                fields=("email",), name="unique_user_email"
            ),
        ),
    ]

src/unique_user_email/migrations/0001_initial.py
carltongibson/django-unique-user-email
# Empty models.py to trigger migrations framework for app.

src/unique_user_email/models.py
carltongibson/django-unique-user-email

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-0=i&_r*xt0vq4e4wy5$qg-4@i5wd)gnsc89^iy7=gx@gw7ycqr"

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",

    "unique_user_email",
    "tests",
]

AUTHENTICATION_BACKENDS = [
    'unique_user_email.backend.EmailBackend',
    'django.contrib.auth.backends.ModelBackend',
]

LOGIN_REDIRECT_URL = "/admin/"

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]

ROOT_URLCONF = "tests.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
        },
    },
]

WSGI_APPLICATION = "tests.wsgi.application"


# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": BASE_DIR / "db.sqlite3",
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/

STATIC_URL = "static/"

# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

tests/settings.py
carltongibson/django-unique-user-email
from django import forms
from django.conf import settings
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.db import IntegrityError
from django.test import TestCase
from unique_user_email.backend import EmailBackend
from unique_user_email.forms import AuthenticationForm


class UniqueEmailTestCase(TestCase):
    def setUp(self):
        self.user = User.objects.create_user(
            username="testuser",
            email="test@example.com",
            password="testpass",
        )

    def test_model_form_disallows_duplicate_emails(self):
        class UserForm(forms.ModelForm):
            class Meta:
                model = User
                fields = ["username", "email"]

        form = UserForm(
            data={
                "username": "testuser2",
                "email": self.user.email,
            }
        )
        self.assertIs(False, form.is_valid())

    def test_full_clean_disallows_duplicate_emails(self):
        user2 = User(
            username="testuser2",
            email=self.user.email,
            password="testpass2",
        )

        with self.assertRaisesMessage(
            ValidationError,
            "User with this Email address already exists.",
        ):
            user2.full_clean()

    def test_model_save_disallows_duplicate_emails(self):
        user2 = User(
            username="testuser2",
            email=self.user.email,
            password="testpass2",
        )
        with self.assertRaisesMessage(
            IntegrityError,
            "UNIQUE constraint failed: auth_user.email",
        ):
            user2.save()


class EmailBackendTests(TestCase):
    def test_none_for_username_logins(self):
        """
        Authenticate with username and password returns None.
        """
        request = None
        backend = EmailBackend()
        self.assertIsNone(
            backend.authenticate(request, username="testUser", password="testPassword")
        )

    def test_user_can_login_with_email(self):
        """
        Authenticate with email and password returns the user.
        """
        user = User.objects.create_user(
            username="testUser", email="a@b.com", password="testPassword"
        )
        request = None
        backend = EmailBackend()
        authed_user = backend.authenticate(
            request, email="a@b.com", password="testPassword"
        )
        self.assertEqual(user, authed_user)

    def test_email_backend_is_installed(self):
        """
        EmailBackend is listed in settings.AUTHENTICATION_BACKENDS.
        """
        self.assertIn(
            "unique_user_email.backend.EmailBackend",
            settings.AUTHENTICATION_BACKENDS,
        )


class AuthenticationFormTests(TestCase):
    def setUp(self) -> None:
        self.user = User.objects.create_user(
            username="testUser",
            email="a@b.com",
            password="testPassword",
            is_staff=True,
        )

    def test_get_credentials_with_email(self):
        """
        get_credentials() returns email kwarg.
        """
        form = AuthenticationForm(data={"login": "a@b.com", "password": "testPassword"})
        self.assertIs(True, form.is_valid(), form.errors)
        self.assertEqual(
            {"email": "a@b.com", "password": "testPassword"}, form.get_credentials()
        )

    def test_login_view(self):
        tests = ["testUser", "a@b.com"]
        for test in tests:
            with self.subTest(login=test):
                data = {"login": test, "password": "testPassword"}
                url = "/accounts/login/"
                response = self.client.post(url, data=data)
                self.assertRedirects(
                    response,
                    settings.LOGIN_REDIRECT_URL,
                )

tests/tests.py
carltongibson/django-unique-user-email
"""
URL configuration for tests project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.contrib.auth.views import LoginView
from django.urls import path

from unique_user_email.forms import AuthenticationForm


urlpatterns = [
    # https://docs.djangoproject.com/en/dev/topics/auth/default/#module-django.contrib.auth.views
    path(
        "accounts/login/",
        LoginView.as_view(form_class=AuthenticationForm),
        name="login",
    ),
    path("admin/", admin.site.urls),
]

tests/urls.py
carltongibson/django-unique-user-email