i can only login if i have a lowercase password

Viewed 51

I made a custom user model and added some authentication system, but when I try to login into my account, it won't let me, but if I change the password to all lowercase, then it lets me login.

I added this custom backend because the email field was case-sensitive, and I didn't want that, and now it messes up my login system.

backends.py

from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend, UserModel

class CaseInsensitiveModelBackend(ModelBackend):
    
    def authenticate(self, request, username=None, password=None, **kwargs):
        UserModel = get_user_model()
        if username is None:
            username = kwargs.get(UserModel.USERNAME_FIELD)
        
        try:
            case_insensitive_username_field = '{}__iexact'.format(UserModel.USERNAME_FIELD)
            user = UserModel._default_manager.get(**{case_insensitive_username_field: username})
        except UserModel.DoesNotExist:
            UserModel().set_password(password)

        else:
            if user.check_password(password) and self.user_can_authenticate(user):
                return user

views.py

from django.shortcuts import redirect, render
from django.contrib.auth import login, logout, authenticate
from django.contrib import messages
from django.template.defaultfilters import slugify

# Create your views here.

from .forms import MyUserCreationForm, SettingsForm
from .decorators import unauthorizedUserCanView, authorizedUserCanView
from .models import User

@unauthorizedUserCanView
def register_view(request):
    form = MyUserCreationForm()

    if request.method == 'POST':
        form = MyUserCreationForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)

            obj.username = slugify(obj.username)

            obj.save()            
            return redirect('home:home')
        else:
            messages.error(request, 'error while creating your account, please try again.')

    context = {'form': form}
    return render(request, 'account/register.html', context)

@unauthorizedUserCanView
def login_view(request):

    if request.method == 'POST':
        email = request.POST.get('email')
        password = request.POST.get('password')
    
        user = authenticate(request, email=email, password=password)

        if user is not None:
            login(request, user)
            return redirect('home:home')
        else:
            messages.error(request, 'Username OR password is incorrect')

    return render(request, 'account/login.html')

settings.py

AUTH_USER_MODEL = 'account.User'

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.AllowAllUsersModelBackend',
    'account.backends.CaseInsensitiveModelBackend',
)

If anyone can help me, it'd mean a lot.

If I should provide and more files, please let me know.

0 Answers
Related