Login

Login with email or username

Author:
zeeg
Posted:
August 23, 2008
Language:
Python
Version:
.96
Tags:
email login auth backend
Score:
5 (after 7 ratings)

A simple backend which allows you to login with either an email address or a username.

It should be combined with another backend for checking permissions:

AUTHENTICATION_BACKENDS = (
    'myproject.accounts.backends.EmailOrUsernameModelBackend',
    'django.contrib.auth.backends.ModelBackend'
)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
from django.conf import settings
from django.contrib.auth.models import User

class EmailOrUsernameModelBackend(object):
    def authenticate(self, username=None, password=None):
        if '@' in username:
            kwargs = {'email': username}
        else:
            kwargs = {'username': username}
        try:
            user = User.objects.get(**kwargs)
            if user.check_password(password):
                return user
        except User.DoesNotExist:
            return None

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

More like this

  1. Email authentication backend by benjaoming 7 months, 3 weeks ago
  2. Email or username authentication with masquerading by petrilli 7 years, 2 months ago
  3. OracleAuthBackend by nosrednakram 7 years ago
  4. Case Insensitive Authentication Backend by ericflo 7 years, 5 months ago
  5. New forms signup validation by Batiste 9 years, 4 months ago

Comments

wozozo (on May 14, 2010):
<p>thanks!</p>

#

nhammond (on October 14, 2014):
<p>If you want to do this, be sure to forbid the '@' character in usernames. Otherwise some serious problems can arise.</p>

#

Please login first before commenting.