Vaihe 1/1: users-moduuli, kirjautuminen ja käyttäjähallinta
- shared-moduuli: DomainError, EmailAddress, UnitOfWork, tapahtumat, TimestampedModel, daisyUI-lomakerenderöinti ja yhteiset pohjat - users-moduuli Clean Architecture -kerroksin: oma käyttäjämalli (AUTH_USER_MODEL), roolit ja oikeudet, harjoittelija-, vastuuhenkilö- ja viimeisen pääkäyttäjän säännöt - kirjautuminen sähköpostilla, yritysten rajoitus, "muista minut", istunnon katkaisu kun tunnus poistetaan käytöstä tai harjoittelu päättyy - kertakäyttöiset salasanalinkit (72 h / 60 min, uusi mitätöi vanhan), salasanasääntö ja create_admin-komento - käyttäjähallinta: lista (HTMX-haku), lomakkeet ja kopioitava linkki - Tailwind 4 + daisyUI 5 + HTMX + Alpine npm-buildilla, suomennokset - testit: domain, application (fakeilla), integraatio ja selaintestit (axe, vaalea/tumma, 1920/320 px); ruff, mypy ja import-linter - dokumentit päivitetty toteutuksen mukaisiksi Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -0,0 +1,121 @@
|
||||
from collections.abc import Sequence
|
||||
from typing import Any
|
||||
|
||||
from django import forms
|
||||
from django.contrib.auth import password_validation
|
||||
from django.contrib.auth.forms import AuthenticationForm, SetPasswordForm
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
from apps.shared.presentation.forms import DaisyFormMixin
|
||||
from apps.users.application.dto import SupervisorChoice, UserDetailsData
|
||||
from apps.users.container import login_throttle
|
||||
from apps.users.domain.enums import Role
|
||||
from apps.users.presentation.labels import ROLE_CHOICES
|
||||
|
||||
|
||||
def client_ip(request: Any) -> str:
|
||||
return str(request.META.get("REMOTE_ADDR", "")) if request is not None else ""
|
||||
|
||||
|
||||
class LoginForm(DaisyFormMixin, AuthenticationForm):
|
||||
username = forms.EmailField(
|
||||
label=_("Email"),
|
||||
widget=forms.EmailInput(attrs={"autocomplete": "email", "autofocus": True}),
|
||||
)
|
||||
remember_me = forms.BooleanField(label=_("Remember me"), required=False)
|
||||
|
||||
error_messages = {
|
||||
# Same message for a wrong password and a deactivated account.
|
||||
"invalid_login": _("The email address or password is incorrect."),
|
||||
"inactive": _("The email address or password is incorrect."),
|
||||
"throttled": _("Too many login attempts. Try again in a few minutes."),
|
||||
}
|
||||
|
||||
def clean(self) -> dict[str, Any]:
|
||||
email = self.cleaned_data.get("username") or ""
|
||||
ip = client_ip(self.request)
|
||||
throttle = login_throttle()
|
||||
if email and throttle.is_blocked(email, ip):
|
||||
raise forms.ValidationError(self.error_messages["throttled"], code="throttled")
|
||||
try:
|
||||
cleaned = super().clean()
|
||||
except forms.ValidationError:
|
||||
if email:
|
||||
throttle.register_failure(email, ip)
|
||||
raise
|
||||
throttle.reset(email, ip)
|
||||
return cleaned
|
||||
|
||||
|
||||
class ForgotPasswordForm(DaisyFormMixin, forms.Form):
|
||||
email = forms.EmailField(
|
||||
label=_("Email"),
|
||||
widget=forms.EmailInput(attrs={"autocomplete": "email", "autofocus": True}),
|
||||
)
|
||||
|
||||
|
||||
class PasswordSetForm(DaisyFormMixin, SetPasswordForm): # type: ignore[type-arg]
|
||||
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
complexity = [
|
||||
v.get_help_text()
|
||||
for v in password_validation.get_default_password_validators()
|
||||
if type(v).__name__ == "ComplexityValidator"
|
||||
]
|
||||
self.fields["new_password1"].help_text = complexity[0] if complexity else ""
|
||||
self.fields["new_password1"].widget.attrs["autofocus"] = True
|
||||
|
||||
|
||||
class UserForm(DaisyFormMixin, forms.Form):
|
||||
name = forms.CharField(label=_("Name"), max_length=150)
|
||||
email = forms.EmailField(label=_("Email"), max_length=254)
|
||||
role = forms.ChoiceField(label=_("Role"), choices=ROLE_CHOICES)
|
||||
is_active = forms.BooleanField(label=_("Active"), required=False, initial=True)
|
||||
employment_ends_on = forms.DateField(
|
||||
label=_("Last day"),
|
||||
required=False,
|
||||
widget=forms.DateInput(attrs={"type": "date"}, format="%Y-%m-%d"),
|
||||
help_text=_("The intern cannot log in after this day."),
|
||||
)
|
||||
supervisor_id = forms.TypedChoiceField(
|
||||
label=_("Supervisor"), required=False, coerce=int, empty_value=None
|
||||
)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*args: Any,
|
||||
supervisors: Sequence[SupervisorChoice] = (),
|
||||
is_new: bool = True,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
self.fields["supervisor_id"].choices = [("", _("Choose a supervisor"))] + [ # type: ignore[attr-defined]
|
||||
(s.id, s.name) for s in supervisors
|
||||
]
|
||||
self.fields["role"].widget.attrs["x-model"] = "role"
|
||||
if is_new:
|
||||
del self.fields["is_active"]
|
||||
|
||||
def to_dto(self) -> UserDetailsData:
|
||||
data = self.cleaned_data
|
||||
is_intern = data["role"] == Role.INTERN.value
|
||||
return UserDetailsData(
|
||||
name=data["name"],
|
||||
email=data["email"],
|
||||
role=Role(data["role"]),
|
||||
is_active=data.get("is_active", True),
|
||||
employment_ends_on=data.get("employment_ends_on") if is_intern else None,
|
||||
supervisor_id=data.get("supervisor_id") if is_intern else None,
|
||||
)
|
||||
|
||||
|
||||
class UserFilterForm(DaisyFormMixin, forms.Form):
|
||||
q = forms.CharField(label=_("Search"), required=False)
|
||||
role = forms.ChoiceField(
|
||||
label=_("Role"), required=False, choices=[("", _("All roles")), *ROLE_CHOICES]
|
||||
)
|
||||
active = forms.ChoiceField(
|
||||
label=_("Status"),
|
||||
required=False,
|
||||
choices=[("", _("All")), ("1", _("Active")), ("0", _("Inactive"))],
|
||||
)
|
||||
Reference in New Issue
Block a user