koko
koko

Reputation: 397

Validation inactive user Django

I looking for a resolving of my issue. I have custom User model:

class User(AbstractUser):
    username = models.CharField(max_length=150, unique=True, blank=False, null=False)
    first_name = models.CharField(max_length=150, blank=True)
    last_name = models.CharField(max_length=150, blank=True)
    password = models.CharField(max_length=150, blank=False)
    email = models.EmailField(unique=True, blank=False)
    date_create = models.DateTimeField(auto_now_add=True)
    address = models.CharField(blank=True, max_length=128)
    phone = PhoneNumberField(unique=True)
    photo = models.ImageField(upload_to='images/', blank=True)
    is_active = models.BooleanField(default=True)

In my app I have e-mail-confirmation. When I create user I hit the "is_active=False". When user activate account then flag "is_active=True". Everything works good. But when INactive user tries to log in I wanna get message from Django in Login form. Django has it(source code):

def confirm_login_allowed(self, user):
        if not user.is_active:
            raise ValidationError(
                self.error_messages['inactive'],
                code='inactive',
            )

But doesn't work for me. Update: When inactive user tried to log in I get same message as user with incorrect username or password. I tried to override AuthenticationForm:

User = get_user_model()
class CustomAuthenticationForm(AuthenticationForm):
    class Meta:                # tried with Meta and without
        model = User
    def confirm_login_allowed(self, user):
        if not user.is_active:
            raise forms.ValidationError('There was a problem with your login.')

View:

class CustomLoginView(SuccessMessageMixin, LoginView):
    form_class = CustomAuthenticationForm
    success_url = reverse_lazy('home')
    success_message = "You was logged in successfully"

url:

path('login/', CustomLoginView.as_view(), name='login'),

Update, templates base and login:

<!doctype html>
{% load static %}
<html lang="en">
<head>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
          integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
            integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
            crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
            integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx"
            crossorigin="anonymous"></script>

    {% block mystyle %}
    {% endblock %}
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark justify-content-center">
    <a class="navbar-brand" href="#">Site</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup"
            aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
        <div class="navbar-nav">
            <a class="nav-link" href="{% url 'home' %}">Home</a>
            {% if user.is_authenticated %}
            <a class="nav-link" href="{% url 'cabinet' %}">Cabinet</a>
            <a class="nav-link" href="{% url 'logout' %}">LogOut</a>
            {% else%}
            <a class="nav-link" href="{% url 'signup' %}">SignUp</a>
            <a class="nav-link text-right" href="{% url 'login' %}">LogIn</a>
            {% endif %}
        </div>
    </div>
</nav>
{% if messages %}
{% for message in messages %}
<div class="alert alert-success">{{ message }}</div>
{% endfor %}
{% endif %}
{% block content %}
{% endblock %}
</body>
</html>

{% extends "base.html" %}
{% load crispy_forms_tags %}
<!DOCTYPE html>
{% block title %}Log In{% endblock %}
{% block content %}
<h1 class="row justify-content-center p-4">Log In</h1>
<div class="row justify-content-center">
    <div class="col-4">
        <form autocomplete="off" method="post">
            {% csrf_token %}
            {{ form|crispy }}
            <div class="container p-2">
                <a href="{% url 'password_reset' %}">Forgot your password?</a>
            </div>
            <div class="container p-2">
                <button type="submit" class="btn btn-primary">Submit</button>
            </div>
        </form>
    </div>
</div>
{% endblock %}

Could someone help me? Thanks.

Upvotes: 0

Views: 793

Answers (1)

koko
koko

Reputation: 397

I understood it from point of security. I resolved it just override ModelBackend

from django.contrib.auth.backends import ModelBackend  
from django.contrib.auth import get_user_model 
UserModel = get_user_model()
class CustomModelBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        if username is None:
            username = kwargs.get(UserModel.USERNAME_FIELD)
        if username is None or password is None:
            return
        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 nonexistent user (#20760).
            UserModel().set_password(password)
        else:
            if user.check_password(password):   # here (remove 'and self.user_can_authenticate(user):')
                return user

Settings

AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
    'accounts.backends.CustomModelBackend',
]

Upvotes: 2

Related Questions