- Author:
- jasongreen
- Posted:
- December 29, 2009
- Language:
- Python
- Version:
- 1.1
- Score:
- 3 (after 3 ratings)
it is an rewrite of [http://www.djangosnippets.org/snippets/74/]
in settings.py AUTHENTICATION_BACKENDS = ( 'yourproject.email-auth.EmailBackend', )
Author: chris
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | """
@author: chris
"""
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
from django.forms.fields import email_re
class EmailBackend(ModelBackend):
"""
Authenticates against django.contrib.auth.models.User.
"""
def authenticate(self, username=None, password=None):
#If username is an email address, then try to pull it up
if email_re.search(username):
try:
user = User.objects.get(email=username)
except User.DoesNotExist:
return None
else:
#We have a non-email address username we should try username
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
return None
if user.check_password(password):
return user
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
thanx, very nice example
#
thanks, i had a hard time figuring out the correct solution due to all the comments in the /snippets/74/ thread.
#
Nice solution, thank you.
I did find a tiny edge-case problem with users who registered on my site, unregistered themselves, then re-registered again because this caused the
User.objects.get()
line to return > 1 result. To fix it, simply change,user = User.objects.get(email=username)
touser = User.objects.get(email=username, is_active=True)
on lines 16 and 22.#
Please login first before commenting.