验证非活动用户 Django
Validation inactive user Django
我正在寻找解决问题的方法。
我有自定义用户模型:
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)
在我的应用程序中,我有电子邮件确认。当我创建用户时,我点击了“is_active=False”。当用户激活帐户时,然后标记“is_active=True”。一切正常。
但是当非活动用户尝试登录时,我想以登录形式从 Django 获取消息。
Django 有它(源码):
def confirm_login_allowed(self, user):
if not user.is_active:
raise ValidationError(
self.error_messages['inactive'],
code='inactive',
)
但对我不起作用。
更新:当非活动用户尝试登录时,我收到与用户名或密码不正确的用户相同的消息。
我试图覆盖 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.')
查看:
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'),
更新、模板库和登录:
<!doctype html>
{% load static %}
<html lang="en">
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/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/bootstrap@4.5.3/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 %}
有人可以帮助我吗?谢谢。
我是从安全的角度理解的。我解决了它只是覆盖 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
设置
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'accounts.backends.CustomModelBackend',
]
我正在寻找解决问题的方法。 我有自定义用户模型:
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)
在我的应用程序中,我有电子邮件确认。当我创建用户时,我点击了“is_active=False”。当用户激活帐户时,然后标记“is_active=True”。一切正常。 但是当非活动用户尝试登录时,我想以登录形式从 Django 获取消息。 Django 有它(源码):
def confirm_login_allowed(self, user):
if not user.is_active:
raise ValidationError(
self.error_messages['inactive'],
code='inactive',
)
但对我不起作用。 更新:当非活动用户尝试登录时,我收到与用户名或密码不正确的用户相同的消息。 我试图覆盖 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.')
查看:
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'),
更新、模板库和登录:
<!doctype html>
{% load static %}
<html lang="en">
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/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/bootstrap@4.5.3/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 %}
有人可以帮助我吗?谢谢。
我是从安全的角度理解的。我解决了它只是覆盖 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
设置
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'accounts.backends.CustomModelBackend',
]