Skip to content Skip to sidebar Skip to footer

Authenticate Returns None With Correct Username And Password During Userlogin

My User login has some issue with the authentication process. I am using Django 1.9 and Python 3.6 this is my code repository user = authenticate(username=username, password=passw

Solution 1:

Django 2.1 authentication returns users for any authentication, only if user.is_active=TRUE and you need to first save the response of form.save(commit=False) and then set custom variables

if form.is_valid():
    user= form.save(commit=False)
    user.active=True
    user.staff=False
    user.admin=False
    user.save()
    messages.success(request, 'Account created successfully')

Solution 2:

Remove

user.set_password(user.password)

from Accounts.views.register

Solution 3:

You need to define check_password for your User class

defcheck_password(self, raw_password):
    if self.password == raw_password:
        returnTrueelse:
        returnFalse

Because if you check the source code under django.contrib.auth.models, check_password() raise and NotImplemented error.

Solution 4:

Make sure that user.is_active is True before calling authenticate(username=user.username, password=password, request=request) in Django 1.11.

It worked fine in Django 1.8, but somewhere between LTS 1.8 and LTS 1.11 they added an additional check for user.is_active in ModelBackend class:

classModelBackend(object):
    """
    Authenticates against settings.AUTH_USER_MODEL.
    """defauthenticate(self, request, username=None, password=None, **kwargs):
        if username isNone:
            username = kwargs.get(UserModel.USERNAME_FIELD)
        try:
            user = UserModel._default_manager.get_by_natural_key(username)
        except UserModel.DoesNotExist:
            # Run the default password hasher once to reduce the timing# difference between an existing and a non-existing user (#20760).
            UserModel().set_password(password)
        else:
            if user.check_password(password) and self.user_can_authenticate(user):
                return user

    defuser_can_authenticate(self, user):
        """
        Reject users with is_active=False. Custom user models that don't have
        that attribute are allowed.
        """
        is_active = getattr(user, 'is_active', None)
        return is_active or is_active isNone

As for the recommendation to use Django built-in auth views, they are not handy for customized non-standard authentication.

Post a Comment for "Authenticate Returns None With Correct Username And Password During Userlogin"