Created
October 11, 2011 17:23
-
-
Save fission6/1278736 to your computer and use it in GitHub Desktop.
django authentication using an email or username
This file contains 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 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