Skip to content

Instantly share code, notes, and snippets.

@fission6
Created October 11, 2011 17:23
Show Gist options
  • Save fission6/1278736 to your computer and use it in GitHub Desktop.
Save fission6/1278736 to your computer and use it in GitHub Desktop.
django authentication using an email or username
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
class EmailorUsernameBackend(ModelBackend):
"""
Authenticate given a users email or user name.
Does a double look up on email and user name but would rather
call super for ModelBackend to keep up with any changes.
put the following in your settings.py
AUTHENTICATION_BACKENDS = ('yourproject.app.backend.EmailorUsernameBackend',)
"""
def authenticate(self, username=None, password=None):
try:
#probably should be more stricy about email format
if '@' in username:
user = User.objects.get(email=username)
username = user.username
except User.DoesNotExist:
return None
return super(EmailorUsernameBackend, self).authenticate(username=username, password=password)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment