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
+180
View File
@@ -0,0 +1,180 @@
from collections.abc import Callable
from datetime import date, timedelta
from typing import Any
import pytest
from django.core import mail
from django.test import Client
from django.urls import reverse
from apps.users.application.dto import PasswordLinkPurpose
from apps.users.infrastructure.orm import User
from apps.users.infrastructure.password_links import DjangoPasswordLinkService
from apps.users.tests.conftest import PASSWORD
pytestmark = pytest.mark.django_db
LOGIN = "/login/"
def login(client: Client, email: str, password: str = PASSWORD, **extra: str) -> Any:
return client.post(LOGIN, {"username": email, "password": password, **extra})
class TestLogin:
def test_login_page_is_public_and_other_pages_are_not(self, client: Client) -> None:
assert client.get(LOGIN).status_code == 200
response = client.get("/")
assert response.status_code == 302
assert response["Location"].startswith(LOGIN)
def test_successful_login(self, client: Client, make_user: Callable[..., User]) -> None:
make_user(email="[email protected]")
response = login(client, "[email protected]")
assert response.status_code == 302
assert client.get("/").status_code == 200
def test_session_ends_with_browser_unless_remember_me(
self, client: Client, make_user: Callable[..., User]
) -> None:
make_user(email="[email protected]")
login(client, "[email protected]")
assert client.session.get_expire_at_browser_close()
client.logout()
login(client, "[email protected]", remember_me="on")
assert not client.session.get_expire_at_browser_close()
def test_wrong_password_and_inactive_user_get_same_message(
self, client: Client, make_user: Callable[..., User]
) -> None:
make_user(email="[email protected]")
make_user(email="[email protected]", is_active=False)
wrong = login(client, "[email protected]", "Wrong-Password-1")
inactive = login(client, "[email protected]")
message = "Sähköpostiosoite tai salasana on väärin."
assert message in wrong.content.decode()
assert message in inactive.content.decode()
def test_ended_intern_cannot_log_in(
self, client: Client, make_user: Callable[..., User]
) -> None:
boss = make_user()
make_user(
email="[email protected]",
role="intern",
supervisor=boss,
employment_ends_on=date.today() - timedelta(days=2),
)
response = login(client, "[email protected]")
assert response.status_code == 200
assert "_auth_user_id" not in client.session
def test_login_is_throttled_after_five_failures(
self, client: Client, make_user: Callable[..., User]
) -> None:
make_user(email="[email protected]")
for _ in range(5):
login(client, "[email protected]", "Wrong-Password-1")
response = login(client, "[email protected]") # correct password, still blocked
assert "Liian monta kirjautumisyritystä" in response.content.decode()
assert "_auth_user_id" not in client.session
class TestSessionEnds:
def test_deactivated_user_is_logged_out_on_next_request(
self, client: Client, make_user: Callable[..., User]
) -> None:
user = make_user()
client.force_login(user)
User.objects.filter(pk=user.pk).update(is_active=False)
response = client.get("/")
assert response.status_code == 302
assert response["Location"] == f"{LOGIN}?access=ended"
assert "_auth_user_id" not in client.session
def test_htmx_request_gets_hx_redirect(
self, client: Client, make_user: Callable[..., User]
) -> None:
user = make_user()
client.force_login(user)
User.objects.filter(pk=user.pk).update(is_active=False)
response = client.get("/", headers={"HX-Request": "true"})
assert response["HX-Redirect"] == f"{LOGIN}?access=ended"
def test_access_ended_message_is_shown(self, client: Client) -> None:
assert (
"Käyttöoikeutesi on päättynyt" in client.get(f"{LOGIN}?access=ended").content.decode()
)
class TestPasswordLinks:
def _link_path(self, user: User, purpose: PasswordLinkPurpose) -> str:
url = DjangoPasswordLinkService().issue(user.pk, purpose).url
return url.split("8000", 1)[-1] if "8000" in url else url
def test_setting_password_works_once(
self, client: Client, make_user: Callable[..., User]
) -> None:
user = make_user(password=None)
path = self._link_path(user, PasswordLinkPurpose.SETUP)
new = "Uusi-Salasana-2026!"
response = client.post(path, {"new_password1": new, "new_password2": new})
assert response.status_code == 302
user.refresh_from_db()
assert user.check_password(new)
assert client.get(path).status_code == 400 # single use
def test_new_link_invalidates_older(
self, client: Client, make_user: Callable[..., User]
) -> None:
user = make_user()
old = self._link_path(user, PasswordLinkPurpose.SETUP)
self._link_path(user, PasswordLinkPurpose.SETUP)
assert client.get(old).status_code == 400
def test_weak_password_is_rejected(
self, client: Client, make_user: Callable[..., User]
) -> None:
user = make_user()
path = self._link_path(user, PasswordLinkPurpose.RESET)
response = client.post(path, {"new_password1": "lyhyt", "new_password2": "lyhyt"})
assert response.status_code == 422
assert "vähintään 12 merkkiä" in response.content.decode()
def test_reset_link_expires_after_60_minutes(
self, client: Client, make_user: Callable[..., User], settings: Any
) -> None:
settings.PASSWORD_RESET_TIMEOUT = -1
user = make_user()
assert client.get(self._link_path(user, PasswordLinkPurpose.RESET)).status_code == 400
def test_password_change_ends_other_sessions(self, make_user: Callable[..., User]) -> None:
user = make_user()
other_device = Client()
other_device.force_login(user)
path = self._link_path(user, PasswordLinkPurpose.RESET)
new = "Uusi-Salasana-2026!"
Client().post(path, {"new_password1": new, "new_password2": new})
assert other_device.get("/").status_code == 302
def test_forgot_password_gives_same_answer(
self, client: Client, make_user: Callable[..., User]
) -> None:
make_user(email="[email protected]")
known = client.post("/password/forgot/", {"email": "[email protected]"}, follow=True)
unknown = client.post("/password/forgot/", {"email": "[email protected]"}, follow=True)
assert len(mail.outbox) == 1
text = "Jos osoite kuuluu käyttäjälle"
assert text in known.content.decode()
assert text in unknown.content.decode()
class TestCreateAdminCommand:
def test_creates_admin_and_prints_link(self, capsys: Any) -> None:
from django.core.management import call_command
call_command("create_admin", "Aino Admin", "[email protected]")
out = capsys.readouterr().out
assert User.objects.get(email="[email protected]").role == "admin"
assert "/password/set/setup/" in out
assert reverse("users:login")