1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-11-08 19:26:48 +00:00
webvirtcloud/accounts/forms.py
catborise 3210ef2eee fix(accounts): a username longer than the field is refused by the login form
Django's login form gives the username its max_length after the field
is built, so a longer username was not refused and reached
authentication. django-axes then stored it in its 255-character column,
which PostgreSQL refuses: a login with a 300-character username was a
500 (SQLite does not enforce the length). Both login forms, with and
without OTP, now check the length, so such a username is a form error
and never reaches authentication, the lockout or the Logs page.

This also turns the PostgreSQL leg of CI green again: the S-16 test
from #167 hit exactly this.
2026-10-23 16:06:10 +03:00

93 lines
3.1 KiB
Python

from appsettings.settings import app_settings
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import AuthenticationForm
from django.core.validators import MaxLengthValidator
from django.forms import EmailField, Form, ModelForm, ValidationError
from django.utils.translation import gettext_lazy as _
from .models import UserInstance, UserSSHKey
from .utils import validate_ssh_key
class UserInstanceForm(ModelForm):
def __init__(self, *args, **kwargs):
super(UserInstanceForm, self).__init__(*args, **kwargs)
# Make user and instance fields not editable after creation
instance = getattr(self, "instance", None)
if instance and instance.id is not None:
self.fields["user"].disabled = True
self.fields["instance"].disabled = True
def clean_instance(self):
instance = self.cleaned_data["instance"]
if app_settings.ALLOW_INSTANCE_MULTIPLE_OWNER == "False":
# the ownership being edited is not another owner
exists = UserInstance.objects.filter(instance=instance).exclude(pk=self.instance.pk)
if exists:
raise ValidationError(_("Instance owned by another user"))
return instance
class Meta:
model = UserInstance
fields = "__all__"
class ProfileForm(ModelForm):
class Meta:
model = get_user_model()
fields = ("first_name", "last_name", "email")
class UserSSHKeyForm(ModelForm):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop("user", None)
self.publickeys = UserSSHKey.objects.filter(user=self.user)
super().__init__(*args, **kwargs)
def clean_keyname(self):
for key in self.publickeys:
if self.cleaned_data["keyname"] == key.keyname:
raise ValidationError(_("Key name already exist"))
return self.cleaned_data["keyname"]
def clean_keypublic(self):
for key in self.publickeys:
if self.cleaned_data["keypublic"] == key.keypublic:
raise ValidationError(_("Public key already exist"))
if not validate_ssh_key(self.cleaned_data["keypublic"]):
raise ValidationError(_("Invalid key"))
return self.cleaned_data["keypublic"]
def save(self, commit=True):
ssh_key = super().save(commit=False)
ssh_key.user = self.user
if commit:
ssh_key.save()
return ssh_key
class Meta:
model = UserSSHKey
fields = ("keyname", "keypublic")
class EmailOTPForm(Form):
email = EmailField(label=_("Email"))
class BoundedUsernameMixin:
"""Django's login form gives the username its max_length after the field
is built, so a longer one is not refused and reaches authentication;
django-axes then cannot store it (PostgreSQL refuses it: 500)."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
username = self.fields["username"]
username.validators.append(MaxLengthValidator(username.max_length))
class LoginForm(BoundedUsernameMixin, AuthenticationForm):
pass