Login

Case Insensitive Authentication Backend

Author:
ericflo
Posted:
March 12, 2009
Language:
Python
Version:
1.0
Tags:
auth case case-insensitive backend insensitive
Score:
5 (after 5 ratings)

By enabling this backend:

AUTHENTICATION_BACKENDS = (
    'path.to.my.backends.CaseInsensitiveModelBackend',
)

Your users will now be able to log in with their username, no matter whether the letters are upper- or lower-case.

 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. Login with email or username by zeeg 7 years ago
  2. OracleAuthBackend by nosrednakram 6 years ago
  3. SimpleMachines forum authentication backend by kropp 7 years, 7 months ago
  4. Case-insensitive lookup by default by sciyoshi 8 years, 1 month ago
  5. Use email addresses for user name for django 1.3 by kidzik 4 years, 2 months ago

Comments

john_nash (on April 27, 2012):

where should i put this code .. !!

#

bquinn (on February 12, 2014):

Since Django 1.5 (?) and pluggable user models, there's an alternative way to do this.

In the Manager for your user model, add a get_by_natural_key method, then you don't need to override the default auth backend.

class MyUserManager(BaseUserManager):
    def get_by_natural_key(self, username):
        return self.get(email__iexact=username)

#

Please login first before commenting.