Skip to content

Instantly share code, notes, and snippets.

@victor-enogwe
Last active January 30, 2020 15:42
Show Gist options
  • Select an option

  • Save victor-enogwe/6af88ba8cf9ea1a0bdadddc7560994e9 to your computer and use it in GitHub Desktop.

Select an option

Save victor-enogwe/6af88ba8cf9ea1a0bdadddc7560994e9 to your computer and use it in GitHub Desktop.
Django Custom Model Backend - Enables Auth With Emails or Usernames
from django.contrib.auth.backends import ModelBackend, get_user_model
class EmailOrUsernameModelBackend(ModelBackend):
'''This is a ModelBacked that allows authentication with either a username or an email address.'''
def authenticate(self, request, username=None, password=None, **kwargs):
if username is None:
username = kwargs.get(get_user_model().USERNAME_FIELD)
if password is None:
password = kwargs.get(get_user_model().PASSWORD_FIELD)
# case insensitive lookup by email **email__iexact**
field = 'email__iexact' if '@' in username else 'username'
kwargs = { field: username }
try:
user = get_user_model().objects.get(**kwargs)
if user.check_password(password) and self.user_can_authenticate(user):
return user
except get_user_model().DoesNotExist:
# Run the default password hasher once to reduce the timing
# difference between an existing and a nonexistent user (#20760).
get_user_model().set_password(password)
@victor-enogwe
Copy link
Author

victor-enogwe commented Jan 30, 2020

replace the default model backend 'django.contrib.auth.backends.ModelBackend in AUTHENTICATION_BACKENDS with this backend.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment