Use email addresses for user name

 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
from django.contrib.auth.models import User
from django.core.validators import email_re

class BasicBackend:
    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

class EmailBackend(BasicBackend):
    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

  1. Use email addresses for user name for django 1.0+ by jasongreen 3 years, 4 months ago
  2. Login with email or username by zeeg 4 years, 9 months ago
  3. Use email addresses for user name for django 1.3 by kidzik 1 year, 11 months ago
  4. Email or username authentication with masquerading by petrilli 3 years, 11 months ago
  5. Case Insensitive Authentication Backend by ericflo 4 years, 2 months ago

Comments

bluszcz (on March 15, 2007):

Does it works admin app? In my case not :)

#

robbie (on April 16, 2007):

This is certainly a useful snippet, but it seems a little over complicated. What's wrong with just:

from django.contrib.auth.backends import ModelBackend
from django.core.validators import email_re
from django.contrib.auth.models import User

class EmailBackend(ModelBackend):
    def authenticate(self, username=None, password=None):
        if email_re.search(username):
            try:
                user = User.objects.get(email=username)
                if user.check_password(password):
                    return user
            except User.DoesNotExist:
                return None
        return None

...and then just adding it in front of Django's ModelBackend?

AUTHENTICATION_BACKENDS = (
    "emailauth.EmailBackend",
    "django.contrib.auth.backends.ModelBackend",
)

#

adurdin (on May 4, 2007):

The admin login view displays a message "Your email address is not your username" if you attempt to login with an email address and password that do not match (e.g. mistyped the password).

#

Paperface (on May 14, 2007):

adurdin: Alter your template registration/login.html to reflect the change in authentication method.

chris: Just thought I'd let you know, I'm using this and it seems to work very well

Thanks

#

zgoda (on July 12, 2007):

The problem is, the email field in User model is not unique, so you have to do 2 things: monkeypatch your database by addinng necessary constraint to the email field and generate some-kind-of-unique username. Unfortunately, the field is only allowed to keep 30 characters, so you cann't just use munged email or md5 hash for username...

#

zgoda (on August 28, 2007):

More problems with this. Users of our applications keep reporting me various places in django's own admin where "weird" usernames are shown. Sometimes it's really hard to customize admin templates to display something other than default __str__ provided by Django. I'm thinking on dynamic replacing __str__ in django.contrib.auth.models.User, maybe using signals?

#

mawoodall (on November 9, 2007):

The key to having this work with user object functions like 'has_perm()' and the admin interface is that you have to add both the new and default backends to your settings file:

'AUTHENTICATION_BACKENDS = ( 'yourproject.email-auth.EmailBackend', "django.contrib.auth.backends.ModelBackend", ) '

#

cogat (on January 17, 2008):

One other thing - the max_length for username in contrib.auth.forms.login is 30. It should be increased to the length of the email field, 75 characters by default.

#

Rich (on February 7, 2008):

One other thing - the max_length for username in contrib.auth.forms.login is 30. It should be increased to the length of the email field, 75 characters by default

Sorry if this is a dumb question, but what would be the correct way to do that?

#

lars.yencken (on May 9, 2008):

Rich: Probably two ways. Firstly, you can manually alter the database yourself after running syncdb. In fact, you could hook a callback onto the post_syncdb signal to do it automatically every time. Secondly, you could simply edit the django source which is installed to change the field width. Find and edit the User class in django/contrib/auth/models.py.

#

crucialfelix (on June 28, 2008):

lars: I misread this the first time too. cogat is saying the the FORM field is limited to 30 chars. nothing to do with the db. the database still stores a username (whatever you want, random, truncated version of email etc.) but the EmailBackend checks against the EMAIL in the db. the db does not have to be altered thus.

#

jturnbull (on August 1, 2008):

Also see this blog post which does a similar thing, but looks for a separate "email" argument to the "authenticate" method.

#

vizualbod (on August 30, 2008):

In Django 1.0 (since beta2) replace

from django.core.validators import email_re

with

from django.forms.fields import email_re

Frank, web development Manchester

#

cornbread (on October 28, 2008):

How can we make it so there is no username field at all? We have 20,000 Users and they all use their emails currently. (making a switch to django)

#

peterbraden (on May 21, 2009):

This is good, but there is a problem - the authentication form limits usernames to 30 characters - emails longer than that are rejected by the charfield clean method. To properly allow for the (legitimate) case of emails longer than 30 characters the authentication views need to be overridden.

#

peterbraden (on May 22, 2009):

A solution for the problem is suggested here: http://groups.google.com/group/django-developers/msg/3420dc565df39fb1

Basically you can monkey patch the form with:

AuthenticationForm.base_fields['username'].max_length = 75

#

jackoder (on April 4, 2010):

Thanks dear.

This snippet solves my issue. It's a bit hard to use OOP class but well.

Funny Games - Kids Games

Thanks.

#

sijojamesjohn (on July 1, 2010):

In any models.py

from django.contrib.auth.forms import AuthenticationForm

AuthenticationForm.base_fields['username'].max_length = 75

#

lorochka85 (on July 1, 2010):

Please, take a look at: django.contrib.auth.authenticate What I see there is that you can pass any credentials to your backend, so instead of toying with username, why not just pass email to it:

from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User

class EmailBackend(ModelBackend):
    def authenticate(self, email=None, password=None):
        try:
            user = User.objects.get(email=email)
            if user.check_password(password):
                return user
        except (User.DoesNotExist,  User.MultipleObjectsReturned):
            pass
        return None

#

starpilot (on December 11, 2010):

I'm a django neophyte, but it appears maintaining the username parameter is required to use the django.contrib.auth.views.login view. Could be wrong though.

#

profkolade (on June 7, 2011):

CONTRACT REVIEW COMMITTEE OFFICE OF THE PRESIDENCY FEDERAL REPUBLIC OF NIGERIA.

Attention: Beneficiary,

For your kind attention, I am Prof.Kolade manager audit/credit department in a banking institution, I will be very glad if you do assist me to relocate the sum of (US$10,000.000.00 Million Dollars) to your personal bank account to be of an immense benefit to both of us. This account belong to one of our foreign customers (Late) Mr. Moises Saba Masri. He was one of the board shareholders in telecommunication in Mexico; he died on a helicopter crash. You can get more information's on the site web address below.

http://www.ynetnews.com/articles/0,7340,L-3832556,00.html?

All legal documents to back up the claims will be obtain legally here, I shall be directing you on the process I don't want this money diverted into our Bank recovery account as unclaimed fund; meanwhile the ministry of finance and economic has issued an order to release any unclaimed fund immediately whenever the next of kin is discovered with dully application. On this regards, I seek your consent to present you as the next of kin / will beneficiary to the deceased so that the proceeds of this account can be transfer to you. This payment will be effected through Swift Transfer in conjunction with the foreign exchange department, Ministry of Finance Nigeria.

This is 50/45 business deal because of your account and support, I will get 50%, you will get 45% while 5% will be taken out to reimburse for any expenses before the fund get to your care. I will come over to your country as soon as the fund is transfer successfully into your account. Also this matter should be a confidential between you and me, please delete it if you are not interested. Upon the receipt of your reply and indication of your capability, I will send to you a draft text of application form to apply for the claim and more details; I don't want any one here in the bank to know my involvement during the process.

Please state your information below to know your capability of handling this transaction;

Full Name: Address: Age: sex: Occupation: Nationality: Phone number:

Send your reply to profkolade20@gmail.com

Your's faithfully, Prof.Kolade

#

naesenwechri (on January 21, 2012):

[HTML_REMOVED][HTML_REMOVED]��[HTML_REMOVED][HTML_REMOVED] | [HTML_REMOVED][HTML_REMOVED]����[HTML_REMOVED][HTML_REMOVED] | [HTML_REMOVED][HTML_REMOVED]�����[HTML_REMOVED][HTML_REMOVED] | [HTML_REMOVED][HTML_REMOVED]������[HTML_REMOVED][HTML_REMOVED] | [HTML_REMOVED][HTML_REMOVED]�����[HTML_REMOVED][HTML_REMOVED][HTML_REMOVED] [HTML_REMOVED][HTML_REMOVED]�Ϳ���[HTML_REMOVED][HTML_REMOVED][HTML_REMOVED] [HTML_REMOVED][HTML_REMOVED]����[HTML_REMOVED][HTML_REMOVED][HTML_REMOVED] [HTML_REMOVED][HTML_REMOVED]��[HTML_REMOVED][HTML_REMOVED][HTML_REMOVED] [HTML_REMOVED][HTML_REMOVED]������a>[HTML_REMOVED][HTML_REMOVED] [HTML_REMOVED][HTML_REMOVED]������a>[HTML_REMOVED][HTML_REMOVED]

#

cochiseruhulessin (on March 4, 2012):

"the field is only allowed to keep 30 characters, so you cann't just use munged email or md5 hash for username..."

A base64 encoding of an md5 hash has 25 characters.

#

kourosh (on June 19, 2012):

Can someone do a review and propose the best solution? thanks

#

RobertPattinson (on July 30, 2012):

you can manually alter the database yourself after running syncdb. In fact, you could hook a callback onto the post_syncdb signal to do it automatically every time.In any models.py

from django.contrib.auth.forms import AuthenticationForm

AuthenticationForm.base_fields['username'].max_length = 75

#

Thanks! RP ---iPhone 4 Cases-iPhone 4s Cases---

#

siblek31 (on April 13, 2013):

Sekitar abad ke-3 Masehi, Romawi cara cepat hamil Gaul mengalami krisis serius dengan "limau" nya (perbatasan dibentengi melindungi Kekaisaran) menyeberang pada beberapa kesempatan oleh barbar [27] soal ulangan harian sd Kelemahan dari kekuasaan kekaisaran pusat, saat ini, yang dipimpin Gallo-Romawi. pemimpin untuk memproklamasikan belajar bahasa inggris cepat kemerdekaan dari Kekaisaran Galia berumur pendek, [27] yang berakhir dengan Pertempuran Châlons di 274, yang melihat Gaul reincorporated di Kekaisaran Romawi.

Namun demikian, situasi membaik di kursus teknisi komputer paruh pertama abad ke-4, yang merupakan periode kebangkitan dan kemakmuran bagi Romawi Gaul. [28] Pada tahun 312, kaisar Constantin saya click here menjadi Kristen. Kristen, dianiaya sampai saat itu, dikalikan di seluruh Kekaisaran Romawi. [29] Tapi, dari paruh kedua kursus bahasa inggris online abad ke-4, para Invasi Barbar mulai lagi, [30] dan suku-suku Jermanik, seperti Vandal, Suebi dan Alans menyeberangi Rhine dan menetap di Gaul, Spanyol dan bagian lain dari Kekaisaran mendapatkan uang dari internet Romawi runtuh. [31]

#

(Forgotten your password?)