Skip to content

Instantly share code, notes, and snippets.

@tijs
Created December 16, 2013 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tijs/7988341 to your computer and use it in GitHub Desktop.
Save tijs/7988341 to your computer and use it in GitHub Desktop.
Custom backend for case insensitive login with email address to prevent login failures for people who created their accounts on device that automatically uppercases input fields (i.e. iOS)
from __future__ import unicode_literals
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
class CustomModelBackend(ModelBackend):
"""
Subclass the default ModelBackend
"""
def authenticate(self, username=None, password=None, **kwargs):
UserModel = get_user_model()
if username is None:
username = kwargs.get(UserModel.USERNAME_FIELD)
try:
# replace default lookup with case insensitive lookup by email
# note: this presumes a CustomUser and login form that saves email to username field
#user = UserModel._default_manager.get_by_natural_key(username)
user = UserModel.objects.get(email__iexact=username)
if user.check_password(password):
return user
except UserModel.DoesNotExist:
# Run the default password hasher once to reduce the timing
# difference between an existing and a non-existing user (#20760).
UserModel().set_password(password)
# custom auth backend replaces default ModelBackend
AUTHENTICATION_BACKENDS = ('core.backends.CustomModelBackend',)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment