Skip to content

Instantly share code, notes, and snippets.

@bcarl
Created July 6, 2012 06:08
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bcarl/3058349 to your computer and use it in GitHub Desktop.
Save bcarl/3058349 to your computer and use it in GitHub Desktop.
Django Email as Username Authentication Backend
from django.contrib.auth.models import User, check_password
class LoginUsingEmailAsUsernameBackend(object):
"""
Custom Authentication backend that supports using an e-mail address
to login instead of a username.
See: http://blog.cingusoft.org/custom-django-authentication-backend
"""
supports_object_permissions = False
supports_anonymous_user = False
supports_inactive_user = False
def authenticate(self, username=None, password=None):
try:
# Check if the user exists in Django's database
user = User.objects.get(email=username)
except User.DoesNotExist:
return None
# Check password of the user we found
if check_password(password, user.password):
return user
return None
# Required for the backend to work properly - unchanged in most scenarios
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
# ...
AUTHENTICATION_BACKENDS = (
'project.backends.LoginUsingEmailAsUsernameBackend',
'django.contrib.auth.backends.ModelBackend',
)
# ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment