Case Insensitive Authentication Backend

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from django.contrib.auth.models import User
 
class CaseInsensitiveModelBackend(object):
    def authenticate(self, username=None, password=None):
        try:
            user = User.objects.get(username__iexact=username)
            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. OracleAuthBackend by nosrednakram 3 years, 10 months ago
  2. Use email addresses for user name for django 1.3 by kidzik 2 years ago
  3. Login with email or username by zeeg 4 years, 10 months ago
  4. Case-insensitive lookup by default by sciyoshi 5 years, 11 months ago
  5. Use email addresses for user name by chris 6 years, 3 months ago

Comments

KingRolo (on February 25, 2011):

This is a really useful snippet, thank you.

Just a small note to mention that the granular non superuser permissions won't work with this as it doesn't inherit from ModelBackend. I just found this out via http://stackoverflow.com/questions/2081061/django-user-get-all-permissions-is-empty-while-user-permissions-is-set .

Changing to:

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

class CaseInsensitiveModelBackend(ModelBackend):

Solves this. Thanks.

#

john_nash (on April 27, 2012):

where should i put this code .. !!

#

(Forgotten your password?)