Skip to content

Instantly share code, notes, and snippets.

@santoshpy
Last active September 28, 2017 05:11
Show Gist options
  • Save santoshpy/90e8098bde0046905c8b27ab2fcbf239 to your computer and use it in GitHub Desktop.
Save santoshpy/90e8098bde0046905c8b27ab2fcbf239 to your computer and use it in GitHub Desktop.
Extends default django ModelBackend for both Email Authentication and Username Authentication against settings.AUTH_USER_MODEL. i.e: user can login with either email or username.
# In any authentication related app create new file email_authentication_backends.py
from django.contrib.auth.models import User
from django.contrib.auth.backends import ModelBackend
class EmailAuthBackend(ModelBackend):
"""
Extends default django ModelBackend for both Email Authentication and Username
Authentication against settings.AUTH_USER_MODEL
i.e: user can login with either email or username.
"""
def authenticate(self, username=None, password=None, **kwargs):
if username is None:
username = kwargs.get('username')
try:
user = User.objects.get(email=username)
except User.DoesNotExist:
# Run the default password hasher once to reduce the timing
# difference between an existing and a non-existing user
User().set_password(password)
else:
if user.check_password(password) and self.user_can_authenticate(user):
return user
# In settings.py add AUTHENTICATION_BACKENDS
# Authentication with custom EmailBackend and default django ModelBackend
# NOTE: Overide <app_name> is with your custom app where your email_authentication_backends.py
AUTHENTICATION_BACKENDS = ['<app_name>.email_authentication_backends.EmailAuthBackend',
'django.contrib.auth.backends.ModelBackend',]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment