Created
December 16, 2013 14:58
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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