Home > Net >  How to fix this problem? Login if statement not working
How to fix this problem? Login if statement not working

Time:02-10

This is my views.py

def user_login(request):
   if request.method == "POST":
    username = request.POST.get('username')  
    password = request.POST.get('password')  
    user = authenticate(username=username, password=password)
    if user:
        if user.is_active:
            login(request, user)
            return HttpResponseRedirect(reverse('index'))
        else:
            return HttpResponse("Your account is Inactive.")
    else:
        return HttpResponse("Invalid User Credentials Provided!!!!")
else:
    return render(request, "MyTestApp/login.html", {})

And this is my login page:

<div >
<div >
    <h2 > Login </h2>
    <form method="post" action="{ url 'MyTestApp:user_login '}">
        {%csrf_token%}
        <label for="username"> Username </label>
        <input type="text" name="username" placeholder=" Write Your UserName Here"> <br></br>

        <label for="password"> Password </label>
        <input type="text" name="password" placeholder=" Write Your Password Here"> <br></br>

        <input  type="submit"  name="savebutton" value="login">
    </form>
</div>

When I try to login it works. If I try to login with a unregistered account then it doesn't allow me returns the message "Invalid User Credentials Provided", which is good. But When I try to login with a inactive account it still returns "Invalid User Credentials Provided". It doesn't return the message "Your account is Inactive.", which it should return when I login with a inactive account. Does anyone know why this is happening. Any help will be very much appreciated.

CodePudding user response:

That's because you are using ModelBackend Authentication which is default for Django. This backend checks if user can authenticate by checking if user is_active. Your user is not active, so it can't authenticate, so your authenticate returns None instead of User. If you want to know more about this authentication method check it django.contrib.auth.backends.ModelBackend.

CodePudding user response:

As authenticate returns None if the account is inactive, you can't know if the account is inactive or the user does not exist. You have to check yourself the status of the user:

from django.shortcuts import render, reverse
from django.contrib.auth import login, get_user_model
from django.http import HttpResponse, HttpResponseRedirect

def user_login(request):
    if request.method == "POST":
        username = request.POST.get('username')
        password = request.POST.get('password')

        try:
            user_model = get_user_model()
            user = user_model.objects.get(username=username)
            if not user.is_active:
                return HttpResponse("Your account is Inactive.")

            if not user.check_password(password):
                return HttpResponse("Invalid User Credentials Provided!!!!")

            login(request, user)
            return HttpResponseRedirect(reverse('index'))
        except user_model.DoesNotExist:
            return HttpResponse("User does not exist!!!!")

    else:
        return render(request, "MyTestApp/login.html", {})

CodePudding user response:

Since default authenticate always validate for username and password with is_active status that's why authenticate always returns None if user is inactive. You can make your own CustomLoginBackend and check for username and password and return user object if username and password correct otherwise returns None and check if user is active or not in your views.py

from django.contrib.auth import get_user_model

class CustomLoginBackend(object):

    def authenticate(self, request, username, password):
        User = get_user_model()
        try:
            user = User.objects.using(db_name).get(username=username)
        except User.DoesNotExist:
            return None
        else:
            if password is not None:
                if  user.check_password(password):
                    return user
        return None

Then in your login views.

from django.contrib.auth import authenticate, login
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.shortcuts import render

def user_login(request):
    if request.method == "POST":
        username = request.POST.get('username')  
        password = request.POST.get('password')  
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect(reverse('index'))
            else:
                return HttpResponse("Your account is Inactive.")
        else:
            return HttpResponse("Invalid User Credentials Provided!!!!")
    else:
        return render(request, "MyTestApp/login.html", {})

And at last don't forgot to add AUTHENTICATION_BACKENDS in your settings.py as

AUTHENTICATION_BACKENDS = ['path_to_your.CustomLoginBackend ',]
  • Related