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:
2026-11-29 13:20:24 +02:00
co-authored by Claude Opus 5.5
parent ba7a7ecfcf
commit e7b2745916
113 changed files with 5558 additions and 98 deletions
View File
+63
View File
@@ -0,0 +1,63 @@
from dataclasses import dataclass
from datetime import date, datetime
from enum import StrEnum
from typing import Any, Self
from apps.users.domain.enums import Role
class PasswordLinkPurpose(StrEnum):
SETUP = "setup" # created by an admin: new user or new link, valid 72 h
RESET = "reset" # "forgot password", valid 60 min
@dataclass(frozen=True, slots=True)
class UserDetailsData:
name: str
email: str
role: Role
is_active: bool = True
employment_ends_on: date | None = None
supervisor_id: int | None = None
@classmethod
def from_dict(cls, data: dict[str, Any]) -> Self:
supervisor = data.get("supervisor_id")
return cls(
name=str(data.get("name", "")),
email=str(data.get("email", "")),
role=Role(data["role"]),
is_active=bool(data.get("is_active", True)),
employment_ends_on=data.get("employment_ends_on") or None,
supervisor_id=int(supervisor) if supervisor else None,
)
@dataclass(frozen=True, slots=True)
class UserSummary:
id: int
name: str
email: str
role: Role
is_active: bool
employment_ends_on: date | None
supervisor_name: str | None
@dataclass(frozen=True, slots=True)
class SupervisorChoice:
id: int
name: str
@dataclass(frozen=True, slots=True)
class PasswordLink:
url: str
expires_at: datetime
emailed: bool = False
@dataclass(frozen=True, slots=True)
class CreatedUser:
user_id: int
password_link: PasswordLink
+14
View File
@@ -0,0 +1,14 @@
from typing import Protocol
from apps.users.application.dto import PasswordLink, PasswordLinkPurpose
from apps.users.domain.entities import UserAccount
class PasswordLinkService(Protocol):
def issue(self, user_id: int, purpose: PasswordLinkPurpose) -> PasswordLink:
"""Create a single-use link; any earlier link of the user stops working."""
...
def send(self, user: UserAccount, link: PasswordLink, purpose: PasswordLinkPurpose) -> bool:
"""Email the link. Returns False (and logs) if sending fails."""
...
+19
View File
@@ -0,0 +1,19 @@
from collections.abc import Sequence
from typing import Protocol
from apps.users.application.dto import SupervisorChoice, UserDetailsData, UserSummary
from apps.users.domain.enums import Role
class UserQueries(Protocol):
def list_users(
self, *, search: str = "", role: Role | None = None, is_active: bool | None = None
) -> Sequence[UserSummary]: ...
def get_details(self, user_id: int) -> UserDetailsData | None: ...
def get_summary(self, user_id: int) -> UserSummary | None: ...
def supervisor_choices(self, *, exclude_id: int | None = None) -> Sequence[SupervisorChoice]:
"""Active management and employee users."""
...
+150
View File
@@ -0,0 +1,150 @@
from dataclasses import replace
from apps.shared.application.ports import Clock, UnitOfWork
from apps.shared.domain.exceptions import InvalidEmailAddress
from apps.shared.domain.value_objects import EmailAddress
from apps.users.application.dto import (
CreatedUser,
PasswordLink,
PasswordLinkPurpose,
UserDetailsData,
)
from apps.users.application.ports import PasswordLinkService
from apps.users.domain.entities import UserAccount
from apps.users.domain.exceptions import (
EmailAlreadyTaken,
InvalidSupervisor,
LastActiveAdmin,
SupervisorHasInterns,
UserNotFound,
)
from apps.users.domain.repositories import UserRepository
from apps.users.domain.value_objects import PersonName
def _check_supervisor(repo: UserRepository, user: UserAccount) -> None:
if user.supervisor_id is None:
return
supervisor = repo.get_by_id(user.supervisor_id)
if supervisor is None or not supervisor.can_supervise or supervisor.id == user.id:
raise InvalidSupervisor()
class CreateUser:
"""An admin creates a user; the user sets the password with a 72 h link."""
def __init__(self, repo: UserRepository, uow: UnitOfWork, links: PasswordLinkService) -> None:
self.repo = repo
self.uow = uow
self.links = links
def execute(self, data: UserDetailsData) -> CreatedUser:
name = PersonName(data.name)
email = EmailAddress(data.email)
with self.uow:
if self.repo.is_email_taken(email):
raise EmailAlreadyTaken()
user = UserAccount.register(
name=name,
email=email,
role=data.role,
employment_ends_on=data.employment_ends_on,
supervisor_id=data.supervisor_id,
)
_check_supervisor(self.repo, user)
user = self.repo.save(user)
assert user.id is not None
link = self.links.issue(user.id, PasswordLinkPurpose.SETUP)
# Email is sent outside the transaction: a mail failure must not undo the user.
emailed = self.links.send(user, link, PasswordLinkPurpose.SETUP)
return CreatedUser(user_id=user.id, password_link=replace(link, emailed=emailed))
class UpdateUser:
def __init__(self, repo: UserRepository, uow: UnitOfWork) -> None:
self.repo = repo
self.uow = uow
def execute(self, user_id: int, data: UserDetailsData) -> None:
name = PersonName(data.name)
email = EmailAddress(data.email)
with self.uow:
current = self.repo.get_by_id(user_id)
if current is None:
raise UserNotFound()
if self.repo.is_email_taken(email, exclude_id=user_id):
raise EmailAlreadyTaken()
updated = current.update_details(
name=name,
email=email,
role=data.role,
is_active=data.is_active,
employment_ends_on=data.employment_ends_on,
supervisor_id=data.supervisor_id,
)
_check_supervisor(self.repo, updated)
# The count locks the admin rows, so two concurrent changes cannot remove the last one.
if (
current.is_active_admin
and not updated.is_active_admin
and self.repo.lock_active_admin_count() <= 1
):
raise LastActiveAdmin()
if (
current.can_supervise
and not updated.can_supervise
and self.repo.has_active_interns(user_id)
):
raise SupervisorHasInterns()
self.repo.save(updated)
class IssuePasswordLink:
"""An admin creates a new 72 h link for an existing user (shown and emailed)."""
def __init__(self, repo: UserRepository, links: PasswordLinkService) -> None:
self.repo = repo
self.links = links
def execute(self, user_id: int) -> PasswordLink:
user = self.repo.get_by_id(user_id)
if user is None:
raise UserNotFound()
link = self.links.issue(user_id, PasswordLinkPurpose.SETUP)
emailed = self.links.send(user, link, PasswordLinkPurpose.SETUP)
return replace(link, emailed=emailed)
class RequestPasswordReset:
"""Forgot password: emails a 60 min link only to users allowed to log in today.
The caller always shows the same message, so the page does not reveal which emails exist.
"""
def __init__(self, repo: UserRepository, links: PasswordLinkService, clock: Clock) -> None:
self.repo = repo
self.links = links
self.clock = clock
def execute(self, email: str) -> None:
try:
address = EmailAddress(email)
except InvalidEmailAddress:
return
user = self.repo.get_by_email(address)
if user is None or user.id is None or not user.can_log_in(self.clock.today()):
return
link = self.links.issue(user.id, PasswordLinkPurpose.RESET)
self.links.send(user, link, PasswordLinkPurpose.RESET)
class CheckLoginAllowed:
"""A user may log in (and keep a session) while active and, for interns, until the end date."""
def __init__(self, repo: UserRepository, clock: Clock) -> None:
self.repo = repo
self.clock = clock
def execute(self, user_id: int) -> bool:
user = self.repo.get_by_id(user_id)
return user is not None and user.can_log_in(self.clock.today())