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

#

(Forgotten your password?)