Files
santeh-ray/users/forms.py
Azimkin d0651274d6
All checks were successful
Build and Push Docker Image / build (push) Successful in 28s
feat: add custom authentication backend to support login with email or username
- Implemented `EmailOrUsernameBackend` to allow authentication via email or username
- Updated settings to include the new authentication backend
- Modified tests to cover email-based login scenarios
- Fixed user lookup logic in forms to handle case-insensitive email matching
2026-04-21 18:09:52 +02:00

89 lines
3.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from django import forms
from django.contrib.auth import authenticate, get_user_model
from django.contrib.auth.forms import PasswordResetForm, SetPasswordForm, UserCreationForm
from django.core.exceptions import ValidationError
User = get_user_model()
class LoginForm(forms.Form):
email = forms.EmailField(label="Электронная почта")
password = forms.CharField(label="Пароль", strip=False, widget=forms.PasswordInput)
error_messages = {
"invalid_login": "Неверная электронная почта или пароль.",
"inactive": "Аккаунт ещё не подтверждён. Проверьте письмо на почте.",
}
def __init__(self, request=None, *args, **kwargs):
self.request = request
self.user_cache = None
super().__init__(*args, **kwargs)
def clean_email(self):
return self.cleaned_data["email"].strip().lower()
def clean(self):
cleaned_data = super().clean()
email = cleaned_data.get("email")
password = cleaned_data.get("password")
if not email or not password:
return cleaned_data
self.user_cache = authenticate(self.request, username=email, password=password)
if self.user_cache is not None:
return cleaned_data
user = User.objects.filter(email__iexact=email).first()
if user and not user.is_active and user.check_password(password):
raise ValidationError(self.error_messages["inactive"])
raise ValidationError(self.error_messages["invalid_login"])
def get_user(self):
return self.user_cache
class RegisterForm(UserCreationForm):
full_name = forms.CharField(label="Имя и фамилия", max_length=150)
email = forms.EmailField(label="Электронная почта")
class Meta(UserCreationForm.Meta):
model = User
fields = ("full_name", "email", "password1", "password2")
def clean_email(self):
email = self.cleaned_data["email"].strip().lower()
if User.objects.filter(email__iexact=email).exists():
raise ValidationError("Пользователь с такой электронной почтой уже существует.")
return email
def save(self, commit=True):
user = super().save(commit=False)
email = self.cleaned_data["email"]
full_name = self.cleaned_data["full_name"].strip()
parts = full_name.split(maxsplit=1)
user.username = email
user.email = email
user.first_name = parts[0] if parts else ""
user.last_name = parts[1] if len(parts) > 1 else ""
user.is_active = False
if commit:
user.save()
return user
class SantehRayPasswordResetForm(PasswordResetForm):
email = forms.EmailField(label="Электронная почта")
def clean_email(self):
return self.cleaned_data["email"].strip().lower()
class SantehRaySetPasswordForm(SetPasswordForm):
pass