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,179 @@
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
|
||||
from apps.shared.domain.value_objects import EmailAddress
|
||||
from apps.users.application.dto import PasswordLinkPurpose, UserDetailsData
|
||||
from apps.users.application.use_cases import (
|
||||
CheckLoginAllowed,
|
||||
CreateUser,
|
||||
IssuePasswordLink,
|
||||
RequestPasswordReset,
|
||||
UpdateUser,
|
||||
)
|
||||
from apps.users.domain.enums import Role
|
||||
from apps.users.domain.exceptions import (
|
||||
EmailAlreadyTaken,
|
||||
InvalidSupervisor,
|
||||
LastActiveAdmin,
|
||||
SupervisorHasInterns,
|
||||
UserNotFound,
|
||||
)
|
||||
from apps.users.tests.fakes import (
|
||||
FakePasswordLinkService,
|
||||
FakeUnitOfWork,
|
||||
FixedClock,
|
||||
InMemoryUserRepository,
|
||||
account,
|
||||
)
|
||||
|
||||
TODAY = date(2026, 3, 1)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def repo() -> InMemoryUserRepository:
|
||||
return InMemoryUserRepository()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def links() -> FakePasswordLinkService:
|
||||
return FakePasswordLinkService()
|
||||
|
||||
|
||||
def details(**overrides: object) -> UserDetailsData:
|
||||
base: dict[str, object] = {
|
||||
"name": "Eeva Employee",
|
||||
"email": "[email protected]",
|
||||
"role": Role.EMPLOYEE,
|
||||
}
|
||||
return UserDetailsData(**{**base, **overrides}) # type: ignore[arg-type]
|
||||
|
||||
|
||||
class TestCreateUser:
|
||||
def test_creates_user_and_emails_setup_link(
|
||||
self, repo: InMemoryUserRepository, links: FakePasswordLinkService
|
||||
) -> None:
|
||||
created = CreateUser(repo, FakeUnitOfWork(), links).execute(details())
|
||||
|
||||
assert repo.get_by_id(created.user_id) is not None
|
||||
assert links.issued == [(created.user_id, PasswordLinkPurpose.SETUP)]
|
||||
assert links.sent == [("[email protected]", PasswordLinkPurpose.SETUP)]
|
||||
assert created.password_link.emailed
|
||||
|
||||
def test_email_must_be_unique(
|
||||
self, repo: InMemoryUserRepository, links: FakePasswordLinkService
|
||||
) -> None:
|
||||
repo.save(account(email=EmailAddress("[email protected]")))
|
||||
with pytest.raises(EmailAlreadyTaken):
|
||||
CreateUser(repo, FakeUnitOfWork(), links).execute(details(email="[email protected]"))
|
||||
|
||||
def test_failed_email_still_creates_user(self, repo: InMemoryUserRepository) -> None:
|
||||
links = FakePasswordLinkService(send_ok=False)
|
||||
created = CreateUser(repo, FakeUnitOfWork(), links).execute(details())
|
||||
|
||||
assert repo.get_by_id(created.user_id) is not None
|
||||
assert not created.password_link.emailed
|
||||
|
||||
def test_intern_supervisor_must_be_active_employee_or_management(
|
||||
self, repo: InMemoryUserRepository, links: FakePasswordLinkService
|
||||
) -> None:
|
||||
sub = repo.save(account(email=EmailAddress("[email protected]"), role=Role.SUBCONTRACTOR))
|
||||
with pytest.raises(InvalidSupervisor):
|
||||
CreateUser(repo, FakeUnitOfWork(), links).execute(
|
||||
details(
|
||||
role=Role.INTERN, employment_ends_on=date(2026, 6, 30), supervisor_id=sub.id
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
class TestUpdateUser:
|
||||
def test_last_active_admin_cannot_be_deactivated(self, repo: InMemoryUserRepository) -> None:
|
||||
admin = repo.save(account(role=Role.ADMIN))
|
||||
with pytest.raises(LastActiveAdmin):
|
||||
UpdateUser(repo, FakeUnitOfWork()).execute(
|
||||
admin.id, # type: ignore[arg-type]
|
||||
details(name="Admin", email="[email protected]", role=Role.ADMIN, is_active=False),
|
||||
)
|
||||
assert repo.locked
|
||||
|
||||
def test_last_active_admin_cannot_change_role(self, repo: InMemoryUserRepository) -> None:
|
||||
admin = repo.save(account(role=Role.ADMIN))
|
||||
with pytest.raises(LastActiveAdmin):
|
||||
UpdateUser(repo, FakeUnitOfWork()).execute(
|
||||
admin.id, # type: ignore[arg-type]
|
||||
details(email="[email protected]", role=Role.MANAGEMENT),
|
||||
)
|
||||
|
||||
def test_admin_can_be_deactivated_when_another_exists(
|
||||
self, repo: InMemoryUserRepository
|
||||
) -> None:
|
||||
admin = repo.save(account(role=Role.ADMIN))
|
||||
repo.save(account(role=Role.ADMIN, email=EmailAddress("[email protected]")))
|
||||
UpdateUser(repo, FakeUnitOfWork()).execute(
|
||||
admin.id, # type: ignore[arg-type]
|
||||
details(email="[email protected]", role=Role.ADMIN, is_active=False),
|
||||
)
|
||||
assert not repo.get_by_id(admin.id).is_active # type: ignore[arg-type, union-attr]
|
||||
|
||||
def test_supervisor_with_active_interns_cannot_be_deactivated(
|
||||
self, repo: InMemoryUserRepository
|
||||
) -> None:
|
||||
boss = repo.save(account(role=Role.EMPLOYEE))
|
||||
repo.save(
|
||||
account(
|
||||
email=EmailAddress("[email protected]"),
|
||||
role=Role.INTERN,
|
||||
employment_ends_on=date(2026, 6, 30),
|
||||
supervisor_id=boss.id,
|
||||
)
|
||||
)
|
||||
with pytest.raises(SupervisorHasInterns):
|
||||
UpdateUser(repo, FakeUnitOfWork()).execute(
|
||||
boss.id, # type: ignore[arg-type]
|
||||
details(email="[email protected]", is_active=False),
|
||||
)
|
||||
|
||||
def test_unknown_user(self, repo: InMemoryUserRepository) -> None:
|
||||
with pytest.raises(UserNotFound):
|
||||
UpdateUser(repo, FakeUnitOfWork()).execute(99, details())
|
||||
|
||||
|
||||
class TestPasswordLinks:
|
||||
def test_issue_link_for_existing_user(
|
||||
self, repo: InMemoryUserRepository, links: FakePasswordLinkService
|
||||
) -> None:
|
||||
user = repo.save(account())
|
||||
link = IssuePasswordLink(repo, links).execute(user.id) # type: ignore[arg-type]
|
||||
assert link.emailed
|
||||
assert links.issued == [(user.id, PasswordLinkPurpose.SETUP)]
|
||||
|
||||
def test_reset_is_sent_to_user_who_may_log_in(
|
||||
self, repo: InMemoryUserRepository, links: FakePasswordLinkService
|
||||
) -> None:
|
||||
repo.save(account())
|
||||
RequestPasswordReset(repo, links, FixedClock(TODAY)).execute("[email protected]")
|
||||
assert links.sent == [("[email protected]", PasswordLinkPurpose.RESET)]
|
||||
|
||||
@pytest.mark.parametrize("email", ["[email protected]", "not an email", ""])
|
||||
def test_reset_does_nothing_for_unknown_address(
|
||||
self, repo: InMemoryUserRepository, links: FakePasswordLinkService, email: str
|
||||
) -> None:
|
||||
RequestPasswordReset(repo, links, FixedClock(TODAY)).execute(email)
|
||||
assert links.issued == []
|
||||
|
||||
def test_reset_is_not_sent_to_ended_intern(
|
||||
self, repo: InMemoryUserRepository, links: FakePasswordLinkService
|
||||
) -> None:
|
||||
repo.save(account(role=Role.INTERN, employment_ends_on=date(2026, 2, 28), supervisor_id=9))
|
||||
RequestPasswordReset(repo, links, FixedClock(TODAY)).execute("[email protected]")
|
||||
assert links.issued == []
|
||||
|
||||
|
||||
class TestCheckLoginAllowed:
|
||||
def test_allowed_and_denied(self, repo: InMemoryUserRepository) -> None:
|
||||
active = repo.save(account())
|
||||
inactive = repo.save(account(email=EmailAddress("[email protected]"), is_active=False))
|
||||
check = CheckLoginAllowed(repo, FixedClock(TODAY))
|
||||
assert check.execute(active.id) # type: ignore[arg-type]
|
||||
assert not check.execute(inactive.id) # type: ignore[arg-type]
|
||||
assert not check.execute(12345)
|
||||
@@ -0,0 +1,43 @@
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from django.core.cache import cache
|
||||
|
||||
from apps.users.infrastructure.orm import User
|
||||
|
||||
PASSWORD = "Vahva-Salasana-2026"
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clear_cache(request: pytest.FixtureRequest) -> None:
|
||||
# The cache (login throttle) lives in the database; only DB tests can touch it.
|
||||
if request.node.get_closest_marker("django_db"):
|
||||
request.getfixturevalue("db")
|
||||
cache.clear()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_user(db: Any) -> Callable[..., User]:
|
||||
counter = iter(range(1, 10_000))
|
||||
|
||||
def factory(**fields: Any) -> User:
|
||||
n = next(counter)
|
||||
fields.setdefault("email", f"user{n}@example.test")
|
||||
fields.setdefault("name", f"User {n}")
|
||||
fields.setdefault("role", "employee")
|
||||
password = fields.pop("password", PASSWORD)
|
||||
return User.objects.create_user(password=password, **fields)
|
||||
|
||||
return factory
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admin(make_user: Callable[..., User]) -> User:
|
||||
return make_user(email="[email protected]", name="Admin", role="admin")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admin_client(client: Any, admin: User) -> Any:
|
||||
client.force_login(admin)
|
||||
return client
|
||||
@@ -0,0 +1,96 @@
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
|
||||
from apps.shared.domain.exceptions import InvalidEmailAddress
|
||||
from apps.shared.domain.value_objects import EmailAddress
|
||||
from apps.users.domain.entities import UserAccount
|
||||
from apps.users.domain.enums import Permission, Role
|
||||
from apps.users.domain.exceptions import (
|
||||
InternRequiresEndDate,
|
||||
InternRequiresSupervisor,
|
||||
InvalidPersonName,
|
||||
InvalidSupervisor,
|
||||
)
|
||||
from apps.users.domain.permissions import role_has
|
||||
from apps.users.domain.value_objects import PersonName
|
||||
from apps.users.tests.fakes import account
|
||||
|
||||
|
||||
def register(**kwargs: object) -> UserAccount:
|
||||
defaults: dict[str, object] = {
|
||||
"name": PersonName("Iida Intern"),
|
||||
"email": EmailAddress("[email protected]"),
|
||||
"role": Role.EMPLOYEE,
|
||||
}
|
||||
return UserAccount.register(**{**defaults, **kwargs}) # type: ignore[arg-type]
|
||||
|
||||
|
||||
class TestValueObjects:
|
||||
def test_email_is_normalized(self) -> None:
|
||||
assert EmailAddress(" [email protected] ").value == "[email protected]"
|
||||
|
||||
@pytest.mark.parametrize("value", ["", "no-at-sign", "a@b", "a [email protected]"])
|
||||
def test_invalid_email(self, value: str) -> None:
|
||||
with pytest.raises(InvalidEmailAddress):
|
||||
EmailAddress(value)
|
||||
|
||||
def test_name_whitespace_is_collapsed(self) -> None:
|
||||
assert PersonName(" Iida Intern ").value == "Iida Intern"
|
||||
|
||||
@pytest.mark.parametrize("value", ["", " ", "x" * 151])
|
||||
def test_invalid_name(self, value: str) -> None:
|
||||
with pytest.raises(InvalidPersonName):
|
||||
PersonName(value)
|
||||
|
||||
|
||||
class TestInternRules:
|
||||
def test_intern_requires_end_date(self) -> None:
|
||||
with pytest.raises(InternRequiresEndDate):
|
||||
register(role=Role.INTERN, supervisor_id=1)
|
||||
|
||||
def test_intern_requires_supervisor(self) -> None:
|
||||
with pytest.raises(InternRequiresSupervisor):
|
||||
register(role=Role.INTERN, employment_ends_on=date(2026, 6, 30))
|
||||
|
||||
def test_intern_cannot_supervise_self(self) -> None:
|
||||
user = account(id=5, role=Role.EMPLOYEE)
|
||||
with pytest.raises(InvalidSupervisor):
|
||||
user.update_details(
|
||||
name=user.name,
|
||||
email=user.email,
|
||||
role=Role.INTERN,
|
||||
is_active=True,
|
||||
employment_ends_on=date(2026, 6, 30),
|
||||
supervisor_id=5,
|
||||
)
|
||||
|
||||
def test_other_roles_clear_intern_fields(self) -> None:
|
||||
user = register(role=Role.EMPLOYEE, employment_ends_on=date(2026, 6, 30), supervisor_id=2)
|
||||
assert user.employment_ends_on is None
|
||||
assert user.supervisor_id is None
|
||||
|
||||
|
||||
class TestCanLogIn:
|
||||
def test_inactive_user_cannot_log_in(self) -> None:
|
||||
assert not account(is_active=False).can_log_in(date(2026, 1, 1))
|
||||
|
||||
def test_intern_can_log_in_until_end_date(self) -> None:
|
||||
intern = account(role=Role.INTERN, employment_ends_on=date(2026, 6, 30), supervisor_id=1)
|
||||
assert intern.can_log_in(date(2026, 6, 30))
|
||||
assert not intern.can_log_in(date(2026, 7, 1))
|
||||
|
||||
def test_intern_without_end_date_cannot_log_in(self) -> None:
|
||||
# A bad stored row must not crash login; it just denies access.
|
||||
assert not account(role=Role.INTERN).can_log_in(date(2026, 1, 1))
|
||||
|
||||
|
||||
class TestPermissions:
|
||||
def test_only_admin_manages_users(self) -> None:
|
||||
assert role_has(Role.ADMIN, Permission.USERS_MANAGE)
|
||||
for role in (Role.MANAGEMENT, Role.EMPLOYEE, Role.INTERN, Role.SUBCONTRACTOR):
|
||||
assert not role_has(role, Permission.USERS_MANAGE)
|
||||
|
||||
def test_subcontractor_does_not_use_customers(self) -> None:
|
||||
assert not role_has(Role.SUBCONTRACTOR, Permission.CUSTOMERS_USE)
|
||||
assert role_has(Role.INTERN, Permission.CUSTOMERS_USE)
|
||||
@@ -0,0 +1,100 @@
|
||||
"""In-memory test doubles for the users application layer (no database)."""
|
||||
|
||||
from dataclasses import replace
|
||||
from datetime import UTC, date, datetime
|
||||
|
||||
from apps.shared.domain.value_objects import EmailAddress
|
||||
from apps.users.application.dto import PasswordLink, PasswordLinkPurpose
|
||||
from apps.users.domain.entities import UserAccount
|
||||
from apps.users.domain.enums import Role
|
||||
|
||||
|
||||
class InMemoryUserRepository:
|
||||
def __init__(self) -> None:
|
||||
self.users: dict[int, UserAccount] = {}
|
||||
self.locked = False
|
||||
self._next_id = 1
|
||||
|
||||
def get_by_id(self, user_id: int) -> UserAccount | None:
|
||||
return self.users.get(user_id)
|
||||
|
||||
def get_by_email(self, email: EmailAddress) -> UserAccount | None:
|
||||
return next((u for u in self.users.values() if u.email == email), None)
|
||||
|
||||
def save(self, user: UserAccount) -> UserAccount:
|
||||
if user.id is None:
|
||||
user = user.with_id(self._next_id)
|
||||
self._next_id += 1
|
||||
self.users[user.id] = user # type: ignore[index]
|
||||
return user
|
||||
|
||||
def is_email_taken(self, email: EmailAddress, *, exclude_id: int | None = None) -> bool:
|
||||
return any(u.email == email and u.id != exclude_id for u in self.users.values())
|
||||
|
||||
def lock_active_admin_count(self) -> int:
|
||||
self.locked = True
|
||||
return sum(1 for u in self.users.values() if u.is_active_admin)
|
||||
|
||||
def has_active_interns(self, supervisor_id: int) -> bool:
|
||||
return any(
|
||||
u.is_active and u.role is Role.INTERN and u.supervisor_id == supervisor_id
|
||||
for u in self.users.values()
|
||||
)
|
||||
|
||||
|
||||
class FakeUnitOfWork:
|
||||
def __init__(self) -> None:
|
||||
self.entered = 0
|
||||
|
||||
def __enter__(self) -> FakeUnitOfWork:
|
||||
self.entered += 1
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc: object) -> None:
|
||||
return None
|
||||
|
||||
|
||||
class FakePasswordLinkService:
|
||||
def __init__(self, *, send_ok: bool = True) -> None:
|
||||
self.send_ok = send_ok
|
||||
self.issued: list[tuple[int, PasswordLinkPurpose]] = []
|
||||
self.sent: list[tuple[str, PasswordLinkPurpose]] = []
|
||||
|
||||
def issue(self, user_id: int, purpose: PasswordLinkPurpose) -> PasswordLink:
|
||||
self.issued.append((user_id, purpose))
|
||||
return PasswordLink(
|
||||
url=f"http://test/password/{purpose.value}/{user_id}/",
|
||||
expires_at=datetime(2026, 1, 1, tzinfo=UTC),
|
||||
)
|
||||
|
||||
def send(self, user: UserAccount, link: PasswordLink, purpose: PasswordLinkPurpose) -> bool:
|
||||
if self.send_ok:
|
||||
self.sent.append((user.email.value, purpose))
|
||||
return self.send_ok
|
||||
|
||||
|
||||
class FixedClock:
|
||||
def __init__(self, today: date) -> None:
|
||||
self._today = today
|
||||
|
||||
def today(self) -> date:
|
||||
return self._today
|
||||
|
||||
def set(self, today: date) -> None:
|
||||
self._today = today
|
||||
|
||||
|
||||
def account(**overrides: object) -> UserAccount:
|
||||
"""A stored user without rule checks, for arranging test state."""
|
||||
from apps.users.domain.value_objects import PersonName
|
||||
|
||||
base = UserAccount.reconstitute(
|
||||
id=None, # type: ignore[arg-type]
|
||||
name=PersonName("Test User"),
|
||||
email=EmailAddress("[email protected]"),
|
||||
role=Role.EMPLOYEE,
|
||||
is_active=True,
|
||||
employment_ends_on=None,
|
||||
supervisor_id=None,
|
||||
)
|
||||
return replace(base, **overrides) # type: ignore[arg-type]
|
||||
@@ -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")
|
||||
@@ -0,0 +1,149 @@
|
||||
from collections.abc import Callable
|
||||
from datetime import date
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from django.core import mail
|
||||
from django.test import Client
|
||||
|
||||
from apps.shared.domain.value_objects import EmailAddress
|
||||
from apps.users.domain.entities import UserAccount
|
||||
from apps.users.domain.enums import Role
|
||||
from apps.users.domain.value_objects import PersonName
|
||||
from apps.users.infrastructure.orm import User
|
||||
from apps.users.infrastructure.repositories import DjangoUserRepository
|
||||
|
||||
pytestmark = pytest.mark.django_db
|
||||
|
||||
|
||||
class TestPermissions:
|
||||
@pytest.mark.parametrize("role", ["management", "employee", "intern", "subcontractor"])
|
||||
def test_non_admin_gets_403(
|
||||
self, client: Client, make_user: Callable[..., User], role: str
|
||||
) -> None:
|
||||
boss = make_user()
|
||||
extra = (
|
||||
{"supervisor": boss, "employment_ends_on": date(2099, 1, 1)} if role == "intern" else {}
|
||||
)
|
||||
client.force_login(make_user(role=role, **extra))
|
||||
for path in ("/users/", "/users/new/", f"/users/{boss.pk}/edit/"):
|
||||
assert client.get(path).status_code == 403
|
||||
assert client.post(f"/users/{boss.pk}/password-link/").status_code == 403
|
||||
|
||||
def test_menu_shows_users_only_to_admin(
|
||||
self, client: Client, admin_client: Client, make_user: Callable[..., User]
|
||||
) -> None:
|
||||
assert 'href="/users/"' in admin_client.get("/").content.decode()
|
||||
other = Client()
|
||||
other.force_login(make_user())
|
||||
assert 'href="/users/"' not in other.get("/").content.decode()
|
||||
|
||||
|
||||
class TestList:
|
||||
def test_search_and_htmx_partial(
|
||||
self, admin_client: Client, make_user: Callable[..., User]
|
||||
) -> None:
|
||||
make_user(name="Eeva Esimerkki")
|
||||
make_user(name="Kalle Koe")
|
||||
response = admin_client.get("/users/?q=eeva", headers={"HX-Request": "true"})
|
||||
html = response.content.decode()
|
||||
assert "Eeva Esimerkki" in html
|
||||
assert "Kalle Koe" not in html
|
||||
assert "<html" not in html # partial only
|
||||
|
||||
def test_filter_inactive(self, admin_client: Client, make_user: Callable[..., User]) -> None:
|
||||
make_user(name="Old Timer", is_active=False)
|
||||
html = admin_client.get("/users/?active=0").content.decode()
|
||||
assert "Old Timer" in html
|
||||
assert "Admin" not in html.split("<tbody>")[1].split("</tbody>")[0]
|
||||
|
||||
|
||||
class TestCreateAndEdit:
|
||||
def test_create_user_shows_copyable_link_and_sends_email(self, admin_client: Client) -> None:
|
||||
response = admin_client.post(
|
||||
"/users/new/", {"name": "Eeva", "email": "[email protected]", "role": "employee"}
|
||||
)
|
||||
html = response.content.decode()
|
||||
assert response.status_code == 200
|
||||
assert "/password/set/setup/" in html
|
||||
assert "Kopioi" in html
|
||||
assert len(mail.outbox) == 1
|
||||
assert User.objects.get(email="[email protected]").has_usable_password() is False
|
||||
|
||||
def test_intern_requires_fields(self, admin_client: Client) -> None:
|
||||
response = admin_client.post(
|
||||
"/users/new/", {"name": "Iida", "email": "[email protected]", "role": "intern"}
|
||||
)
|
||||
assert response.status_code == 422
|
||||
assert "Harjoittelijalla on oltava viimeinen päivä." in response.content.decode()
|
||||
|
||||
def test_duplicate_email(self, admin_client: Client, make_user: Callable[..., User]) -> None:
|
||||
make_user(email="[email protected]")
|
||||
response = admin_client.post(
|
||||
"/users/new/", {"name": "Eeva", "email": "[email protected]", "role": "employee"}
|
||||
)
|
||||
assert response.status_code == 422
|
||||
assert "Tällä sähköpostiosoitteella on jo käyttäjä." in response.content.decode()
|
||||
|
||||
def test_last_admin_cannot_be_deactivated(self, admin_client: Client, admin: User) -> None:
|
||||
response = admin_client.post(
|
||||
f"/users/{admin.pk}/edit/",
|
||||
{
|
||||
"name": "Admin",
|
||||
"email": "[email protected]",
|
||||
"role": "admin",
|
||||
}, # is_active unchecked
|
||||
)
|
||||
assert response.status_code == 422
|
||||
admin.refresh_from_db()
|
||||
assert admin.is_active
|
||||
|
||||
def test_edit_saves_and_redirects(
|
||||
self, admin_client: Client, make_user: Callable[..., User]
|
||||
) -> None:
|
||||
user = make_user(name="Eeva")
|
||||
response = admin_client.post(
|
||||
f"/users/{user.pk}/edit/",
|
||||
{"name": "Eeva Uusi", "email": user.email, "role": "management", "is_active": "on"},
|
||||
)
|
||||
assert response.status_code == 302
|
||||
user.refresh_from_db()
|
||||
assert (user.name, user.role) == ("Eeva Uusi", "management")
|
||||
|
||||
def test_password_link_partial(
|
||||
self, admin_client: Client, make_user: Callable[..., User]
|
||||
) -> None:
|
||||
user = make_user()
|
||||
response = admin_client.post(
|
||||
f"/users/{user.pk}/password-link/", headers={"HX-Request": "true"}
|
||||
)
|
||||
html = response.content.decode()
|
||||
assert "<html" not in html
|
||||
assert 'role="status"' in html
|
||||
assert "/password/set/setup/" in html
|
||||
|
||||
def test_unknown_user_is_404(self, admin_client: Client) -> None:
|
||||
assert admin_client.get("/users/9999/edit/").status_code == 404
|
||||
|
||||
|
||||
class TestRepository:
|
||||
def test_save_and_reload(self) -> None:
|
||||
repo = DjangoUserRepository()
|
||||
saved = repo.save(
|
||||
UserAccount.register(
|
||||
name=PersonName("Eeva"), email=EmailAddress("[email protected]"), role=Role.EMPLOYEE
|
||||
)
|
||||
)
|
||||
assert saved.id is not None
|
||||
assert repo.get_by_email(EmailAddress("[email protected]")) == saved
|
||||
assert repo.is_email_taken(EmailAddress("[email protected]"))
|
||||
assert not repo.is_email_taken(EmailAddress("[email protected]"), exclude_id=saved.id)
|
||||
|
||||
def test_lock_counts_active_admins(self, make_user: Callable[..., User], admin: User) -> None:
|
||||
make_user(role="admin", is_active=False)
|
||||
assert DjangoUserRepository().lock_active_admin_count() == 1
|
||||
|
||||
def test_reconstitute_tolerates_bad_rows(self, make_user: Callable[..., User]) -> Any:
|
||||
# An intern without supervisor/end date must load (and simply not log in).
|
||||
bad = make_user(role="intern")
|
||||
assert DjangoUserRepository().get_by_id(bad.pk) is not None
|
||||
Reference in New Issue
Block a user