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:
@@ -9,3 +9,8 @@ DB_USER=root
|
|||||||
DB_PASSWORD=
|
DB_PASSWORD=
|
||||||
DB_HOST=127.0.0.1
|
DB_HOST=127.0.0.1
|
||||||
DB_PORT=3306
|
DB_PORT=3306
|
||||||
|
|
||||||
|
# Sähköposti ja linkit
|
||||||
|
SITE_URL=http://127.0.0.1:8000
|
||||||
|
EMAIL_BACKEND=django.core.mail.backends.console.EmailBackend
|
||||||
|
DEFAULT_FROM_EMAIL=toiminnanohjaus@localhost
|
||||||
|
|||||||
@@ -7,3 +7,10 @@ media/
|
|||||||
*.sqlite3
|
*.sqlite3
|
||||||
.idea/
|
.idea/
|
||||||
.vscode/
|
.vscode/
|
||||||
|
node_modules/
|
||||||
|
static/dist/
|
||||||
|
*.mo
|
||||||
|
test-results/
|
||||||
|
.pytest_cache/
|
||||||
|
.mypy_cache/
|
||||||
|
.ruff_cache/
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ Toiminnanohjaus is an ERP for a small (5–10 people) Finnish media and marketin
|
|||||||
- Stack: Django 5.2 LTS, Python 3.14, MariaDB 10.11 (XAMPP in development), HTMX, Alpine.js, Tailwind CSS 4 and daisyUI 5.
|
- Stack: Django 5.2 LTS, Python 3.14, MariaDB 10.11 (XAMPP in development), HTMX, Alpine.js, Tailwind CSS 4 and daisyUI 5.
|
||||||
- Language: code (identifiers, tables, columns, enum keys) is in English. Specs, UI texts, docs and commit messages are in Finnish.
|
- Language: code (identifiers, tables, columns, enum keys) is in English. Specs, UI texts, docs and commit messages are in Finnish.
|
||||||
|
|
||||||
**Current state:** only the project skeleton exists (the `config/` package, MariaDB settings, `.env`). Nothing under `apps/` has been built yet, and the frontend build (`package.json`), pytest, ruff, mypy and import-linter are not set up. `docs/architecture.md` describes the target design. Follow it when you add code, and set up each tool the first time it is needed.
|
**Current state:** phase 1 item 1 is done: the `shared` module and the `users` module (custom user model, login, password links, user management). It is the reference implementation of the architecture; copy its patterns for new modules. Other modules described in `docs/architecture.md` are not built yet.
|
||||||
|
|
||||||
## Source of truth
|
## Source of truth
|
||||||
|
|
||||||
@@ -20,32 +20,36 @@ Toiminnanohjaus is an ERP for a small (5–10 people) Finnish media and marketin
|
|||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
.venv\Scripts\python manage.py runserver # dev server http://127.0.0.1:8000 (start MySQL in XAMPP Control Panel first)
|
.venv\Scripts\python manage.py runserver # dev server http://127.0.0.1:8000 (start MySQL in XAMPP Control Panel first)
|
||||||
.venv\Scripts\python manage.py check
|
npm run build # vendor htmx/alpine + Tailwind/daisyUI -> static/dist (npm run dev = watch)
|
||||||
.venv\Scripts\python manage.py makemigrations <app>
|
.venv\Scripts\python manage.py makemigrations <app> ; .venv\Scripts\python manage.py migrate
|
||||||
.venv\Scripts\python manage.py migrate
|
.venv\Scripts\python manage.py create_admin "Name" email # prints a password link (email goes to console in dev)
|
||||||
.venv\Scripts\python -m pip install -r requirements.txt
|
|
||||||
```
|
|
||||||
|
|
||||||
Planned tooling, per `docs/architecture.md` (not set up yet):
|
.venv\Scripts\pytest apps # unit + integration tests (MariaDB test DB)
|
||||||
|
.venv\Scripts\pytest apps/users/tests/domain/test_user_account.py::TestCanLogIn::test_inactive_user_cannot_log_in
|
||||||
```powershell
|
.venv\Scripts\pytest apps -m "not django_db" # fast tests without DB
|
||||||
.venv\Scripts\pytest apps # all tests
|
.venv\Scripts\pytest tests/browser -m browser # Playwright + axe, light/dark, 1920/320 px; needs npm run build
|
||||||
.venv\Scripts\pytest apps/customers/tests/domain/test_x.py::test_name # single test
|
.venv\Scripts\lint-imports # layer contracts in pyproject.toml
|
||||||
.venv\Scripts\pytest apps -m "not django_db" # fast tests that don't touch the DB
|
|
||||||
.venv\Scripts\lint-imports # layer/module dependency rules
|
|
||||||
.venv\Scripts\mypy apps
|
.venv\Scripts\mypy apps
|
||||||
.venv\Scripts\ruff check . ; .venv\Scripts\ruff format .
|
.venv\Scripts\ruff check . ; .venv\Scripts\ruff format .
|
||||||
npm run dev / npm run build # Tailwind + daisyUI -> static/dist/app.css
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Translations: source strings are English; Finnish is in `locale/fi/LC_MESSAGES/django.po`. GNU gettext lives in `%LOCALAPPDATA%\Programs\gettext-iconv\bin` (prepend it to `PATH` if `makemessages` cannot find it). Run `makemessages -l fi --ignore=.venv --ignore=node_modules --ignore=static`, fill every new `msgstr`, then `compilemessages -l fi --ignore=.venv`. Tests assert Finnish texts, so stale `.mo` files make them fail.
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
|
||||||
- `config/settings.py` reads `.env` via python-dotenv. Variables: `DJANGO_SECRET_KEY` (required), `DJANGO_DEBUG`, `DJANGO_ALLOWED_HOSTS`, `DB_NAME` (default `django-toiminnanohjaus`), `DB_USER`, `DB_PASSWORD`, `DB_HOST`, `DB_PORT`. `.env` is gitignored; `.env.example` is the template.
|
- `config/settings.py` reads `.env` via python-dotenv. Variables: `DJANGO_SECRET_KEY` (required), `DJANGO_DEBUG`, `DJANGO_ALLOWED_HOSTS`, `DB_NAME` (default `django-toiminnanohjaus`), `DB_USER`, `DB_PASSWORD`, `DB_HOST`, `DB_PORT`. `.env` is gitignored; `.env.example` is the template.
|
||||||
- The database engine is `django.db.backends.mysql` (mysqlclient), with utf8mb4 and `STRICT_TRANS_TABLES`. The database name contains a hyphen, so backtick-quote it in raw SQL.
|
- The database engine is `django.db.backends.mysql` (mysqlclient), with utf8mb4 and `STRICT_TRANS_TABLES`. The database name contains a hyphen, so backtick-quote it in raw SQL.
|
||||||
- Settings use `LANGUAGE_CODE = "fi"` and `TIME_ZONE = "Europe/Helsinki"`. Templates go in `templates/` plus app templates, static files in `static/`, and `STATIC_ROOT` is `staticfiles/`.
|
- Settings use `LANGUAGE_CODE = "fi"` and `TIME_ZONE = "Europe/Helsinki"`. Templates go in `templates/` plus app templates, static files in `static/`, and `STATIC_ROOT` is `staticfiles/`.
|
||||||
- **The custom user model `users.User` (`AUTH_USER_MODEL`) does not exist yet.** The database was already migrated with Django's default `auth.User`. Before creating the users app, drop and recreate the (still empty) database, then rerun migrations.
|
- `AUTH_USER_MODEL = "users.User"` (`apps/users/infrastructure/orm.py`): email login, a role field, no `PermissionsMixin` and no Django admin. Permissions are role-based: `apps/users/domain/permissions.py` (`role_has`), `PermissionRequiredMixin`, and the template filter `{% if request.user|can:"users.manage" %}` (`{% load users_tags %}`).
|
||||||
|
- `LoginRequiredMiddleware` is on, so mark public views with `login_not_required`. `EnsureAccountIsUsable` logs out deactivated users and interns past their end date on every request.
|
||||||
|
- The cache is `DatabaseCache` (login throttling), so run `createcachetable` on new databases.
|
||||||
|
- **Templates and tags:**
|
||||||
|
- Each module's templates live in `apps/<module>/presentation/templates` and are added to `TEMPLATES['DIRS']` by a glob in settings.
|
||||||
|
- Template tag libraries live in `presentation/templatetags` and must be registered in `TEMPLATES['OPTIONS']['libraries']`.
|
||||||
|
- Shared layouts and components are in the project `templates/` folder (`base.html`, `layouts/auth.html`, `components/`).
|
||||||
|
- **Forms:** `FORM_RENDERER` (`apps/shared/presentation/forms.py`) renders every field with `components/field.html`. Forms should mix in `DaisyFormMixin`, which adds the daisyUI classes and `aria-describedby`/`aria-invalid` on errors and provides `add_domain_error(error, ERROR_MESSAGES)`.
|
||||||
|
|
||||||
## Architecture (target, see `docs/architecture.md`)
|
## Architecture (see `docs/architecture.md`)
|
||||||
|
|
||||||
The project is a modular monolith. Each business area is a Django app under `apps/<module>/` (planned: `shared`, `users`, `customers`, `jobs`, `tasks`, `time_tracking`, `expenses`, `catalog`, `sales`, `billing`, later `inventory`, `machines`). Each app has Clean Architecture layers:
|
The project is a modular monolith. Each business area is a Django app under `apps/<module>/` (planned: `shared`, `users`, `customers`, `jobs`, `tasks`, `time_tracking`, `expenses`, `catalog`, `sales`, `billing`, later `inventory`, `machines`). Each app has Clean Architecture layers:
|
||||||
|
|
||||||
@@ -53,7 +57,8 @@ The project is a modular monolith. Each business area is a Django app under `app
|
|||||||
- `application/` holds use cases (one class, one `execute()`, with dependencies injected through the constructor), frozen dataclass DTOs and query `Protocol`s. Query protocols are the module's public read API. This layer has no `django` imports.
|
- `application/` holds use cases (one class, one `execute()`, with dependencies injected through the constructor), frozen dataclass DTOs and query `Protocol`s. Query protocols are the module's public read API. This layer has no `django` imports.
|
||||||
- `infrastructure/` holds the Django models (named `…Model`, in `orm.py` and re-exported from the app's `models.py`; set `Meta.db_table` to the table names in spec section 14), the repository implementations and the query implementations, which return DTOs straight from the ORM.
|
- `infrastructure/` holds the Django models (named `…Model`, in `orm.py` and re-exported from the app's `models.py`; set `Meta.db_table` to the table names in spec section 14), the repository implementations and the query implementations, which return DTOs straight from the ORM.
|
||||||
- `presentation/` holds thin views, Django Forms and templates. Forms validate input shape and build DTOs. Domain errors are turned into field errors with `form.add_error()`. HTMX requests get partial templates.
|
- `presentation/` holds thin views, Django Forms and templates. Forms validate input shape and build DTOs. Domain errors are turned into field errors with `form.add_error()`. HTMX requests get partial templates.
|
||||||
- `container.py` is the composition root, with factory functions that wire the use cases. There is no DI framework.
|
- `container.py` is the composition root, with factory functions that wire the use cases. There is no DI framework. Presentation reaches infrastructure only through the container (import-linter enforces this; add every new module to the contracts in `pyproject.toml`).
|
||||||
|
- Tests live in `apps/<module>/tests/{domain,application,integration}`. Application tests use in-memory fakes (`apps/users/tests/fakes.py` shows the pattern) and need no DB.
|
||||||
|
|
||||||
Cross-cutting rules:
|
Cross-cutting rules:
|
||||||
|
|
||||||
@@ -72,6 +77,7 @@ WCAG 2.2 AA / EN 301 549 is the contract's acceptance criterion for the whole UI
|
|||||||
- After an HTMX swap, move focus deliberately and announce the change in an `aria-live` / `role="status"` region.
|
- After an HTMX swap, move focus deliberately and announce the change in an `aria-live` / `role="status"` region.
|
||||||
- Dialogs use `<dialog>` (the daisyUI modal).
|
- Dialogs use `<dialog>` (the daisyUI modal).
|
||||||
- **Layout:** no horizontal page scrolling from 320 px up to FullHD. The machine console needs touch targets of at least 44 × 44 px.
|
- **Layout:** no horizontal page scrolling from 320 px up to FullHD. The machine console needs touch targets of at least 44 × 44 px.
|
||||||
- **Implementation:** use daisyUI classes, with shared partials in `apps/shared/presentation/templates/components/`. Alpine.js is for local UI state only, never for business logic.
|
- **Implementation:** use daisyUI classes and the shared partials in `templates/components/`. Alpine.js is for local UI state only, never for business logic.
|
||||||
|
- **Colours:** daisyUI's default text colours fail WCAG contrast in places. `static/src/app.css` overrides soft alerts and badges, `.menu-title`, and the light theme's error and success colours. Use `link` rather than `link-primary` for text links. The browser tests (axe) catch regressions.
|
||||||
- **Assets:** no CDN in production; build the assets with npm.
|
- **Assets:** no CDN in production; build the assets with npm.
|
||||||
- **Texts:** all UI text goes through `gettext` / `{% translate %}`.
|
- **Texts:** all UI text goes through `gettext` / `{% translate %}`.
|
||||||
|
|||||||
@@ -1,8 +1,12 @@
|
|||||||
# Toiminnanohjaus (Django 5.2 LTS)
|
# Toiminnanohjaus (Django 5.2 LTS)
|
||||||
|
|
||||||
|
Määrittely: `docs/maarittely.md`, arkkitehtuuri: `docs/architecture.md`.
|
||||||
|
|
||||||
## Vaatimukset
|
## Vaatimukset
|
||||||
- Python 3.14
|
- Python 3.14
|
||||||
|
- Node.js (Tailwind CSS 4 + daisyUI 5 -build)
|
||||||
- XAMPP (vain MariaDB/MySQL käytössä – Apachea tai htdocs-kansiota ei tarvita)
|
- XAMPP (vain MariaDB/MySQL käytössä – Apachea tai htdocs-kansiota ei tarvita)
|
||||||
|
- GNU gettext käännösten kääntämiseen: `winget install mlocati.GetText`
|
||||||
|
|
||||||
## Käyttöönotto
|
## Käyttöönotto
|
||||||
1. Käynnistä **MySQL** XAMPP Control Panelista.
|
1. Käynnistä **MySQL** XAMPP Control Panelista.
|
||||||
@@ -10,16 +14,41 @@
|
|||||||
```powershell
|
```powershell
|
||||||
C:\xampp\mysql\bin\mysql.exe -u root -e "CREATE DATABASE IF NOT EXISTS ``django-toiminnanohjaus`` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
|
C:\xampp\mysql\bin\mysql.exe -u root -e "CREATE DATABASE IF NOT EXISTS ``django-toiminnanohjaus`` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
|
||||||
```
|
```
|
||||||
3. Kopioi `.env.example` → `.env` ja täytä arvot (jos ei vielä ole).
|
3. Kopioi `.env.example` → `.env` ja täytä arvot (`DJANGO_SECRET_KEY` vähintään).
|
||||||
4. Asenna riippuvuudet ja aja migraatiot:
|
4. Asenna riippuvuudet, rakenna käyttöliittymä ja käännökset, aja migraatiot:
|
||||||
```powershell
|
```powershell
|
||||||
py -3.14 -m venv .venv
|
py -3.14 -m venv .venv
|
||||||
.venv\Scripts\python -m pip install -r requirements.txt
|
.venv\Scripts\python -m pip install -r requirements-dev.txt
|
||||||
|
npm install
|
||||||
|
npm run build
|
||||||
|
.venv\Scripts\python manage.py compilemessages -l fi --ignore=.venv
|
||||||
.venv\Scripts\python manage.py migrate
|
.venv\Scripts\python manage.py migrate
|
||||||
.venv\Scripts\python manage.py createsuperuser
|
.venv\Scripts\python manage.py createcachetable
|
||||||
```
|
```
|
||||||
5. Käynnistä kehityspalvelin:
|
5. Luo ensimmäinen pääkäyttäjä. Salasanan asetuslinkki tulostuu konsoliin (kehityksessä sähköposti tulostuu konsoliin):
|
||||||
|
```powershell
|
||||||
|
.venv\Scripts\python manage.py create_admin "Nimi" [email protected]
|
||||||
|
```
|
||||||
|
6. Käynnistä kehityspalvelin ja avaa http://127.0.0.1:8000/:
|
||||||
```powershell
|
```powershell
|
||||||
.venv\Scripts\python manage.py runserver
|
.venv\Scripts\python manage.py runserver
|
||||||
```
|
```
|
||||||
Avaa http://127.0.0.1:8000/ ja ylläpito http://127.0.0.1:8000/admin/
|
Tyylejä muokatessa `npm run dev` rakentaa CSS:n automaattisesti uudelleen.
|
||||||
|
|
||||||
|
## Testit ja tarkistukset
|
||||||
|
```powershell
|
||||||
|
.venv\Scripts\pytest apps # domain-, application- ja integraatiotestit
|
||||||
|
.venv\Scripts\pytest apps -m "not django_db" # nopeat testit ilman tietokantaa
|
||||||
|
.venv\Scripts\python -m playwright install chromium # kerran
|
||||||
|
.venv\Scripts\pytest tests/browser -m browser # saavutettavuus (axe) selaimessa, vaatii npm run build
|
||||||
|
.venv\Scripts\lint-imports # kerrossäännöt
|
||||||
|
.venv\Scripts\mypy apps
|
||||||
|
.venv\Scripts\ruff check . ; .venv\Scripts\ruff format .
|
||||||
|
```
|
||||||
|
|
||||||
|
## Käännökset
|
||||||
|
Lähdetekstit ovat englanniksi, suomenkieliset käännökset tiedostossa `locale/fi/LC_MESSAGES/django.po`.
|
||||||
|
```powershell
|
||||||
|
.venv\Scripts\python manage.py makemessages -l fi --ignore=.venv --ignore=node_modules --ignore=static
|
||||||
|
.venv\Scripts\python manage.py compilemessages -l fi --ignore=.venv
|
||||||
|
```
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
"""Ports that application layers of all modules depend on."""
|
||||||
|
|
||||||
|
from collections.abc import Callable
|
||||||
|
from contextlib import AbstractContextManager
|
||||||
|
from datetime import date
|
||||||
|
from types import TracebackType
|
||||||
|
from typing import Protocol
|
||||||
|
|
||||||
|
|
||||||
|
class UnitOfWork(Protocol):
|
||||||
|
"""Transaction boundary of a use case: ``with uow: ...``."""
|
||||||
|
|
||||||
|
def __enter__(self) -> object: ...
|
||||||
|
|
||||||
|
def __exit__(
|
||||||
|
self,
|
||||||
|
exc_type: type[BaseException] | None,
|
||||||
|
exc: BaseException | None,
|
||||||
|
tb: TracebackType | None,
|
||||||
|
) -> bool | None: ...
|
||||||
|
|
||||||
|
|
||||||
|
class EventPublisher(Protocol):
|
||||||
|
def publish(self, event: object) -> None: ...
|
||||||
|
|
||||||
|
|
||||||
|
class Clock(Protocol):
|
||||||
|
def today(self) -> date:
|
||||||
|
"""Current date in the business time zone."""
|
||||||
|
...
|
||||||
|
|
||||||
|
|
||||||
|
EventHandler = Callable[[object], None]
|
||||||
|
TransactionFactory = Callable[[], AbstractContextManager[object]]
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
from django.apps import AppConfig
|
||||||
|
|
||||||
|
|
||||||
|
class SharedConfig(AppConfig):
|
||||||
|
name = "apps.shared"
|
||||||
|
label = "shared"
|
||||||
|
default_auto_field = "django.db.models.BigAutoField"
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
"""Base class for business rule violations."""
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
|
||||||
|
class DomainError(Exception):
|
||||||
|
"""A business rule was violated.
|
||||||
|
|
||||||
|
``code`` identifies the rule; presentation maps it to a translated message.
|
||||||
|
``field`` optionally names the input field the error belongs to.
|
||||||
|
"""
|
||||||
|
|
||||||
|
code: str = "domain_error"
|
||||||
|
field: str | None = None
|
||||||
|
|
||||||
|
def __init__(self, **params: Any) -> None:
|
||||||
|
self.params = params
|
||||||
|
super().__init__(self.code)
|
||||||
|
|
||||||
|
|
||||||
|
class InvalidEmailAddress(DomainError):
|
||||||
|
code = "invalid_email"
|
||||||
|
field = "email"
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
"""Value objects shared by several modules."""
|
||||||
|
|
||||||
|
import re
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from apps.shared.domain.exceptions import InvalidEmailAddress
|
||||||
|
|
||||||
|
_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class EmailAddress:
|
||||||
|
value: str
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
normalized = self.value.strip().lower()
|
||||||
|
if len(normalized) > 254 or not _EMAIL_RE.match(normalized):
|
||||||
|
raise InvalidEmailAddress()
|
||||||
|
object.__setattr__(self, "value", normalized)
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
return self.value
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
from datetime import date, datetime
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
from django.conf import settings
|
||||||
|
|
||||||
|
|
||||||
|
class DjangoClock:
|
||||||
|
def today(self) -> date:
|
||||||
|
return datetime.now(ZoneInfo(settings.BUSINESS_TIME_ZONE)).date()
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
"""In-process domain event bus. Events are delivered after the transaction commits."""
|
||||||
|
|
||||||
|
from collections import defaultdict
|
||||||
|
from collections.abc import Callable
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from django.db import transaction
|
||||||
|
|
||||||
|
_handlers: dict[type, list[Callable[[Any], None]]] = defaultdict(list)
|
||||||
|
|
||||||
|
|
||||||
|
def subscribe(event_type: type, handler: Callable[[Any], None]) -> None:
|
||||||
|
"""Register a handler; call from ``AppConfig.ready()``."""
|
||||||
|
if handler not in _handlers[event_type]:
|
||||||
|
_handlers[event_type].append(handler)
|
||||||
|
|
||||||
|
|
||||||
|
def _dispatch(event: object) -> None:
|
||||||
|
for handler in list(_handlers[type(event)]):
|
||||||
|
handler(event)
|
||||||
|
|
||||||
|
|
||||||
|
class DjangoEventPublisher:
|
||||||
|
def publish(self, event: object) -> None:
|
||||||
|
transaction.on_commit(lambda: _dispatch(event))
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
from django.db import models
|
||||||
|
|
||||||
|
|
||||||
|
class TimestampedModel(models.Model):
|
||||||
|
created_at = models.DateTimeField(auto_now_add=True)
|
||||||
|
updated_at = models.DateTimeField(auto_now=True)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
abstract = True
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
from types import TracebackType
|
||||||
|
|
||||||
|
from django.db import transaction
|
||||||
|
|
||||||
|
|
||||||
|
class DjangoUnitOfWork:
|
||||||
|
"""Wraps a use case in ``transaction.atomic``."""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self._atomic: transaction.Atomic | None = None
|
||||||
|
|
||||||
|
def __enter__(self) -> DjangoUnitOfWork:
|
||||||
|
self._atomic = transaction.atomic()
|
||||||
|
self._atomic.__enter__()
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(
|
||||||
|
self,
|
||||||
|
exc_type: type[BaseException] | None,
|
||||||
|
exc: BaseException | None,
|
||||||
|
tb: TracebackType | None,
|
||||||
|
) -> None:
|
||||||
|
assert self._atomic is not None
|
||||||
|
self._atomic.__exit__(exc_type, exc, tb)
|
||||||
|
self._atomic = None
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
# The shared app has no concrete models; TimestampedModel is abstract.
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
"""Form helpers that give every form the same daisyUI styling and ARIA wiring."""
|
||||||
|
|
||||||
|
from collections.abc import Mapping
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from django import forms
|
||||||
|
from django.forms.renderers import TemplatesSetting
|
||||||
|
from django.forms.widgets import Input
|
||||||
|
|
||||||
|
from apps.shared.domain.exceptions import DomainError
|
||||||
|
|
||||||
|
|
||||||
|
class DaisyFormRenderer(TemplatesSetting):
|
||||||
|
"""Renders ``{{ field.as_field_group }}`` / ``{{ form }}`` with ``components/field.html``."""
|
||||||
|
|
||||||
|
form_template_name = "components/form.html"
|
||||||
|
field_template_name = "components/field.html"
|
||||||
|
|
||||||
|
|
||||||
|
_WIDGET_CLASSES: list[tuple[type[forms.Widget], str]] = [
|
||||||
|
(forms.CheckboxInput, "checkbox"),
|
||||||
|
(forms.RadioSelect, "radio"),
|
||||||
|
(forms.CheckboxSelectMultiple, "checkbox"),
|
||||||
|
(forms.Select, "select w-full"),
|
||||||
|
(forms.Textarea, "textarea w-full"),
|
||||||
|
(Input, "input w-full"),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
class DaisyFormMixin:
|
||||||
|
"""Adds daisyUI classes to widgets and links field errors with ``aria-describedby``."""
|
||||||
|
|
||||||
|
fields: dict[str, forms.Field]
|
||||||
|
|
||||||
|
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
for field in self.fields.values():
|
||||||
|
widget = field.widget
|
||||||
|
for widget_type, css in _WIDGET_CLASSES:
|
||||||
|
if isinstance(widget, widget_type):
|
||||||
|
existing = widget.attrs.get("class", "")
|
||||||
|
widget.attrs["class"] = f"{css} {existing}".strip()
|
||||||
|
break
|
||||||
|
|
||||||
|
def full_clean(self) -> None:
|
||||||
|
super().full_clean() # type: ignore[misc]
|
||||||
|
form: Any = self
|
||||||
|
for name in form.errors:
|
||||||
|
if name not in self.fields:
|
||||||
|
continue
|
||||||
|
bound = form[name]
|
||||||
|
widget = self.fields[name].widget
|
||||||
|
error_id = f"{bound.auto_id}_error"
|
||||||
|
described = widget.attrs.get("aria-describedby", "")
|
||||||
|
if error_id not in described.split():
|
||||||
|
widget.attrs["aria-describedby"] = f"{described} {error_id}".strip()
|
||||||
|
widget.attrs["aria-invalid"] = "true"
|
||||||
|
|
||||||
|
def add_domain_error(self, error: DomainError, messages: Mapping[str, object]) -> None:
|
||||||
|
"""Show a domain rule violation as a field (or non-field) error."""
|
||||||
|
form: Any = self
|
||||||
|
message = str(messages.get(error.code, messages.get("*", error.code)))
|
||||||
|
field = error.field if error.field in self.fields else None
|
||||||
|
form.add_error(field, message)
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
from django.http import HttpRequest, HttpResponse
|
||||||
|
from django.shortcuts import render
|
||||||
|
|
||||||
|
|
||||||
|
def home(request: HttpRequest) -> HttpResponse:
|
||||||
|
return render(request, "home.html")
|
||||||
@@ -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
|
||||||
@@ -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."""
|
||||||
|
...
|
||||||
@@ -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."""
|
||||||
|
...
|
||||||
@@ -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())
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
from django.apps import AppConfig
|
||||||
|
|
||||||
|
|
||||||
|
class UsersConfig(AppConfig):
|
||||||
|
name = "apps.users"
|
||||||
|
label = "users"
|
||||||
|
default_auto_field = "django.db.models.BigAutoField"
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
"""Composition root of the users module: wires use cases to their implementations."""
|
||||||
|
|
||||||
|
from apps.shared.infrastructure.clock import DjangoClock
|
||||||
|
from apps.shared.infrastructure.unit_of_work import DjangoUnitOfWork
|
||||||
|
from apps.users.application.dto import PasswordLinkPurpose
|
||||||
|
from apps.users.application.queries import UserQueries
|
||||||
|
from apps.users.application.use_cases import (
|
||||||
|
CheckLoginAllowed,
|
||||||
|
CreateUser,
|
||||||
|
IssuePasswordLink,
|
||||||
|
RequestPasswordReset,
|
||||||
|
UpdateUser,
|
||||||
|
)
|
||||||
|
from apps.users.infrastructure.orm import User
|
||||||
|
from apps.users.infrastructure.password_links import DjangoPasswordLinkService
|
||||||
|
from apps.users.infrastructure.queries import DjangoUserQueries
|
||||||
|
from apps.users.infrastructure.repositories import DjangoUserRepository
|
||||||
|
from apps.users.infrastructure.throttle import LoginThrottle
|
||||||
|
from apps.users.infrastructure.tokens import token_generator
|
||||||
|
|
||||||
|
|
||||||
|
def create_user() -> CreateUser:
|
||||||
|
return CreateUser(DjangoUserRepository(), DjangoUnitOfWork(), DjangoPasswordLinkService())
|
||||||
|
|
||||||
|
|
||||||
|
def update_user() -> UpdateUser:
|
||||||
|
return UpdateUser(DjangoUserRepository(), DjangoUnitOfWork())
|
||||||
|
|
||||||
|
|
||||||
|
def issue_password_link() -> IssuePasswordLink:
|
||||||
|
return IssuePasswordLink(DjangoUserRepository(), DjangoPasswordLinkService())
|
||||||
|
|
||||||
|
|
||||||
|
def request_password_reset() -> RequestPasswordReset:
|
||||||
|
return RequestPasswordReset(DjangoUserRepository(), DjangoPasswordLinkService(), DjangoClock())
|
||||||
|
|
||||||
|
|
||||||
|
def check_login_allowed() -> CheckLoginAllowed:
|
||||||
|
return CheckLoginAllowed(DjangoUserRepository(), DjangoClock())
|
||||||
|
|
||||||
|
|
||||||
|
def user_queries() -> UserQueries:
|
||||||
|
return DjangoUserQueries()
|
||||||
|
|
||||||
|
|
||||||
|
def login_throttle() -> LoginThrottle:
|
||||||
|
return LoginThrottle()
|
||||||
|
|
||||||
|
|
||||||
|
def user_for_password_link(user_id: int, purpose: PasswordLinkPurpose, token: str) -> User | None:
|
||||||
|
"""The auth user a valid password link belongs to (Django's SetPasswordForm needs it)."""
|
||||||
|
user = User.objects.filter(pk=user_id).first()
|
||||||
|
if user is None or not token_generator(purpose).check_token(user, token):
|
||||||
|
return None
|
||||||
|
return user
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
from dataclasses import dataclass, replace
|
||||||
|
from datetime import date
|
||||||
|
from typing import Self
|
||||||
|
|
||||||
|
from apps.shared.domain.value_objects import EmailAddress
|
||||||
|
from apps.users.domain.enums import Role
|
||||||
|
from apps.users.domain.exceptions import (
|
||||||
|
InternRequiresEndDate,
|
||||||
|
InternRequiresSupervisor,
|
||||||
|
InvalidSupervisor,
|
||||||
|
)
|
||||||
|
from apps.users.domain.value_objects import PersonName
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class UserAccount:
|
||||||
|
"""Business view of a user (specification 2.1, 2.2).
|
||||||
|
|
||||||
|
Invariant: an intern always has an end date and a supervisor; other roles never have them.
|
||||||
|
"""
|
||||||
|
|
||||||
|
id: int | None
|
||||||
|
name: PersonName
|
||||||
|
email: EmailAddress
|
||||||
|
role: Role
|
||||||
|
is_active: bool
|
||||||
|
employment_ends_on: date | None
|
||||||
|
supervisor_id: int | None
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def register(
|
||||||
|
cls,
|
||||||
|
*,
|
||||||
|
name: PersonName,
|
||||||
|
email: EmailAddress,
|
||||||
|
role: Role,
|
||||||
|
employment_ends_on: date | None = None,
|
||||||
|
supervisor_id: int | None = None,
|
||||||
|
) -> Self:
|
||||||
|
return cls._validated(
|
||||||
|
id=None,
|
||||||
|
name=name,
|
||||||
|
email=email,
|
||||||
|
role=role,
|
||||||
|
is_active=True,
|
||||||
|
employment_ends_on=employment_ends_on,
|
||||||
|
supervisor_id=supervisor_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def reconstitute(
|
||||||
|
cls,
|
||||||
|
*,
|
||||||
|
id: int,
|
||||||
|
name: PersonName,
|
||||||
|
email: EmailAddress,
|
||||||
|
role: Role,
|
||||||
|
is_active: bool,
|
||||||
|
employment_ends_on: date | None,
|
||||||
|
supervisor_id: int | None,
|
||||||
|
) -> Self:
|
||||||
|
"""Rebuild a stored user without checking rules, so a bad row cannot break login."""
|
||||||
|
return cls(id, name, email, role, is_active, employment_ends_on, supervisor_id)
|
||||||
|
|
||||||
|
def update_details(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
name: PersonName,
|
||||||
|
email: EmailAddress,
|
||||||
|
role: Role,
|
||||||
|
is_active: bool,
|
||||||
|
employment_ends_on: date | None,
|
||||||
|
supervisor_id: int | None,
|
||||||
|
) -> Self:
|
||||||
|
return self._validated(
|
||||||
|
id=self.id,
|
||||||
|
name=name,
|
||||||
|
email=email,
|
||||||
|
role=role,
|
||||||
|
is_active=is_active,
|
||||||
|
employment_ends_on=employment_ends_on,
|
||||||
|
supervisor_id=supervisor_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
def with_id(self, id: int) -> Self:
|
||||||
|
return replace(self, id=id)
|
||||||
|
|
||||||
|
def can_log_in(self, today: date) -> bool:
|
||||||
|
if not self.is_active:
|
||||||
|
return False
|
||||||
|
if self.role is Role.INTERN:
|
||||||
|
return self.employment_ends_on is not None and self.employment_ends_on >= today
|
||||||
|
return True
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_active_admin(self) -> bool:
|
||||||
|
return self.is_active and self.role is Role.ADMIN
|
||||||
|
|
||||||
|
@property
|
||||||
|
def can_supervise(self) -> bool:
|
||||||
|
return self.is_active and self.role.can_supervise_interns
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _validated(
|
||||||
|
cls,
|
||||||
|
*,
|
||||||
|
id: int | None,
|
||||||
|
name: PersonName,
|
||||||
|
email: EmailAddress,
|
||||||
|
role: Role,
|
||||||
|
is_active: bool,
|
||||||
|
employment_ends_on: date | None,
|
||||||
|
supervisor_id: int | None,
|
||||||
|
) -> Self:
|
||||||
|
if role is Role.INTERN:
|
||||||
|
if employment_ends_on is None:
|
||||||
|
raise InternRequiresEndDate()
|
||||||
|
if supervisor_id is None:
|
||||||
|
raise InternRequiresSupervisor()
|
||||||
|
if id is not None and supervisor_id == id:
|
||||||
|
raise InvalidSupervisor()
|
||||||
|
else:
|
||||||
|
employment_ends_on = None
|
||||||
|
supervisor_id = None
|
||||||
|
return cls(id, name, email, role, is_active, employment_ends_on, supervisor_id)
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
from enum import StrEnum
|
||||||
|
|
||||||
|
|
||||||
|
class Role(StrEnum):
|
||||||
|
"""User roles (specification 2.2). Public: other modules may use it for authorization."""
|
||||||
|
|
||||||
|
ADMIN = "admin"
|
||||||
|
MANAGEMENT = "management"
|
||||||
|
EMPLOYEE = "employee"
|
||||||
|
INTERN = "intern"
|
||||||
|
SUBCONTRACTOR = "subcontractor"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def can_supervise_interns(self) -> bool:
|
||||||
|
return self in (Role.MANAGEMENT, Role.EMPLOYEE)
|
||||||
|
|
||||||
|
|
||||||
|
class Permission(StrEnum):
|
||||||
|
USERS_MANAGE = "users.manage"
|
||||||
|
CUSTOMERS_USE = "customers.use"
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
from apps.shared.domain.exceptions import DomainError
|
||||||
|
|
||||||
|
|
||||||
|
class InvalidPersonName(DomainError):
|
||||||
|
code = "invalid_name"
|
||||||
|
field = "name"
|
||||||
|
|
||||||
|
|
||||||
|
class InternRequiresEndDate(DomainError):
|
||||||
|
code = "intern_requires_end_date"
|
||||||
|
field = "employment_ends_on"
|
||||||
|
|
||||||
|
|
||||||
|
class InternRequiresSupervisor(DomainError):
|
||||||
|
code = "intern_requires_supervisor"
|
||||||
|
field = "supervisor_id"
|
||||||
|
|
||||||
|
|
||||||
|
class InvalidSupervisor(DomainError):
|
||||||
|
"""The supervisor must be an active management or employee user, not the user itself."""
|
||||||
|
|
||||||
|
code = "invalid_supervisor"
|
||||||
|
field = "supervisor_id"
|
||||||
|
|
||||||
|
|
||||||
|
class EmailAlreadyTaken(DomainError):
|
||||||
|
code = "email_taken"
|
||||||
|
field = "email"
|
||||||
|
|
||||||
|
|
||||||
|
class LastActiveAdmin(DomainError):
|
||||||
|
"""The last active admin cannot be deactivated or moved to another role."""
|
||||||
|
|
||||||
|
code = "last_active_admin"
|
||||||
|
|
||||||
|
|
||||||
|
class SupervisorHasInterns(DomainError):
|
||||||
|
"""A supervisor of active interns cannot be deactivated or moved to a non-supervising role."""
|
||||||
|
|
||||||
|
code = "supervisor_has_interns"
|
||||||
|
|
||||||
|
|
||||||
|
class UserNotFound(DomainError):
|
||||||
|
code = "user_not_found"
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
"""Role based permissions (specification 2.4). Extended module by module."""
|
||||||
|
|
||||||
|
from apps.users.domain.enums import Permission, Role
|
||||||
|
|
||||||
|
_ALL_EXCEPT_SUBCONTRACTOR = frozenset({Role.ADMIN, Role.MANAGEMENT, Role.EMPLOYEE, Role.INTERN})
|
||||||
|
|
||||||
|
_PERMISSIONS: dict[Permission, frozenset[Role]] = {
|
||||||
|
Permission.USERS_MANAGE: frozenset({Role.ADMIN}),
|
||||||
|
Permission.CUSTOMERS_USE: _ALL_EXCEPT_SUBCONTRACTOR,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def role_has(role: Role, permission: Permission) -> bool:
|
||||||
|
return role in _PERMISSIONS.get(permission, frozenset())
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
from typing import Protocol
|
||||||
|
|
||||||
|
from apps.shared.domain.value_objects import EmailAddress
|
||||||
|
from apps.users.domain.entities import UserAccount
|
||||||
|
|
||||||
|
|
||||||
|
class UserRepository(Protocol):
|
||||||
|
def get_by_id(self, user_id: int) -> UserAccount | None: ...
|
||||||
|
|
||||||
|
def get_by_email(self, email: EmailAddress) -> UserAccount | None: ...
|
||||||
|
|
||||||
|
def save(self, user: UserAccount) -> UserAccount:
|
||||||
|
"""Insert or update; a new user gets its id here."""
|
||||||
|
...
|
||||||
|
|
||||||
|
def is_email_taken(self, email: EmailAddress, *, exclude_id: int | None = None) -> bool: ...
|
||||||
|
|
||||||
|
def lock_active_admin_count(self) -> int:
|
||||||
|
"""Lock the active admin rows for the transaction and return their number."""
|
||||||
|
...
|
||||||
|
|
||||||
|
def has_active_interns(self, supervisor_id: int) -> bool: ...
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from apps.users.domain.exceptions import InvalidPersonName
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class PersonName:
|
||||||
|
value: str
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
normalized = " ".join(self.value.split())
|
||||||
|
if not normalized or len(normalized) > 150:
|
||||||
|
raise InvalidPersonName()
|
||||||
|
object.__setattr__(self, "value", normalized)
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
return self.value
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from django.contrib.auth.backends import BaseBackend
|
||||||
|
from django.http import HttpRequest
|
||||||
|
|
||||||
|
from apps.shared.infrastructure.clock import DjangoClock
|
||||||
|
from apps.users.application.use_cases import CheckLoginAllowed
|
||||||
|
from apps.users.infrastructure.orm import User
|
||||||
|
from apps.users.infrastructure.repositories import DjangoUserRepository
|
||||||
|
|
||||||
|
|
||||||
|
class EmailBackend(BaseBackend):
|
||||||
|
"""Email + password login; the user must be allowed to log in today (CheckLoginAllowed)."""
|
||||||
|
|
||||||
|
def authenticate(
|
||||||
|
self,
|
||||||
|
request: HttpRequest | None,
|
||||||
|
username: str | None = None,
|
||||||
|
password: str | None = None,
|
||||||
|
email: str | None = None,
|
||||||
|
**kwargs: Any,
|
||||||
|
) -> User | None:
|
||||||
|
address = (email or username or "").strip().lower()
|
||||||
|
if not address or password is None:
|
||||||
|
return None
|
||||||
|
user = User.objects.filter(email__iexact=address).first()
|
||||||
|
if user is None:
|
||||||
|
# Run the hasher anyway so response time does not reveal unknown emails.
|
||||||
|
User().set_password(password)
|
||||||
|
return None
|
||||||
|
if user.check_password(password) and self.user_can_authenticate(user):
|
||||||
|
return user
|
||||||
|
return None
|
||||||
|
|
||||||
|
def user_can_authenticate(self, user: User) -> bool:
|
||||||
|
return CheckLoginAllowed(DjangoUserRepository(), DjangoClock()).execute(user.pk)
|
||||||
|
|
||||||
|
def get_user(self, user_id: int) -> User | None:
|
||||||
|
return User.objects.filter(pk=user_id).first()
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
|
||||||
|
from django.db import models
|
||||||
|
|
||||||
|
from apps.shared.infrastructure.models import TimestampedModel
|
||||||
|
from apps.users.domain.enums import Role
|
||||||
|
|
||||||
|
|
||||||
|
class UserManager(BaseUserManager["User"]):
|
||||||
|
use_in_migrations = True
|
||||||
|
|
||||||
|
def create_user(self, email: str, name: str, password: str | None = None, **extra: Any) -> User:
|
||||||
|
user = self.model(email=self.normalize_email(email).lower(), name=name, **extra)
|
||||||
|
if password:
|
||||||
|
user.set_password(password)
|
||||||
|
else:
|
||||||
|
user.set_unusable_password()
|
||||||
|
user.save(using=self._db)
|
||||||
|
return user
|
||||||
|
|
||||||
|
def create_superuser(
|
||||||
|
self, email: str, name: str, password: str | None = None, **extra: Any
|
||||||
|
) -> User:
|
||||||
|
extra.setdefault("role", Role.ADMIN.value)
|
||||||
|
return self.create_user(email, name, password, **extra)
|
||||||
|
|
||||||
|
|
||||||
|
class User(AbstractBaseUser, TimestampedModel):
|
||||||
|
"""Persistence model of users.UserAccount and Django's AUTH_USER_MODEL.
|
||||||
|
|
||||||
|
Business rules live in the domain entity; change users through the use cases.
|
||||||
|
"""
|
||||||
|
|
||||||
|
email = models.EmailField(unique=True, max_length=254)
|
||||||
|
name = models.CharField(max_length=150)
|
||||||
|
role = models.CharField(max_length=20, default=Role.EMPLOYEE.value)
|
||||||
|
is_active = models.BooleanField(default=True)
|
||||||
|
employment_ends_on = models.DateField(null=True, blank=True)
|
||||||
|
supervisor = models.ForeignKey(
|
||||||
|
"self", null=True, blank=True, on_delete=models.PROTECT, related_name="interns"
|
||||||
|
)
|
||||||
|
# Incremented whenever a password link is issued; earlier links then stop working.
|
||||||
|
password_link_nonce = models.PositiveIntegerField(default=0)
|
||||||
|
|
||||||
|
objects = UserManager()
|
||||||
|
|
||||||
|
USERNAME_FIELD = "email"
|
||||||
|
EMAIL_FIELD = "email"
|
||||||
|
REQUIRED_FIELDS = ["name"]
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
db_table = "users"
|
||||||
|
ordering = ["name"]
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
return self.name
|
||||||
|
|
||||||
|
@property
|
||||||
|
def role_enum(self) -> Role:
|
||||||
|
return Role(self.role)
|
||||||
|
|
||||||
|
# Django admin is not used; these keep third-party code that asks happy.
|
||||||
|
@property
|
||||||
|
def is_staff(self) -> bool:
|
||||||
|
return False
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_superuser(self) -> bool:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def has_perm(self, perm: str, obj: object = None) -> bool:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def has_module_perms(self, app_label: str) -> bool:
|
||||||
|
return False
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
from django.core.exceptions import ValidationError
|
||||||
|
from django.utils.translation import gettext as _
|
||||||
|
|
||||||
|
|
||||||
|
class ComplexityValidator:
|
||||||
|
"""At least 12 characters with upper and lower case letters, a digit and a special character."""
|
||||||
|
|
||||||
|
min_length = 12
|
||||||
|
|
||||||
|
def validate(self, password: str, user: object = None) -> None:
|
||||||
|
errors: list[ValidationError] = []
|
||||||
|
if len(password) < self.min_length:
|
||||||
|
errors.append(
|
||||||
|
ValidationError(
|
||||||
|
_("The password must be at least %(min)d characters long.")
|
||||||
|
% {"min": self.min_length},
|
||||||
|
code="password_too_short",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
checks = [
|
||||||
|
(
|
||||||
|
any(c.isupper() for c in password),
|
||||||
|
_("The password must contain an upper case letter."),
|
||||||
|
"password_no_upper",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
any(c.islower() for c in password),
|
||||||
|
_("The password must contain a lower case letter."),
|
||||||
|
"password_no_lower",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
any(c.isdigit() for c in password),
|
||||||
|
_("The password must contain a digit."),
|
||||||
|
"password_no_digit",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
any(not c.isalnum() and not c.isspace() for c in password),
|
||||||
|
_("The password must contain a special character."),
|
||||||
|
"password_no_special",
|
||||||
|
),
|
||||||
|
]
|
||||||
|
errors += [ValidationError(message, code=code) for ok, message, code in checks if not ok]
|
||||||
|
if errors:
|
||||||
|
raise ValidationError(errors)
|
||||||
|
|
||||||
|
def get_help_text(self) -> str:
|
||||||
|
return _(
|
||||||
|
"At least %(min)d characters, including upper and lower case letters, "
|
||||||
|
"a digit and a special character."
|
||||||
|
) % {"min": self.min_length}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import logging
|
||||||
|
from datetime import timedelta
|
||||||
|
|
||||||
|
from django.conf import settings
|
||||||
|
from django.core.mail import send_mail
|
||||||
|
from django.db.models import F
|
||||||
|
from django.template.loader import render_to_string
|
||||||
|
from django.urls import reverse
|
||||||
|
from django.utils import timezone
|
||||||
|
from django.utils.encoding import force_bytes
|
||||||
|
from django.utils.http import urlsafe_base64_encode
|
||||||
|
|
||||||
|
from apps.users.application.dto import PasswordLink, PasswordLinkPurpose
|
||||||
|
from apps.users.domain.entities import UserAccount
|
||||||
|
from apps.users.infrastructure.orm import User
|
||||||
|
from apps.users.infrastructure.tokens import token_generator
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class DjangoPasswordLinkService:
|
||||||
|
def issue(self, user_id: int, purpose: PasswordLinkPurpose) -> PasswordLink:
|
||||||
|
User.objects.filter(pk=user_id).update(password_link_nonce=F("password_link_nonce") + 1)
|
||||||
|
user = User.objects.get(pk=user_id)
|
||||||
|
generator = token_generator(purpose)
|
||||||
|
path = reverse(
|
||||||
|
"users:set_password",
|
||||||
|
kwargs={
|
||||||
|
"purpose": purpose.value,
|
||||||
|
"uidb64": urlsafe_base64_encode(force_bytes(user.pk)),
|
||||||
|
"token": generator.make_token(user),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
return PasswordLink(
|
||||||
|
url=f"{settings.SITE_URL.rstrip('/')}{path}",
|
||||||
|
expires_at=timezone.now() + timedelta(seconds=generator.timeout_seconds),
|
||||||
|
)
|
||||||
|
|
||||||
|
def send(self, user: UserAccount, link: PasswordLink, purpose: PasswordLinkPurpose) -> bool:
|
||||||
|
context = {
|
||||||
|
"name": user.name.value,
|
||||||
|
"url": link.url,
|
||||||
|
"expires_at": link.expires_at,
|
||||||
|
"purpose": purpose.value,
|
||||||
|
}
|
||||||
|
subject = render_to_string("users/email/password_link_subject.txt", context).strip()
|
||||||
|
body = render_to_string("users/email/password_link.txt", context)
|
||||||
|
try:
|
||||||
|
send_mail(subject, body, None, [user.email.value])
|
||||||
|
except Exception:
|
||||||
|
logger.exception("Sending the password link to user %s failed", user.id)
|
||||||
|
return False
|
||||||
|
return True
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
from django.db.models import Q
|
||||||
|
|
||||||
|
from apps.users.application.dto import SupervisorChoice, UserDetailsData, UserSummary
|
||||||
|
from apps.users.domain.enums import Role
|
||||||
|
from apps.users.infrastructure.orm import User
|
||||||
|
|
||||||
|
|
||||||
|
def _summary(user: User) -> UserSummary:
|
||||||
|
return UserSummary(
|
||||||
|
id=user.pk,
|
||||||
|
name=user.name,
|
||||||
|
email=user.email,
|
||||||
|
role=Role(user.role),
|
||||||
|
is_active=user.is_active,
|
||||||
|
employment_ends_on=user.employment_ends_on,
|
||||||
|
supervisor_name=user.supervisor.name if user.supervisor else None,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class DjangoUserQueries:
|
||||||
|
def list_users(
|
||||||
|
self, *, search: str = "", role: Role | None = None, is_active: bool | None = None
|
||||||
|
) -> Sequence[UserSummary]:
|
||||||
|
qs = User.objects.select_related("supervisor").order_by("name", "pk")
|
||||||
|
if search:
|
||||||
|
qs = qs.filter(Q(name__icontains=search) | Q(email__icontains=search))
|
||||||
|
if role is not None:
|
||||||
|
qs = qs.filter(role=role.value)
|
||||||
|
if is_active is not None:
|
||||||
|
qs = qs.filter(is_active=is_active)
|
||||||
|
return [_summary(u) for u in qs]
|
||||||
|
|
||||||
|
def get_details(self, user_id: int) -> UserDetailsData | None:
|
||||||
|
user = User.objects.filter(pk=user_id).first()
|
||||||
|
if user is None:
|
||||||
|
return None
|
||||||
|
return UserDetailsData(
|
||||||
|
name=user.name,
|
||||||
|
email=user.email,
|
||||||
|
role=Role(user.role),
|
||||||
|
is_active=user.is_active,
|
||||||
|
employment_ends_on=user.employment_ends_on,
|
||||||
|
supervisor_id=user.supervisor_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
def get_summary(self, user_id: int) -> UserSummary | None:
|
||||||
|
user = User.objects.select_related("supervisor").filter(pk=user_id).first()
|
||||||
|
return _summary(user) if user else None
|
||||||
|
|
||||||
|
def supervisor_choices(self, *, exclude_id: int | None = None) -> Sequence[SupervisorChoice]:
|
||||||
|
qs = User.objects.filter(
|
||||||
|
is_active=True, role__in=[Role.MANAGEMENT.value, Role.EMPLOYEE.value]
|
||||||
|
).order_by("name")
|
||||||
|
if exclude_id is not None:
|
||||||
|
qs = qs.exclude(pk=exclude_id)
|
||||||
|
return [SupervisorChoice(id=u.pk, name=u.name) for u in qs]
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
def to_entity(model: User) -> UserAccount:
|
||||||
|
return UserAccount.reconstitute(
|
||||||
|
id=model.pk,
|
||||||
|
name=PersonName(model.name),
|
||||||
|
email=EmailAddress(model.email),
|
||||||
|
role=Role(model.role),
|
||||||
|
is_active=model.is_active,
|
||||||
|
employment_ends_on=model.employment_ends_on,
|
||||||
|
supervisor_id=model.supervisor_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class DjangoUserRepository:
|
||||||
|
def get_by_id(self, user_id: int) -> UserAccount | None:
|
||||||
|
model = User.objects.filter(pk=user_id).first()
|
||||||
|
return to_entity(model) if model else None
|
||||||
|
|
||||||
|
def get_by_email(self, email: EmailAddress) -> UserAccount | None:
|
||||||
|
model = User.objects.filter(email__iexact=email.value).first()
|
||||||
|
return to_entity(model) if model else None
|
||||||
|
|
||||||
|
def save(self, user: UserAccount) -> UserAccount:
|
||||||
|
if user.id is None:
|
||||||
|
model = User(password="")
|
||||||
|
model.set_unusable_password()
|
||||||
|
else:
|
||||||
|
model = User.objects.get(pk=user.id)
|
||||||
|
model.name = user.name.value
|
||||||
|
model.email = user.email.value
|
||||||
|
model.role = user.role.value
|
||||||
|
model.is_active = user.is_active
|
||||||
|
model.employment_ends_on = user.employment_ends_on
|
||||||
|
model.supervisor_id = user.supervisor_id
|
||||||
|
model.save()
|
||||||
|
return user.with_id(model.pk)
|
||||||
|
|
||||||
|
def is_email_taken(self, email: EmailAddress, *, exclude_id: int | None = None) -> bool:
|
||||||
|
qs = User.objects.filter(email__iexact=email.value)
|
||||||
|
if exclude_id is not None:
|
||||||
|
qs = qs.exclude(pk=exclude_id)
|
||||||
|
return qs.exists()
|
||||||
|
|
||||||
|
def lock_active_admin_count(self) -> int:
|
||||||
|
rows = User.objects.select_for_update().filter(is_active=True, role=Role.ADMIN.value)
|
||||||
|
return len(list(rows.values_list("pk", flat=True)))
|
||||||
|
|
||||||
|
def has_active_interns(self, supervisor_id: int) -> bool:
|
||||||
|
return User.objects.filter(
|
||||||
|
supervisor_id=supervisor_id, is_active=True, role=Role.INTERN.value
|
||||||
|
).exists()
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
"""Login attempt limit: 5 failed attempts per email + IP within 5 minutes."""
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
|
||||||
|
from django.core.cache import cache
|
||||||
|
|
||||||
|
MAX_ATTEMPTS = 5
|
||||||
|
WINDOW_SECONDS = 5 * 60
|
||||||
|
|
||||||
|
|
||||||
|
class LoginThrottle:
|
||||||
|
def _key(self, email: str, ip: str) -> str:
|
||||||
|
digest = hashlib.sha256(f"{email.strip().lower()}|{ip}".encode()).hexdigest()
|
||||||
|
return f"login-attempts:{digest}"
|
||||||
|
|
||||||
|
def is_blocked(self, email: str, ip: str) -> bool:
|
||||||
|
return int(cache.get(self._key(email, ip), 0)) >= MAX_ATTEMPTS
|
||||||
|
|
||||||
|
def register_failure(self, email: str, ip: str) -> None:
|
||||||
|
key = self._key(email, ip)
|
||||||
|
if not cache.add(key, 1, WINDOW_SECONDS):
|
||||||
|
try:
|
||||||
|
cache.incr(key)
|
||||||
|
except ValueError:
|
||||||
|
cache.set(key, 1, WINDOW_SECONDS)
|
||||||
|
|
||||||
|
def reset(self, email: str, ip: str) -> None:
|
||||||
|
cache.delete(self._key(email, ip))
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
"""Single-use password links with per-purpose lifetimes (specification 3)."""
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from django.conf import settings
|
||||||
|
from django.contrib.auth.tokens import PasswordResetTokenGenerator
|
||||||
|
from django.utils.crypto import constant_time_compare
|
||||||
|
from django.utils.http import base36_to_int
|
||||||
|
|
||||||
|
from apps.users.application.dto import PasswordLinkPurpose
|
||||||
|
|
||||||
|
|
||||||
|
class PasswordLinkTokenGenerator(PasswordResetTokenGenerator):
|
||||||
|
"""Token that stops working when the password is set or a newer link is issued.
|
||||||
|
|
||||||
|
The hash covers the password hash (changes when the password is set: single use)
|
||||||
|
and ``password_link_nonce`` (incremented for every new link: older links die).
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, purpose: PasswordLinkPurpose, timeout_seconds: int) -> None:
|
||||||
|
super().__init__()
|
||||||
|
self.purpose = purpose
|
||||||
|
self.timeout_seconds = timeout_seconds
|
||||||
|
self.key_salt = f"apps.users.password_link.{purpose.value}"
|
||||||
|
|
||||||
|
def _make_hash_value(self, user: Any, timestamp: int) -> str:
|
||||||
|
return f"{user.pk}{user.password}{user.password_link_nonce}{timestamp}{user.email}"
|
||||||
|
|
||||||
|
def check_token(self, user: Any, token: str | None) -> bool:
|
||||||
|
if not (user and token):
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
ts_b36, _ = token.split("-")
|
||||||
|
ts = base36_to_int(ts_b36)
|
||||||
|
except ValueError:
|
||||||
|
return False
|
||||||
|
for secret in [self.secret, *self.secret_fallbacks]:
|
||||||
|
if constant_time_compare(self._make_token_with_timestamp(user, ts, secret), token):
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
return False
|
||||||
|
return (self._num_seconds(self._now()) - ts) <= self.timeout_seconds
|
||||||
|
|
||||||
|
|
||||||
|
def token_generator(purpose: PasswordLinkPurpose) -> PasswordLinkTokenGenerator:
|
||||||
|
timeout = (
|
||||||
|
settings.PASSWORD_LINK_SETUP_TIMEOUT
|
||||||
|
if purpose is PasswordLinkPurpose.SETUP
|
||||||
|
else settings.PASSWORD_RESET_TIMEOUT
|
||||||
|
)
|
||||||
|
return PasswordLinkTokenGenerator(purpose, timeout)
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from django.core.management.base import BaseCommand, CommandError, CommandParser
|
||||||
|
|
||||||
|
from apps.shared.domain.exceptions import DomainError
|
||||||
|
from apps.users.application.dto import UserDetailsData
|
||||||
|
from apps.users.container import create_user
|
||||||
|
from apps.users.domain.enums import Role
|
||||||
|
|
||||||
|
|
||||||
|
class Command(BaseCommand):
|
||||||
|
help = 'Creates an admin user and prints a password link: create_admin "Name" email'
|
||||||
|
|
||||||
|
def add_arguments(self, parser: CommandParser) -> None:
|
||||||
|
parser.add_argument("name")
|
||||||
|
parser.add_argument("email")
|
||||||
|
|
||||||
|
def handle(self, *args: Any, **options: Any) -> None:
|
||||||
|
data = UserDetailsData(name=options["name"], email=options["email"], role=Role.ADMIN)
|
||||||
|
try:
|
||||||
|
created = create_user().execute(data)
|
||||||
|
except DomainError as error:
|
||||||
|
raise CommandError(f"Could not create the admin: {error.code}") from error
|
||||||
|
link = created.password_link
|
||||||
|
self.stdout.write(self.style.SUCCESS(f"Admin created (id {created.user_id})."))
|
||||||
|
self.stdout.write(f"Password link (valid until {link.expires_at:%Y-%m-%d %H:%M} UTC):")
|
||||||
|
self.stdout.write(link.url)
|
||||||
|
if not link.emailed:
|
||||||
|
self.stdout.write(
|
||||||
|
self.style.WARNING("Sending the email failed; deliver the link yourself.")
|
||||||
|
)
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
# Generated by Django 5.2.19 on 2026-11-29 10:10
|
||||||
|
|
||||||
|
import apps.users.infrastructure.orm
|
||||||
|
import django.db.models.deletion
|
||||||
|
from django.conf import settings
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
initial = True
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.CreateModel(
|
||||||
|
name='User',
|
||||||
|
fields=[
|
||||||
|
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||||
|
('password', models.CharField(max_length=128, verbose_name='password')),
|
||||||
|
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
|
||||||
|
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||||
|
('updated_at', models.DateTimeField(auto_now=True)),
|
||||||
|
('email', models.EmailField(max_length=254, unique=True)),
|
||||||
|
('name', models.CharField(max_length=150)),
|
||||||
|
('role', models.CharField(default='employee', max_length=20)),
|
||||||
|
('is_active', models.BooleanField(default=True)),
|
||||||
|
('employment_ends_on', models.DateField(blank=True, null=True)),
|
||||||
|
('password_link_nonce', models.PositiveIntegerField(default=0)),
|
||||||
|
('supervisor', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='interns', to=settings.AUTH_USER_MODEL)),
|
||||||
|
],
|
||||||
|
options={
|
||||||
|
'db_table': 'users',
|
||||||
|
'ordering': ['name'],
|
||||||
|
},
|
||||||
|
managers=[
|
||||||
|
('objects', apps.users.infrastructure.orm.UserManager()),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
# Django discovers the module's ORM models through this file.
|
||||||
|
from apps.users.infrastructure.orm import User
|
||||||
|
|
||||||
|
__all__ = ["User"]
|
||||||
@@ -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"))],
|
||||||
|
)
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
"""Translated display names and error messages of the users module."""
|
||||||
|
|
||||||
|
from django.utils.translation import gettext_lazy as _
|
||||||
|
|
||||||
|
from apps.users.domain.enums import Role
|
||||||
|
|
||||||
|
ROLE_LABELS = {
|
||||||
|
Role.ADMIN: _("Admin"),
|
||||||
|
Role.MANAGEMENT: _("Management"),
|
||||||
|
Role.EMPLOYEE: _("Employee"),
|
||||||
|
Role.INTERN: _("Intern"),
|
||||||
|
Role.SUBCONTRACTOR: _("Subcontractor"),
|
||||||
|
}
|
||||||
|
|
||||||
|
ROLE_CHOICES = [(role.value, label) for role, label in ROLE_LABELS.items()]
|
||||||
|
|
||||||
|
ERROR_MESSAGES = {
|
||||||
|
"invalid_name": _("Enter a name (at most 150 characters)."),
|
||||||
|
"invalid_email": _("Enter a valid email address."),
|
||||||
|
"email_taken": _("A user with this email address already exists."),
|
||||||
|
"intern_requires_end_date": _("An intern must have an end date."),
|
||||||
|
"intern_requires_supervisor": _("An intern must have a supervisor."),
|
||||||
|
"invalid_supervisor": _("The supervisor must be an active management or employee user."),
|
||||||
|
"last_active_admin": _(
|
||||||
|
"This is the last active admin. It cannot be deactivated or moved to another role."
|
||||||
|
),
|
||||||
|
"supervisor_has_interns": _(
|
||||||
|
"This user supervises active interns. Change their supervisor first."
|
||||||
|
),
|
||||||
|
"user_not_found": _("The user was not found."),
|
||||||
|
"*": _("The change could not be saved."),
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
from collections.abc import Callable
|
||||||
|
|
||||||
|
from django.contrib.auth import logout
|
||||||
|
from django.http import HttpRequest, HttpResponse
|
||||||
|
from django.shortcuts import redirect
|
||||||
|
from django.urls import reverse
|
||||||
|
|
||||||
|
from apps.users.container import check_login_allowed
|
||||||
|
|
||||||
|
|
||||||
|
class EnsureAccountIsUsable:
|
||||||
|
"""Ends the session at once when the user is deactivated or the internship has ended.
|
||||||
|
|
||||||
|
The reason travels in the URL (``?access=ended``) so the login page can explain it.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]) -> None:
|
||||||
|
self.get_response = get_response
|
||||||
|
|
||||||
|
def __call__(self, request: HttpRequest) -> HttpResponse:
|
||||||
|
user = request.user
|
||||||
|
if user.is_authenticated and not check_login_allowed().execute(user.pk):
|
||||||
|
logout(request)
|
||||||
|
url = f"{reverse('users:login')}?access=ended"
|
||||||
|
if request.headers.get("HX-Request") == "true":
|
||||||
|
response = HttpResponse(status=204)
|
||||||
|
response["HX-Redirect"] = url
|
||||||
|
return response
|
||||||
|
return redirect(url)
|
||||||
|
return self.get_response(request)
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from django.core.exceptions import PermissionDenied
|
||||||
|
from django.http import HttpRequest, HttpResponseBase
|
||||||
|
|
||||||
|
from apps.users.domain.enums import Permission, Role
|
||||||
|
from apps.users.domain.permissions import role_has
|
||||||
|
|
||||||
|
|
||||||
|
def user_has(user: Any, permission: Permission | str) -> bool:
|
||||||
|
if not getattr(user, "is_authenticated", False):
|
||||||
|
return False
|
||||||
|
return role_has(Role(user.role), Permission(permission))
|
||||||
|
|
||||||
|
|
||||||
|
class PermissionRequiredMixin:
|
||||||
|
"""Requires a role based permission (specification 2.4); otherwise 403."""
|
||||||
|
|
||||||
|
permission: Permission
|
||||||
|
|
||||||
|
def dispatch(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponseBase:
|
||||||
|
if not user_has(request.user, self.permission):
|
||||||
|
raise PermissionDenied
|
||||||
|
response: HttpResponseBase = super().dispatch(request, *args, **kwargs) # type: ignore[misc]
|
||||||
|
return response
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
{% autoescape off %}{% blocktranslate %}Hello {{ name }},{% endblocktranslate %}
|
||||||
|
|
||||||
|
{% if purpose == "reset" %}{% translate "You asked for a link for setting a new password." %}{% else %}{% translate "An account has been created or a new password link has been requested for you." %}{% endif %}
|
||||||
|
{% translate "Set your password with this link:" %}
|
||||||
|
|
||||||
|
{{ url }}
|
||||||
|
|
||||||
|
{% blocktranslate with expires=expires_at|date:"j.n.Y H:i" %}The link can be used once and it is valid until {{ expires }}.{% endblocktranslate %}
|
||||||
|
{% translate "If you did not expect this message, you can ignore it." %}
|
||||||
|
{% endautoescape %}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{% if purpose == "reset" %}{% translate "Set a new password" %}{% else %}{% translate "Set your password" %}{% endif %} – Toiminnanohjaus
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
{% extends "layouts/auth.html" %}
|
||||||
|
{% block title %}{% translate "Forgot your password?" %}{% endblock %}
|
||||||
|
{% block content %}
|
||||||
|
<h1 class="card-title text-2xl">{% translate "Forgot your password?" %}</h1>
|
||||||
|
<p>{% translate "Enter your email address. We will send you a link for setting a new password." %}</p>
|
||||||
|
<form method="post" novalidate class="space-y-2">
|
||||||
|
{% csrf_token %}
|
||||||
|
{{ form }}
|
||||||
|
<button type="submit" class="btn btn-primary w-full mt-2">{% translate "Send link" %}</button>
|
||||||
|
</form>
|
||||||
|
<a class="link mt-2" href="{% url 'users:login' %}">{% translate "Back to login" %}</a>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
{% block title %}{% if user_id %}{% translate "Edit user" %}{% else %}{% translate "New user" %}{% endif %}{% endblock %}
|
||||||
|
{% block content %}
|
||||||
|
<nav class="breadcrumbs text-sm" aria-label="{% translate 'Breadcrumbs' %}">
|
||||||
|
<ul><li><a href="{% url 'users:list' %}">{% translate "Users" %}</a></li>
|
||||||
|
<li aria-current="page">{% if user_id %}{{ user_name }}{% else %}{% translate "New user" %}{% endif %}</li></ul>
|
||||||
|
</nav>
|
||||||
|
<h1 class="text-2xl font-bold mb-4">{% if user_id %}{% translate "Edit user" %}{% else %}{% translate "New user" %}{% endif %}</h1>
|
||||||
|
|
||||||
|
<div class="grid gap-4 lg:grid-cols-3">
|
||||||
|
<form method="post" novalidate class="card bg-base-100 shadow-sm lg:col-span-2"
|
||||||
|
x-data="{ role: '{{ form.role.value|default:'employee'|escapejs }}' }">
|
||||||
|
{% csrf_token %}
|
||||||
|
<div class="card-body">
|
||||||
|
{% include "components/non_field_errors.html" %}
|
||||||
|
{{ form.name.as_field_group }}
|
||||||
|
{{ form.email.as_field_group }}
|
||||||
|
{{ form.role.as_field_group }}
|
||||||
|
<div x-show="role === 'intern'" x-cloak class="border-l-4 border-base-300 pl-4">
|
||||||
|
<p class="text-sm">{% translate "An intern must have a last day and a supervisor." %}</p>
|
||||||
|
{{ form.employment_ends_on.as_field_group }}
|
||||||
|
{{ form.supervisor_id.as_field_group }}
|
||||||
|
</div>
|
||||||
|
{% if form.is_active %}{{ form.is_active.as_field_group }}{% endif %}
|
||||||
|
<div class="card-actions justify-end mt-4">
|
||||||
|
<a href="{% url 'users:list' %}" class="btn">{% translate "Cancel" %}</a>
|
||||||
|
<button type="submit" class="btn btn-primary">{% translate "Save" %}</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
{% if user_id %}
|
||||||
|
<section class="card bg-base-100 shadow-sm" aria-labelledby="password-link-title">
|
||||||
|
<div class="card-body">
|
||||||
|
<h2 id="password-link-title" class="card-title">{% translate "Password link" %}</h2>
|
||||||
|
<p class="text-sm">{% translate "Creates a new link for setting the password. The link is emailed to the user and shown here for copying. Earlier links stop working." %}</p>
|
||||||
|
<button type="button" class="btn" onclick="document.getElementById('confirm-password-link').showModal()">{% translate "Create password link" %}</button>
|
||||||
|
<div id="password-link-result"></div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
{% url 'users:password_link' user_id as link_url %}
|
||||||
|
{% translate "Create a new password link?" as dialog_title %}
|
||||||
|
{% translate "Earlier links of this user stop working." as dialog_body %}
|
||||||
|
{% translate "Create link" as dialog_confirm %}
|
||||||
|
{% include "components/confirm_dialog.html" with id="confirm-password-link" title=dialog_title body=dialog_body action_url=link_url confirm_label=dialog_confirm hx_target="#password-link-result" %}
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
{% block title %}{% translate "Users" %}{% endblock %}
|
||||||
|
{% block content %}
|
||||||
|
<div class="flex flex-wrap items-center justify-between gap-2 mb-4">
|
||||||
|
<h1 class="text-2xl font-bold">{% translate "Users" %}</h1>
|
||||||
|
<a href="{% url 'users:create' %}" class="btn btn-primary">{% translate "New user" %}</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form method="get" role="search" aria-label="{% translate 'Filter users' %}"
|
||||||
|
class="card bg-base-100 shadow-sm mb-4"
|
||||||
|
hx-get="{% url 'users:list' %}" hx-target="#user-table" hx-push-url="true"
|
||||||
|
hx-trigger="input changed delay:300ms from:input[name='q'], change from:select, submit">
|
||||||
|
<div class="card-body grid gap-2 sm:grid-cols-3 py-4">
|
||||||
|
{{ filters.q.as_field_group }}
|
||||||
|
{{ filters.role.as_field_group }}
|
||||||
|
{{ filters.active.as_field_group }}
|
||||||
|
<noscript><button type="submit" class="btn">{% translate "Filter" %}</button></noscript>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div id="user-table">
|
||||||
|
{% include "users/partials/user_table.html" %}
|
||||||
|
</div>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
{% extends "layouts/auth.html" %}
|
||||||
|
{% block title %}{% translate "Log in" %}{% endblock %}
|
||||||
|
{% block content %}
|
||||||
|
<h1 class="card-title text-2xl">{% translate "Log in" %}</h1>
|
||||||
|
{% if access_ended %}
|
||||||
|
<div role="alert" class="alert alert-warning alert-soft">
|
||||||
|
<span>{% translate "Your access has ended: the account has been deactivated or the internship has ended. Contact the admin if you think this is a mistake." %}</span>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
<form method="post" novalidate class="space-y-2">
|
||||||
|
{% csrf_token %}
|
||||||
|
{{ form }}
|
||||||
|
<input type="hidden" name="next" value="{{ next }}">
|
||||||
|
<button type="submit" class="btn btn-primary w-full mt-2">{% translate "Log in" %}</button>
|
||||||
|
</form>
|
||||||
|
<a class="link mt-2" href="{% url 'users:forgot_password' %}">{% translate "Forgot your password?" %}</a>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
<div class="space-y-2 mt-2" x-data="{ copied: false }" tabindex="-1" data-autofocus id="password-link-box">
|
||||||
|
<p role="status">
|
||||||
|
{% if link.emailed %}
|
||||||
|
{% blocktranslate with email=user_summary.email %}The link has been emailed to {{ email }}.{% endblocktranslate %}
|
||||||
|
{% else %}
|
||||||
|
<span class="text-error font-semibold">{% translate "Sending the email failed." %}</span>
|
||||||
|
{% translate "Deliver the link to the user in another way." %}
|
||||||
|
{% endif %}
|
||||||
|
{% blocktranslate with expires=link.expires_at|date:"j.n.Y H:i" %}Valid until {{ expires }}.{% endblocktranslate %}
|
||||||
|
</p>
|
||||||
|
<label class="fieldset-legend text-sm" for="password-link-url">{% translate "Link" %}</label>
|
||||||
|
<div class="join w-full">
|
||||||
|
<input id="password-link-url" class="input join-item w-full" readonly value="{{ link.url }}" x-ref="url">
|
||||||
|
<button type="button" class="btn btn-primary join-item"
|
||||||
|
@click="navigator.clipboard.writeText($refs.url.value).then(() => { copied = true; notify('{% translate "Link copied" %}') })">
|
||||||
|
{% translate "Copy" %}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p x-show="copied" class="text-success text-sm">{% translate "Link copied" %}</p>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
{% load users_tags %}
|
||||||
|
<p class="sr-only" role="status">{% blocktranslate count counter=page.paginator.count %}{{ counter }} user found{% plural %}{{ counter }} users found{% endblocktranslate %}</p>
|
||||||
|
<div class="overflow-x-auto card bg-base-100 shadow-sm">
|
||||||
|
<table class="table">
|
||||||
|
<caption class="sr-only">{% translate "Users" %}</caption>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th scope="col">{% translate "Name" %}</th>
|
||||||
|
<th scope="col">{% translate "Email" %}</th>
|
||||||
|
<th scope="col">{% translate "Role" %}</th>
|
||||||
|
<th scope="col">{% translate "Status" %}</th>
|
||||||
|
<th scope="col">{% translate "Last day" %}</th>
|
||||||
|
<th scope="col">{% translate "Supervisor" %}</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for u in page.object_list %}
|
||||||
|
<tr>
|
||||||
|
<td><a class="link" href="{% url 'users:edit' u.id %}">{{ u.name }}</a></td>
|
||||||
|
<td class="break-all">{{ u.email }}</td>
|
||||||
|
<td>{{ u.role|role_label }}</td>
|
||||||
|
<td>
|
||||||
|
{% if u.is_active %}<span class="badge badge-success badge-soft">{% translate "Active" %}</span>
|
||||||
|
{% else %}<span class="badge badge-ghost">{% translate "Inactive" %}</span>{% endif %}
|
||||||
|
</td>
|
||||||
|
<td>{{ u.employment_ends_on|date:"j.n.Y"|default:"–" }}</td>
|
||||||
|
<td>{{ u.supervisor_name|default:"–" }}</td>
|
||||||
|
</tr>
|
||||||
|
{% empty %}
|
||||||
|
<tr><td colspan="6">{% translate "No users match the filters." %}</td></tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
{% if page.paginator.num_pages > 1 %}
|
||||||
|
<nav aria-label="{% translate 'Pages' %}" class="join mt-4">
|
||||||
|
{% if page.has_previous %}
|
||||||
|
<a class="join-item btn" href="?{{ query }}{% if query %}&{% endif %}page={{ page.previous_page_number }}"
|
||||||
|
hx-get="?{{ query }}{% if query %}&{% endif %}page={{ page.previous_page_number }}" hx-target="#user-table" hx-push-url="true">{% translate "Previous" %}</a>
|
||||||
|
{% endif %}
|
||||||
|
<span class="join-item btn btn-disabled" aria-current="page">{% blocktranslate with n=page.number total=page.paginator.num_pages %}Page {{ n }} / {{ total }}{% endblocktranslate %}</span>
|
||||||
|
{% if page.has_next %}
|
||||||
|
<a class="join-item btn" href="?{{ query }}{% if query %}&{% endif %}page={{ page.next_page_number }}"
|
||||||
|
hx-get="?{{ query }}{% if query %}&{% endif %}page={{ page.next_page_number }}" hx-target="#user-table" hx-push-url="true">{% translate "Next" %}</a>
|
||||||
|
{% endif %}
|
||||||
|
</nav>
|
||||||
|
{% endif %}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
{% block title %}{% translate "Password link" %}{% endblock %}
|
||||||
|
{% block content %}
|
||||||
|
<h1 class="text-2xl font-bold mb-4">{% blocktranslate with name=user_summary.name %}Password link for {{ name }}{% endblocktranslate %}</h1>
|
||||||
|
<div class="card bg-base-100 shadow-sm max-w-2xl">
|
||||||
|
<div class="card-body">
|
||||||
|
{% include "users/partials/password_link.html" %}
|
||||||
|
<div class="card-actions mt-4">
|
||||||
|
<a href="{% url 'users:edit' user_summary.id %}" class="btn">{% translate "Edit user" %}</a>
|
||||||
|
<a href="{% url 'users:list' %}" class="btn btn-primary">{% translate "Back to users" %}</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
{% extends "layouts/auth.html" %}
|
||||||
|
{% block title %}{% translate "Set password" %}{% endblock %}
|
||||||
|
{% block content %}
|
||||||
|
<h1 class="card-title text-2xl">{% translate "Set password" %}</h1>
|
||||||
|
<form method="post" novalidate class="space-y-2">
|
||||||
|
{% csrf_token %}
|
||||||
|
{{ form }}
|
||||||
|
<button type="submit" class="btn btn-primary w-full mt-2">{% translate "Set password" %}</button>
|
||||||
|
</form>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
{% extends "layouts/auth.html" %}
|
||||||
|
{% block title %}{% translate "The link is not valid" %}{% endblock %}
|
||||||
|
{% block content %}
|
||||||
|
<h1 class="card-title text-2xl">{% translate "The link is not valid" %}</h1>
|
||||||
|
<p>{% translate "The link has expired, it has already been used, or a newer link has been created. Request a new link or ask the admin to create one." %}</p>
|
||||||
|
<a class="btn btn-primary mt-4" href="{% url 'users:forgot_password' %}">{% translate "Request a new link" %}</a>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from django import template
|
||||||
|
|
||||||
|
from apps.users.domain.enums import Role
|
||||||
|
from apps.users.presentation.labels import ROLE_LABELS
|
||||||
|
from apps.users.presentation.mixins import user_has
|
||||||
|
|
||||||
|
register = template.Library()
|
||||||
|
|
||||||
|
|
||||||
|
@register.filter
|
||||||
|
def can(user: Any, permission: str) -> bool:
|
||||||
|
"""``{% if request.user|can:"users.manage" %}``"""
|
||||||
|
return user_has(user, permission)
|
||||||
|
|
||||||
|
|
||||||
|
@register.filter
|
||||||
|
def role_label(role: Any) -> str:
|
||||||
|
return str(ROLE_LABELS.get(Role(role), role))
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
from django.contrib.auth import views as auth_views
|
||||||
|
from django.urls import path
|
||||||
|
|
||||||
|
from apps.users.presentation import views
|
||||||
|
|
||||||
|
app_name = "users"
|
||||||
|
|
||||||
|
urlpatterns = [
|
||||||
|
path("login/", views.LoginView.as_view(), name="login"),
|
||||||
|
path("logout/", auth_views.LogoutView.as_view(), name="logout"),
|
||||||
|
path("password/forgot/", views.ForgotPasswordView.as_view(), name="forgot_password"),
|
||||||
|
path(
|
||||||
|
"password/set/<str:purpose>/<str:uidb64>/<str:token>/",
|
||||||
|
views.SetPasswordView.as_view(),
|
||||||
|
name="set_password",
|
||||||
|
),
|
||||||
|
path("users/", views.UserListView.as_view(), name="list"),
|
||||||
|
path("users/new/", views.UserCreateView.as_view(), name="create"),
|
||||||
|
path("users/<int:pk>/edit/", views.UserUpdateView.as_view(), name="edit"),
|
||||||
|
path("users/<int:pk>/password-link/", views.PasswordLinkView.as_view(), name="password_link"),
|
||||||
|
]
|
||||||
@@ -0,0 +1,219 @@
|
|||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from django.contrib import messages
|
||||||
|
from django.contrib.auth import views as auth_views
|
||||||
|
from django.contrib.auth.decorators import login_not_required
|
||||||
|
from django.core.paginator import Paginator
|
||||||
|
from django.http import Http404, HttpRequest, HttpResponse
|
||||||
|
from django.shortcuts import redirect, render
|
||||||
|
from django.utils.decorators import method_decorator
|
||||||
|
from django.utils.encoding import force_str
|
||||||
|
from django.utils.http import urlsafe_base64_decode
|
||||||
|
from django.utils.translation import gettext as _
|
||||||
|
from django.views import View
|
||||||
|
from django.views.generic import FormView, TemplateView
|
||||||
|
|
||||||
|
from apps.shared.domain.exceptions import DomainError
|
||||||
|
from apps.users import container
|
||||||
|
from apps.users.application.dto import PasswordLinkPurpose
|
||||||
|
from apps.users.domain.enums import Permission, Role
|
||||||
|
from apps.users.presentation.forms import (
|
||||||
|
ForgotPasswordForm,
|
||||||
|
LoginForm,
|
||||||
|
PasswordSetForm,
|
||||||
|
UserFilterForm,
|
||||||
|
UserForm,
|
||||||
|
)
|
||||||
|
from apps.users.presentation.labels import ERROR_MESSAGES
|
||||||
|
from apps.users.presentation.mixins import PermissionRequiredMixin
|
||||||
|
|
||||||
|
|
||||||
|
class LoginView(auth_views.LoginView):
|
||||||
|
form_class = LoginForm
|
||||||
|
template_name = "users/login.html"
|
||||||
|
redirect_authenticated_user = True
|
||||||
|
|
||||||
|
def form_valid(self, form: LoginForm) -> HttpResponse: # type: ignore[override]
|
||||||
|
if not form.cleaned_data.get("remember_me"):
|
||||||
|
self.request.session.set_expiry(0) # ends when the browser is closed
|
||||||
|
return super().form_valid(form)
|
||||||
|
|
||||||
|
def get_context_data(self, **kwargs: Any) -> dict[str, Any]:
|
||||||
|
context = super().get_context_data(**kwargs)
|
||||||
|
context["access_ended"] = self.request.GET.get("access") == "ended"
|
||||||
|
return context
|
||||||
|
|
||||||
|
|
||||||
|
@method_decorator(login_not_required, name="dispatch")
|
||||||
|
class ForgotPasswordView(FormView): # type: ignore[type-arg]
|
||||||
|
form_class = ForgotPasswordForm
|
||||||
|
template_name = "users/forgot_password.html"
|
||||||
|
|
||||||
|
def form_valid(self, form: ForgotPasswordForm) -> HttpResponse:
|
||||||
|
container.request_password_reset().execute(form.cleaned_data["email"])
|
||||||
|
# Same answer for every address: the page must not reveal which emails exist.
|
||||||
|
messages.info(
|
||||||
|
self.request,
|
||||||
|
_(
|
||||||
|
"If the address belongs to a user who may log in, a link for setting "
|
||||||
|
"the password has been sent to it. The link is valid for 60 minutes."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
return redirect("users:login")
|
||||||
|
|
||||||
|
|
||||||
|
@method_decorator(login_not_required, name="dispatch")
|
||||||
|
class SetPasswordView(View):
|
||||||
|
template_name = "users/set_password.html"
|
||||||
|
|
||||||
|
def _get_user(self, purpose: str, uidb64: str, token: str) -> Any:
|
||||||
|
try:
|
||||||
|
link_purpose = PasswordLinkPurpose(purpose)
|
||||||
|
user_id = int(force_str(urlsafe_base64_decode(uidb64)))
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
user = container.user_for_password_link(user_id, link_purpose, token)
|
||||||
|
if user is None or not container.check_login_allowed().execute(user.pk):
|
||||||
|
return None
|
||||||
|
return user
|
||||||
|
|
||||||
|
def get(self, request: HttpRequest, purpose: str, uidb64: str, token: str) -> HttpResponse:
|
||||||
|
user = self._get_user(purpose, uidb64, token)
|
||||||
|
if user is None:
|
||||||
|
return render(request, "users/set_password_invalid.html", status=400)
|
||||||
|
return render(request, self.template_name, {"form": PasswordSetForm(user)})
|
||||||
|
|
||||||
|
def post(self, request: HttpRequest, purpose: str, uidb64: str, token: str) -> HttpResponse:
|
||||||
|
user = self._get_user(purpose, uidb64, token)
|
||||||
|
if user is None:
|
||||||
|
return render(request, "users/set_password_invalid.html", status=400)
|
||||||
|
form = PasswordSetForm(user, request.POST)
|
||||||
|
if not form.is_valid():
|
||||||
|
return render(request, self.template_name, {"form": form}, status=422)
|
||||||
|
# Saving changes the password hash: the link stops working and other sessions end.
|
||||||
|
form.save()
|
||||||
|
messages.success(request, _("Your password has been set. You can now log in."))
|
||||||
|
return redirect("users:login")
|
||||||
|
|
||||||
|
|
||||||
|
class UserListView(PermissionRequiredMixin, TemplateView):
|
||||||
|
permission = Permission.USERS_MANAGE
|
||||||
|
template_name = "users/list.html"
|
||||||
|
page_size = 25
|
||||||
|
|
||||||
|
def get_context_data(self, **kwargs: Any) -> dict[str, Any]:
|
||||||
|
context = super().get_context_data(**kwargs)
|
||||||
|
filters = UserFilterForm(self.request.GET or None)
|
||||||
|
search, role, active = "", None, None
|
||||||
|
if filters.is_valid():
|
||||||
|
search = filters.cleaned_data["q"].strip()
|
||||||
|
role = Role(filters.cleaned_data["role"]) if filters.cleaned_data["role"] else None
|
||||||
|
if filters.cleaned_data["active"] in ("0", "1"):
|
||||||
|
active = filters.cleaned_data["active"] == "1"
|
||||||
|
users = container.user_queries().list_users(search=search, role=role, is_active=active)
|
||||||
|
page = Paginator(users, self.page_size).get_page(self.request.GET.get("page"))
|
||||||
|
query = self.request.GET.copy()
|
||||||
|
query.pop("page", None)
|
||||||
|
context.update(filters=filters, page=page, query=query.urlencode())
|
||||||
|
return context
|
||||||
|
|
||||||
|
def get_template_names(self) -> list[str]:
|
||||||
|
if getattr(self.request, "htmx", False):
|
||||||
|
return ["users/partials/user_table.html"]
|
||||||
|
return [self.template_name]
|
||||||
|
|
||||||
|
|
||||||
|
class UserCreateView(PermissionRequiredMixin, FormView): # type: ignore[type-arg]
|
||||||
|
permission = Permission.USERS_MANAGE
|
||||||
|
form_class = UserForm
|
||||||
|
template_name = "users/form.html"
|
||||||
|
|
||||||
|
def get_form_kwargs(self) -> dict[str, Any]:
|
||||||
|
kwargs = super().get_form_kwargs()
|
||||||
|
kwargs["supervisors"] = container.user_queries().supervisor_choices()
|
||||||
|
kwargs["is_new"] = True
|
||||||
|
return kwargs
|
||||||
|
|
||||||
|
def form_valid(self, form: UserForm) -> HttpResponse:
|
||||||
|
try:
|
||||||
|
created = container.create_user().execute(form.to_dto())
|
||||||
|
except DomainError as error:
|
||||||
|
form.add_domain_error(error, ERROR_MESSAGES)
|
||||||
|
return self.render_to_response(self.get_context_data(form=form), status=422)
|
||||||
|
user = container.user_queries().get_summary(created.user_id)
|
||||||
|
messages.success(self.request, _("User created."))
|
||||||
|
return render(
|
||||||
|
self.request,
|
||||||
|
"users/password_link_page.html",
|
||||||
|
{"link": created.password_link, "user_summary": user},
|
||||||
|
)
|
||||||
|
|
||||||
|
def form_invalid(self, form: UserForm) -> HttpResponse:
|
||||||
|
return self.render_to_response(self.get_context_data(form=form), status=422)
|
||||||
|
|
||||||
|
|
||||||
|
class UserUpdateView(PermissionRequiredMixin, FormView): # type: ignore[type-arg]
|
||||||
|
permission = Permission.USERS_MANAGE
|
||||||
|
form_class = UserForm
|
||||||
|
template_name = "users/form.html"
|
||||||
|
|
||||||
|
def dispatch(self, request: HttpRequest, *args: Any, **kwargs: Any) -> Any:
|
||||||
|
self.details = container.user_queries().get_details(kwargs["pk"])
|
||||||
|
if self.details is None:
|
||||||
|
raise Http404
|
||||||
|
return super().dispatch(request, *args, **kwargs)
|
||||||
|
|
||||||
|
def get_initial(self) -> dict[str, Any]:
|
||||||
|
d = self.details
|
||||||
|
assert d is not None
|
||||||
|
return {
|
||||||
|
"name": d.name,
|
||||||
|
"email": d.email,
|
||||||
|
"role": d.role.value,
|
||||||
|
"is_active": d.is_active,
|
||||||
|
"employment_ends_on": d.employment_ends_on,
|
||||||
|
"supervisor_id": d.supervisor_id,
|
||||||
|
}
|
||||||
|
|
||||||
|
def get_form_kwargs(self) -> dict[str, Any]:
|
||||||
|
kwargs = super().get_form_kwargs()
|
||||||
|
kwargs["supervisors"] = container.user_queries().supervisor_choices(
|
||||||
|
exclude_id=self.kwargs["pk"]
|
||||||
|
)
|
||||||
|
kwargs["is_new"] = False
|
||||||
|
return kwargs
|
||||||
|
|
||||||
|
def get_context_data(self, **kwargs: Any) -> dict[str, Any]:
|
||||||
|
context = super().get_context_data(**kwargs)
|
||||||
|
context["user_id"] = self.kwargs["pk"]
|
||||||
|
context["user_name"] = self.details.name if self.details else ""
|
||||||
|
return context
|
||||||
|
|
||||||
|
def form_valid(self, form: UserForm) -> HttpResponse:
|
||||||
|
try:
|
||||||
|
container.update_user().execute(self.kwargs["pk"], form.to_dto())
|
||||||
|
except DomainError as error:
|
||||||
|
form.add_domain_error(error, ERROR_MESSAGES)
|
||||||
|
return self.form_invalid(form)
|
||||||
|
messages.success(self.request, _("Changes saved."))
|
||||||
|
return redirect("users:list")
|
||||||
|
|
||||||
|
def form_invalid(self, form: UserForm) -> HttpResponse:
|
||||||
|
return self.render_to_response(self.get_context_data(form=form), status=422)
|
||||||
|
|
||||||
|
|
||||||
|
class PasswordLinkView(PermissionRequiredMixin, View):
|
||||||
|
"""Creates a new 72 h link for a user and shows it for copying (POST only)."""
|
||||||
|
|
||||||
|
permission = Permission.USERS_MANAGE
|
||||||
|
|
||||||
|
def post(self, request: HttpRequest, pk: int) -> HttpResponse:
|
||||||
|
try:
|
||||||
|
link = container.issue_password_link().execute(pk)
|
||||||
|
except DomainError:
|
||||||
|
raise Http404 from None
|
||||||
|
user = container.user_queries().get_summary(pk)
|
||||||
|
context = {"link": link, "user_summary": user}
|
||||||
|
if getattr(request, "htmx", False):
|
||||||
|
return render(request, "users/partials/password_link.html", context)
|
||||||
|
return render(request, "users/password_link_page.html", context)
|
||||||
@@ -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
|
||||||
+1
-1
@@ -11,6 +11,6 @@ import os
|
|||||||
|
|
||||||
from django.core.asgi import get_asgi_application
|
from django.core.asgi import get_asgi_application
|
||||||
|
|
||||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
|
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
|
||||||
|
|
||||||
application = get_asgi_application()
|
application = get_asgi_application()
|
||||||
|
|||||||
+105
-43
@@ -37,58 +37,76 @@ ALLOWED_HOSTS = [h.strip() for h in os.getenv("DJANGO_ALLOWED_HOSTS", "").split(
|
|||||||
# Application definition
|
# Application definition
|
||||||
|
|
||||||
INSTALLED_APPS = [
|
INSTALLED_APPS = [
|
||||||
'django.contrib.admin',
|
"django.contrib.auth",
|
||||||
'django.contrib.auth',
|
"django.contrib.contenttypes",
|
||||||
'django.contrib.contenttypes',
|
"django.contrib.sessions",
|
||||||
'django.contrib.sessions',
|
"django.contrib.messages",
|
||||||
'django.contrib.messages',
|
"django.contrib.staticfiles",
|
||||||
'django.contrib.staticfiles',
|
"django.forms",
|
||||||
|
"django_htmx",
|
||||||
|
"apps.shared",
|
||||||
|
"apps.users",
|
||||||
]
|
]
|
||||||
|
|
||||||
MIDDLEWARE = [
|
MIDDLEWARE = [
|
||||||
'django.middleware.security.SecurityMiddleware',
|
"django.middleware.security.SecurityMiddleware",
|
||||||
'django.contrib.sessions.middleware.SessionMiddleware',
|
"django.contrib.sessions.middleware.SessionMiddleware",
|
||||||
'django.middleware.common.CommonMiddleware',
|
"django.middleware.locale.LocaleMiddleware",
|
||||||
'django.middleware.csrf.CsrfViewMiddleware',
|
"django.middleware.common.CommonMiddleware",
|
||||||
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
"django.middleware.csrf.CsrfViewMiddleware",
|
||||||
'django.contrib.messages.middleware.MessageMiddleware',
|
"django.contrib.auth.middleware.AuthenticationMiddleware",
|
||||||
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
"django.contrib.auth.middleware.LoginRequiredMiddleware",
|
||||||
|
"apps.users.presentation.middleware.EnsureAccountIsUsable",
|
||||||
|
"django_htmx.middleware.HtmxMiddleware",
|
||||||
|
"django.contrib.messages.middleware.MessageMiddleware",
|
||||||
|
"django.middleware.clickjacking.XFrameOptionsMiddleware",
|
||||||
]
|
]
|
||||||
|
|
||||||
ROOT_URLCONF = 'config.urls'
|
ROOT_URLCONF = "config.urls"
|
||||||
|
|
||||||
TEMPLATES = [
|
TEMPLATES = [
|
||||||
{
|
{
|
||||||
'BACKEND': 'django.template.backends.django.DjangoTemplates',
|
"BACKEND": "django.template.backends.django.DjangoTemplates",
|
||||||
'DIRS': [BASE_DIR / 'templates'],
|
# Project templates + each module's presentation/templates.
|
||||||
'APP_DIRS': True,
|
"DIRS": [
|
||||||
'OPTIONS': {
|
BASE_DIR / "templates",
|
||||||
'context_processors': [
|
*sorted((BASE_DIR / "apps").glob("*/presentation/templates")),
|
||||||
'django.template.context_processors.request',
|
|
||||||
'django.contrib.auth.context_processors.auth',
|
|
||||||
'django.contrib.messages.context_processors.messages',
|
|
||||||
],
|
],
|
||||||
|
"APP_DIRS": True,
|
||||||
|
"OPTIONS": {
|
||||||
|
"context_processors": [
|
||||||
|
"django.template.context_processors.request",
|
||||||
|
"django.contrib.auth.context_processors.auth",
|
||||||
|
"django.contrib.messages.context_processors.messages",
|
||||||
|
],
|
||||||
|
"builtins": ["django.templatetags.i18n"],
|
||||||
|
# Module template tags live in <module>/presentation/templatetags.
|
||||||
|
"libraries": {
|
||||||
|
"users_tags": "apps.users.presentation.templatetags.users_tags",
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
|
|
||||||
WSGI_APPLICATION = 'config.wsgi.application'
|
WSGI_APPLICATION = "config.wsgi.application"
|
||||||
|
|
||||||
|
FORM_RENDERER = "apps.shared.presentation.forms.DaisyFormRenderer"
|
||||||
|
|
||||||
|
|
||||||
# Database
|
# Database
|
||||||
# https://docs.djangoproject.com/en/5.2/ref/settings/#databases
|
# https://docs.djangoproject.com/en/5.2/ref/settings/#databases
|
||||||
|
|
||||||
DATABASES = {
|
DATABASES = {
|
||||||
'default': {
|
"default": {
|
||||||
'ENGINE': 'django.db.backends.mysql',
|
"ENGINE": "django.db.backends.mysql",
|
||||||
'NAME': os.getenv('DB_NAME', 'django-toiminnanohjaus'),
|
"NAME": os.getenv("DB_NAME", "django-toiminnanohjaus"),
|
||||||
'USER': os.getenv('DB_USER', 'root'),
|
"USER": os.getenv("DB_USER", "root"),
|
||||||
'PASSWORD': os.getenv('DB_PASSWORD', ''),
|
"PASSWORD": os.getenv("DB_PASSWORD", ""),
|
||||||
'HOST': os.getenv('DB_HOST', '127.0.0.1'),
|
"HOST": os.getenv("DB_HOST", "127.0.0.1"),
|
||||||
'PORT': os.getenv('DB_PORT', '3306'),
|
"PORT": os.getenv("DB_PORT", "3306"),
|
||||||
'OPTIONS': {
|
"OPTIONS": {
|
||||||
'charset': 'utf8mb4',
|
"charset": "utf8mb4",
|
||||||
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
|
"init_command": "SET sql_mode='STRICT_TRANS_TABLES'",
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -99,16 +117,16 @@ DATABASES = {
|
|||||||
|
|
||||||
AUTH_PASSWORD_VALIDATORS = [
|
AUTH_PASSWORD_VALIDATORS = [
|
||||||
{
|
{
|
||||||
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
|
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
|
"NAME": "apps.users.infrastructure.password.ComplexityValidator",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
|
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
|
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -116,23 +134,67 @@ AUTH_PASSWORD_VALIDATORS = [
|
|||||||
# Internationalization
|
# Internationalization
|
||||||
# https://docs.djangoproject.com/en/5.2/topics/i18n/
|
# https://docs.djangoproject.com/en/5.2/topics/i18n/
|
||||||
|
|
||||||
LANGUAGE_CODE = 'fi'
|
LANGUAGE_CODE = "fi"
|
||||||
|
|
||||||
TIME_ZONE = 'Europe/Helsinki'
|
TIME_ZONE = "Europe/Helsinki"
|
||||||
|
|
||||||
USE_I18N = True
|
USE_I18N = True
|
||||||
|
|
||||||
|
LANGUAGES = [("fi", "Suomi")]
|
||||||
|
LOCALE_PATHS = [BASE_DIR / "locale"]
|
||||||
|
|
||||||
|
# Business day boundaries (intern end dates, cash days) are computed in this zone.
|
||||||
|
BUSINESS_TIME_ZONE = "Europe/Helsinki"
|
||||||
|
|
||||||
USE_TZ = True
|
USE_TZ = True
|
||||||
|
|
||||||
|
|
||||||
# Static files (CSS, JavaScript, Images)
|
# Static files (CSS, JavaScript, Images)
|
||||||
# https://docs.djangoproject.com/en/5.2/howto/static-files/
|
# https://docs.djangoproject.com/en/5.2/howto/static-files/
|
||||||
|
|
||||||
STATIC_URL = 'static/'
|
STATIC_URL = "static/"
|
||||||
STATICFILES_DIRS = [BASE_DIR / 'static']
|
STATICFILES_DIRS = [BASE_DIR / "static"]
|
||||||
STATIC_ROOT = BASE_DIR / 'staticfiles'
|
STATIC_ROOT = BASE_DIR / "staticfiles"
|
||||||
|
|
||||||
# Default primary key field type
|
# Default primary key field type
|
||||||
# https://docs.djangoproject.com/en/5.2/ref/settings/#default-auto-field
|
# https://docs.djangoproject.com/en/5.2/ref/settings/#default-auto-field
|
||||||
|
|
||||||
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
|
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
|
||||||
|
|
||||||
|
|
||||||
|
# Authentication (docs/architecture.md, luku 14)
|
||||||
|
AUTH_USER_MODEL = "users.User"
|
||||||
|
AUTHENTICATION_BACKENDS = ["apps.users.infrastructure.auth.EmailBackend"]
|
||||||
|
LOGIN_URL = "users:login"
|
||||||
|
LOGIN_REDIRECT_URL = "home"
|
||||||
|
LOGOUT_REDIRECT_URL = "users:login"
|
||||||
|
PASSWORD_LINK_SETUP_TIMEOUT = 72 * 60 * 60 # link created by an admin
|
||||||
|
PASSWORD_RESET_TIMEOUT = 60 * 60 # "forgot password" link
|
||||||
|
SESSION_COOKIE_AGE = 14 * 24 * 60 * 60 # "remember me"
|
||||||
|
|
||||||
|
# Login throttling uses the cache, so it must be shared between processes.
|
||||||
|
CACHES = {
|
||||||
|
"default": {
|
||||||
|
"BACKEND": "django.core.cache.backends.db.DatabaseCache",
|
||||||
|
"LOCATION": "django_cache",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Email
|
||||||
|
EMAIL_BACKEND = os.getenv("EMAIL_BACKEND", "django.core.mail.backends.console.EmailBackend")
|
||||||
|
EMAIL_HOST = os.getenv("EMAIL_HOST", "localhost")
|
||||||
|
EMAIL_PORT = int(os.getenv("EMAIL_PORT", "25"))
|
||||||
|
EMAIL_HOST_USER = os.getenv("EMAIL_HOST_USER", "")
|
||||||
|
EMAIL_HOST_PASSWORD = os.getenv("EMAIL_HOST_PASSWORD", "")
|
||||||
|
EMAIL_USE_TLS = os.getenv("EMAIL_USE_TLS", "False").lower() in ("1", "true", "yes")
|
||||||
|
DEFAULT_FROM_EMAIL = os.getenv("DEFAULT_FROM_EMAIL", "toiminnanohjaus@localhost")
|
||||||
|
|
||||||
|
# Absolute base URL for links in emails.
|
||||||
|
SITE_URL = os.getenv("SITE_URL", "http://127.0.0.1:8000")
|
||||||
|
|
||||||
|
LOGGING = {
|
||||||
|
"version": 1,
|
||||||
|
"disable_existing_loggers": False,
|
||||||
|
"handlers": {"console": {"class": "logging.StreamHandler"}},
|
||||||
|
"root": {"handlers": ["console"], "level": "WARNING"},
|
||||||
|
}
|
||||||
|
|||||||
+4
-18
@@ -1,22 +1,8 @@
|
|||||||
"""
|
from django.urls import include, path
|
||||||
URL configuration for config project.
|
|
||||||
|
|
||||||
The `urlpatterns` list routes URLs to views. For more information please see:
|
from apps.shared.presentation.views import home
|
||||||
https://docs.djangoproject.com/en/5.2/topics/http/urls/
|
|
||||||
Examples:
|
|
||||||
Function views
|
|
||||||
1. Add an import: from my_app import views
|
|
||||||
2. Add a URL to urlpatterns: path('', views.home, name='home')
|
|
||||||
Class-based views
|
|
||||||
1. Add an import: from other_app.views import Home
|
|
||||||
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
|
|
||||||
Including another URLconf
|
|
||||||
1. Import the include() function: from django.urls import include, path
|
|
||||||
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
|
|
||||||
"""
|
|
||||||
from django.contrib import admin
|
|
||||||
from django.urls import path
|
|
||||||
|
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
path('admin/', admin.site.urls),
|
path("", home, name="home"),
|
||||||
|
path("", include("apps.users.presentation.urls")),
|
||||||
]
|
]
|
||||||
|
|||||||
+1
-1
@@ -11,6 +11,6 @@ import os
|
|||||||
|
|
||||||
from django.core.wsgi import get_wsgi_application
|
from django.core.wsgi import get_wsgi_application
|
||||||
|
|
||||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
|
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
|
||||||
|
|
||||||
application = get_wsgi_application()
|
application = get_wsgi_application()
|
||||||
|
|||||||
+13
-9
@@ -31,9 +31,10 @@ apps/
|
|||||||
│ │ ├── events.py # DjangoEventPublisher (on_commit), kuuntelijarekisteri
|
│ │ ├── events.py # DjangoEventPublisher (on_commit), kuuntelijarekisteri
|
||||||
│ │ └── models.py # abstrakti TimestampedModel
|
│ │ └── models.py # abstrakti TimestampedModel
|
||||||
│ └── presentation/
|
│ └── presentation/
|
||||||
│ ├── templates/ # base.html, layout, daisyUI-komponenttien osapohjat (components/)
|
│ ├── forms.py # DaisyFormRenderer, DaisyFormMixin (daisyUI-luokat, ARIA, domain-virheet)
|
||||||
│ └── templatetags/
|
│ └── views.py
|
||||||
├── users/ # käyttäjät, roolit, kirjautuminen (ks. luku 14)
|
├── users/ # käyttäjät, roolit, kirjautuminen (ks. luku 14) – ensimmäinen valmis moduuli
|
||||||
|
│ └── presentation/templatetags/users_tags.py # {% load users_tags %}: can, role_label
|
||||||
└── customers/
|
└── customers/
|
||||||
├── domain/
|
├── domain/
|
||||||
│ ├── entities.py # Customer (dataclass)
|
│ ├── entities.py # Customer (dataclass)
|
||||||
@@ -60,11 +61,14 @@ apps/
|
|||||||
├── apps.py # CustomersConfig.ready(): tapahtumakuuntelijat
|
├── apps.py # CustomersConfig.ready(): tapahtumakuuntelijat
|
||||||
├── migrations/
|
├── migrations/
|
||||||
└── tests/ # domain/, application/, integration/
|
└── tests/ # domain/, application/, integration/
|
||||||
|
templates/ # yhteiset pohjat: base.html, layouts/auth.html, components/, 403/404
|
||||||
locale/fi/LC_MESSAGES/ # käännökset (django.po)
|
locale/fi/LC_MESSAGES/ # käännökset (django.po)
|
||||||
static/src/app.css # Tailwind + daisyUI -lähde → static/dist/app.css
|
static/src/app.css, app.js # Tailwind + daisyUI -lähde → static/dist/app.css; teema ja fokus
|
||||||
tests/browser/ # selaintestit (Playwright + axe)
|
tests/browser/ # selaintestit (Playwright + axe)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
- Moduulin templatet ovat `presentation/templates`-kansiossa. Ne lisätään `TEMPLATES['DIRS']`iin asetusten globilla, koska Django etsii appien templateja vain appin juuresta. Template-tagikirjastot rekisteröidään `TEMPLATES['OPTIONS']['libraries']`iin samasta syystä.
|
||||||
|
|
||||||
- Appin nimi on `apps.customers`, `label` = `customers`. Moduulit rekisteröidään `INSTALLED_APPS`iin.
|
- Appin nimi on `apps.customers`, `label` = `customers`. Moduulit rekisteröidään `INSTALLED_APPS`iin.
|
||||||
- Migraatiot ovat appin omassa `migrations/`-kansiossa (Djangon käytäntö). Taulujen nimet asetetaan `Meta.db_table`:llä määrittelyn (luku 14) mukaisiksi.
|
- Migraatiot ovat appin omassa `migrations/`-kansiossa (Djangon käytäntö). Taulujen nimet asetetaan `Meta.db_table`:llä määrittelyn (luku 14) mukaisiksi.
|
||||||
- Kansioita ja tiedostoja luodaan vain tarpeeseen. Pienessä moduulissa `use_cases.py` voi olla yksi tiedosto; se jaetaan paketiksi (`use_cases/`), kun se kasvaa.
|
- Kansioita ja tiedostoja luodaan vain tarpeeseen. Pienessä moduulissa `use_cases.py` voi olla yksi tiedosto; se jaetaan paketiksi (`use_cases/`), kun se kasvaa.
|
||||||
@@ -111,7 +115,7 @@ Käyttöliittymä: **Django-templatet, daisyUI 5 -komponentit, HTMX ja Alpine.js
|
|||||||
- JSON-rajapinta (esim. Fennoa) lisätään `presentation/api/`-kansioon vasta, kun sitä tarvitaan.
|
- JSON-rajapinta (esim. Fennoa) lisätään `presentation/api/`-kansioon vasta, kun sitä tarvitaan.
|
||||||
|
|
||||||
### Kokoamispiste: `container.py`
|
### Kokoamispiste: `container.py`
|
||||||
Moduulin ainoa paikka, joka tuntee sekä application- että infrastructure-luokat. Se tarjoaa tehdasfunktiot, esim. `register_customer() -> RegisterCustomer` ja `customer_queries() -> CustomerQueries`. Testit korvaavat riippuvuudet antamalla fake-toteutukset suoraan use casen konstruktorille.
|
Moduulin ainoa paikka, joka tuntee sekä application- että infrastructure-luokat. Se tarjoaa tehdasfunktiot, esim. `register_customer() -> RegisterCustomer` ja `customer_queries() -> CustomerQueries`. Testit korvaavat riippuvuudet antamalla fake-toteutukset suoraan use casen konstruktorille. Jos presentation tarvitsee infrastruktuurin palvelua (esim. salasanalinkin tokenin tarkistus), container tarjoaa sille funktion; import-linter estää presentationia importtaamasta infrastructurea suoraan.
|
||||||
|
|
||||||
## 4. Riippuvuussäännöt
|
## 4. Riippuvuussäännöt
|
||||||
|
|
||||||
@@ -191,7 +195,7 @@ Testityökalu on **pytest + pytest-django** (asetukset `pyproject.toml`:ssa).
|
|||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| Arkkitehtuuri | `lint-imports` | riippuvuussäännöt (luku 4) | ei |
|
| Arkkitehtuuri | `lint-imports` | riippuvuussäännöt (luku 4) | ei |
|
||||||
| Domain | `apps/<moduuli>/tests/domain` | entiteetit, value objectit, invarianssit | ei |
|
| Domain | `apps/<moduuli>/tests/domain` | entiteetit, value objectit, invarianssit | ei |
|
||||||
| Application | `apps/<moduuli>/tests/application` | use caset fakeilla (`tests/fakes.py`: `InMemoryCustomerRepository`, `FakeUnitOfWork`, `FakeEventPublisher`) | ei |
|
| Application | `apps/<moduuli>/tests/application` | use caset fakeilla (`apps/<moduuli>/tests/fakes.py`, esim. users: `InMemoryUserRepository`, `FakeUnitOfWork`, `FakePasswordLinkService`, `FixedClock`) | ei |
|
||||||
| Integraatio | `apps/<moduuli>/tests/integration` | repositoryt ja kyselyt oikeaa kantaa vasten, näkymät (Django test client, HTMX-otsakkeet), transaktiot ja tapahtumat | kyllä, `@pytest.mark.django_db` |
|
| Integraatio | `apps/<moduuli>/tests/integration` | repositoryt ja kyselyt oikeaa kantaa vasten, näkymät (Django test client, HTMX-otsakkeet), transaktiot ja tapahtumat | kyllä, `@pytest.mark.django_db` |
|
||||||
| Selain | `tests/browser` | saavutettavuus (axe-core, vaalea/tumma teema, työpöytä/mobiili), näppäimistökäyttö | kyllä, `pytest-playwright` + `live_server` |
|
| Selain | `tests/browser` | saavutettavuus (axe-core, vaalea/tumma teema, työpöytä/mobiili), näppäimistökäyttö | kyllä, `pytest-playwright` + `live_server` |
|
||||||
|
|
||||||
@@ -224,8 +228,8 @@ Esimerkki: vaiheen 1 `jobs` (asiakastyöt).
|
|||||||
## 12. Käyttöliittymä: daisyUI, HTMX ja Alpine.js
|
## 12. Käyttöliittymä: daisyUI, HTMX ja Alpine.js
|
||||||
|
|
||||||
- **Tyylit:** Tailwind CSS 4 + daisyUI 5 rakennetaan npm:llä (`package.json`: `npm run dev` = watch, `npm run build` = minifioitu). Lähde `static/src/app.css` (`@import "tailwindcss"; @plugin "daisyui" { themes: light --default, dark --prefersdark; }`, `@source "../../apps/**/templates"`), tuloste `static/dist/app.css`, joka on versionhallinnan ulkopuolella ja rakennetaan julkaisussa. `collectstatic` kokoaa tiedostot `STATIC_ROOT`iin.
|
- **Tyylit:** Tailwind CSS 4 + daisyUI 5 rakennetaan npm:llä (`package.json`: `npm run dev` = watch, `npm run build` = minifioitu). Lähde `static/src/app.css` (`@import "tailwindcss"; @plugin "daisyui" { themes: light --default, dark --prefersdark; }`, `@source "../../apps/**/templates"`), tuloste `static/dist/app.css`, joka on versionhallinnan ulkopuolella ja rakennetaan julkaisussa. `collectstatic` kokoaa tiedostot `STATIC_ROOT`iin.
|
||||||
- **Komponentit:** käytetään daisyUI:n luokkia (`btn`, `card`, `table`, `input`, `select`, `checkbox`, `modal`, `dropdown`, `menu`, `drawer`, `navbar`, `tabs`, `badge`, `alert`, `toast`, `loading`). Toistuvat rakenteet (lomakekenttä otsikkoineen ja virheineen, vahvistusdialogi, ilmoitus, sivutus) ovat yhteisiä osapohjia `apps/shared/presentation/templates/components/` (`{% include … with … %}`; Djangon `{% partialdef %}` tulee vasta Django 6.0:ssa, tarvittaessa `django-template-partials`). Lomakekentät renderöidään omalla `FormRenderer`illä/kenttäpohjalla, jotta daisyUI-luokat ja ARIA-attribuutit tulevat kaikkiin lomakkeisiin samoin.
|
- **Komponentit:** käytetään daisyUI:n luokkia (`btn`, `card`, `table`, `input`, `select`, `checkbox`, `modal`, `dropdown`, `menu`, `drawer`, `navbar`, `tabs`, `badge`, `alert`, `toast`, `loading`). Toistuvat rakenteet (lomakekenttä otsikkoineen ja virheineen, vahvistusdialogi, ilmoitus, sivutus) ovat yhteisiä osapohjia projektin `templates/components/`-kansiossa (`{% include … with … %}`; Djangon `{% partialdef %}` tulee vasta Django 6.0:ssa, tarvittaessa `django-template-partials`). Lomakekentät renderöidään omalla `FormRenderer`illä/kenttäpohjalla, jotta daisyUI-luokat ja ARIA-attribuutit tulevat kaikkiin lomakkeisiin samoin.
|
||||||
- **Teemat:** daisyUI:n `light` ja `dark` (käyttäjän valinta tai `prefers-color-scheme`). Teemavärien kontrasti tarkistetaan (WCAG AA 4,5:1 tekstille); tarvittaessa projektille tehdään oma teema.
|
- **Teemat:** daisyUI:n `light` ja `dark` (käyttäjän valinta tai `prefers-color-scheme`). Daisyn oletusvärit eivät kaikkialla täytä WCAG AA -kontrastia: `static/src/app.css` korjaa soft-alertit ja -badget, `.menu-title`n sekä vaalean teeman error- ja success-värit (`@plugin "daisyui/theme"`). Tekstilinkeissä käytetään `link`-luokkaa, ei `link-primary`a. Selaintestien axe-tarkistus havaitsee regressiot.
|
||||||
- **HTMX** (`django-htmx`): lomakkeiden lähetys ja kenttätason tallennus (`hx-post`, `hx-trigger="change"`), haut ja suodattimet (`hx-get` + `hx-push-url`), Kanbanin tilanvaihto, viikkonäkymän solut, dialogien sisältö. CSRF-token lisätään kaikkiin HTMX-pyyntöihin (`hx-headers` body-elementissä). Ilmoitukset palautetaan `HX-Trigger`-otsakkeella tai out-of-band-swapilla (`hx-swap-oob`) toast-alueelle.
|
- **HTMX** (`django-htmx`): lomakkeiden lähetys ja kenttätason tallennus (`hx-post`, `hx-trigger="change"`), haut ja suodattimet (`hx-get` + `hx-push-url`), Kanbanin tilanvaihto, viikkonäkymän solut, dialogien sisältö. CSRF-token lisätään kaikkiin HTMX-pyyntöihin (`hx-headers` body-elementissä). Ilmoitukset palautetaan `HX-Trigger`-otsakkeella tai out-of-band-swapilla (`hx-swap-oob`) toast-alueelle.
|
||||||
- **Alpine.js:** vain paikallinen selaintila (dialogin avaus, valikot, laskettu summa ennen tallennusta, vedä ja pudota yhdessä SortableJS:n kanssa). Liiketoimintalogiikkaa ei kirjoiteta JavaScriptiin.
|
- **Alpine.js:** vain paikallinen selaintila (dialogin avaus, valikot, laskettu summa ennen tallennusta, vedä ja pudota yhdessä SortableJS:n kanssa). Liiketoimintalogiikkaa ei kirjoiteta JavaScriptiin.
|
||||||
- HTMX ja Alpine asennetaan npm:llä ja niputetaan staattisiksi tiedostoiksi; CDN:ää ei käytetä tuotannossa.
|
- HTMX ja Alpine asennetaan npm:llä ja niputetaan staattisiksi tiedostoiksi; CDN:ää ei käytetä tuotannossa.
|
||||||
@@ -244,7 +248,7 @@ WCAG 2.2 AA / EN 301 549 on hyväksymiskriteeri koko käyttöliittymälle. Perus
|
|||||||
|
|
||||||
## 14. Users-moduuli ja kirjautuminen
|
## 14. Users-moduuli ja kirjautuminen
|
||||||
|
|
||||||
- **Käyttäjämalli:** oma `User` (`AbstractBaseUser` + `PermissionsMixin`, tunnisteena sähköposti) asetetaan `AUTH_USER_MODEL = "users.User"` **ennen ensimmäistä migraatiota**. Se on users-moduulin infrastructure-malli; Djangon auth, admin ja vierasavaimet (`settings.AUTH_USER_MODEL`) viittaavat siihen.
|
- **Käyttäjämalli:** oma `User` (`AbstractBaseUser`, tunnisteena sähköposti, ei `PermissionsMixin`iä) on asetettu `AUTH_USER_MODEL = "users.User"`. Se on users-moduulin infrastructure-malli; Djangon auth ja vierasavaimet (`settings.AUTH_USER_MODEL`) viittaavat siihen. Django admin ei ole käytössä, jotta käyttäjiä muutetaan vain use casejen kautta eivätkä domain-säännöt ohitu.
|
||||||
- **Roolit** (`Role`): pääkäyttäjä, johto, työntekijä, harjoittelija ja alihankkija. Vain pääkäyttäjä hallitsee käyttäjiä (`users.manage`). Alihankkijat eivät käytä asiakasrekisteriä (`customers.use`). Oikeustarkistukset ovat users-moduulin funktioita (`can(user, "customers.use")`), joita näkymien mixinit ja templatet käyttävät.
|
- **Roolit** (`Role`): pääkäyttäjä, johto, työntekijä, harjoittelija ja alihankkija. Vain pääkäyttäjä hallitsee käyttäjiä (`users.manage`). Alihankkijat eivät käytä asiakasrekisteriä (`customers.use`). Oikeustarkistukset ovat users-moduulin funktioita (`can(user, "customers.use")`), joita näkymien mixinit ja templatet käyttävät.
|
||||||
- **`UserAccount`-entiteetti** on liiketoimintanäkymä käyttäjään. Harjoittelijalla on aina viimeinen päivä ja vastuuhenkilö (aktiivinen johto tai työntekijä); muilla rooleilla niitä ei ole. Viimeistä aktiivista pääkäyttäjää ei voi poistaa käytöstä eikä vaihtaa toiseen rooliin; tarkistus lukitsee pääkäyttäjärivit (`select_for_update`), joten samanaikaiset muutokset eivät ohita sitä. Aktiivisten harjoittelijoiden vastuuhenkilöä ei voi poistaa käytöstä eikä siirtää rooliin, joka ei voi toimia vastuuhenkilönä (`SupervisorHasInterns`). Tallennettu käyttäjä ladataan tarkistamatta sääntöjä (`reconstitute`), jotta virheellinen rivi ei kaada kirjautumista.
|
- **`UserAccount`-entiteetti** on liiketoimintanäkymä käyttäjään. Harjoittelijalla on aina viimeinen päivä ja vastuuhenkilö (aktiivinen johto tai työntekijä); muilla rooleilla niitä ei ole. Viimeistä aktiivista pääkäyttäjää ei voi poistaa käytöstä eikä vaihtaa toiseen rooliin; tarkistus lukitsee pääkäyttäjärivit (`select_for_update`), joten samanaikaiset muutokset eivät ohita sitä. Aktiivisten harjoittelijoiden vastuuhenkilöä ei voi poistaa käytöstä eikä siirtää rooliin, joka ei voi toimia vastuuhenkilönä (`SupervisorHasInterns`). Tallennettu käyttäjä ladataan tarkistamatta sääntöjä (`reconstitute`), jotta virheellinen rivi ei kaada kirjautumista.
|
||||||
- **Kirjautuminen:** Djangon `LoginView` omalla authentication-backendillä, joka tarkistaa `CheckLoginAllowed`-ehdon: käyttäjä on aktiivinen eikä harjoittelijan viimeinen päivä ole mennyt. Päivä lasketaan aikavyöhykkeessä `settings.BUSINESS_TIME_ZONE` (oletus `Europe/Helsinki`). Yrityksiä rajoitetaan sähköposti+IP-paria kohden (5 / 5 min, Djangon välimuistilla tai django-axesilla). Väärä salasana ja käytöstä poistettu tunnus saavat saman viestin.
|
- **Kirjautuminen:** Djangon `LoginView` omalla authentication-backendillä, joka tarkistaa `CheckLoginAllowed`-ehdon: käyttäjä on aktiivinen eikä harjoittelijan viimeinen päivä ole mennyt. Päivä lasketaan aikavyöhykkeessä `settings.BUSINESS_TIME_ZONE` (oletus `Europe/Helsinki`). Yrityksiä rajoitetaan sähköposti+IP-paria kohden (5 / 5 min, Djangon välimuistilla tai django-axesilla). Väärä salasana ja käytöstä poistettu tunnus saavat saman viestin.
|
||||||
|
|||||||
@@ -0,0 +1,499 @@
|
|||||||
|
# SOME DESCRIPTIVE TITLE.
|
||||||
|
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
|
||||||
|
# This file is distributed under the same license as the PACKAGE package.
|
||||||
|
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
|
||||||
|
#
|
||||||
|
#, fuzzy
|
||||||
|
msgid ""
|
||||||
|
msgstr ""
|
||||||
|
"Project-Id-Version: PACKAGE VERSION\n"
|
||||||
|
"Report-Msgid-Bugs-To: \n"
|
||||||
|
"POT-Creation-Date: 2026-11-29 12:10+0200\n"
|
||||||
|
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
|
||||||
|
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
|
||||||
|
"Language-Team: LANGUAGE <[email protected]>\n"
|
||||||
|
"Language: fi\n"
|
||||||
|
"MIME-Version: 1.0\n"
|
||||||
|
"Content-Type: text/plain; charset=UTF-8\n"
|
||||||
|
"Content-Transfer-Encoding: 8bit\n"
|
||||||
|
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
|
||||||
|
|
||||||
|
#: .\apps\users\infrastructure\password.py:15
|
||||||
|
#, python-format
|
||||||
|
msgid "The password must be at least %(min)d characters long."
|
||||||
|
msgstr "Salasanassa on oltava vähintään %(min)d merkkiä."
|
||||||
|
|
||||||
|
#: .\apps\users\infrastructure\password.py:21
|
||||||
|
msgid "The password must contain an upper case letter."
|
||||||
|
msgstr "Salasanassa on oltava iso kirjain."
|
||||||
|
|
||||||
|
#: .\apps\users\infrastructure\password.py:22
|
||||||
|
msgid "The password must contain a lower case letter."
|
||||||
|
msgstr "Salasanassa on oltava pieni kirjain."
|
||||||
|
|
||||||
|
#: .\apps\users\infrastructure\password.py:23
|
||||||
|
msgid "The password must contain a digit."
|
||||||
|
msgstr "Salasanassa on oltava numero."
|
||||||
|
|
||||||
|
#: .\apps\users\infrastructure\password.py:26
|
||||||
|
msgid "The password must contain a special character."
|
||||||
|
msgstr "Salasanassa on oltava erikoismerkki."
|
||||||
|
|
||||||
|
#: .\apps\users\infrastructure\password.py:36
|
||||||
|
#, python-format
|
||||||
|
msgid ""
|
||||||
|
"At least %(min)d characters, including upper and lower case letters, a digit "
|
||||||
|
"and a special character."
|
||||||
|
msgstr "Vähintään %(min)d merkkiä, joista on oltava iso ja pieni kirjain, numero ja erikoismerkki."
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\forms.py:22 .\apps\users\presentation\forms.py:52
|
||||||
|
#: .\apps\users\presentation\forms.py:66
|
||||||
|
#: .\apps\users\presentation\templates\users\partials\user_table.html:9
|
||||||
|
msgid "Email"
|
||||||
|
msgstr "Sähköposti"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\forms.py:25
|
||||||
|
msgid "Remember me"
|
||||||
|
msgstr "Muista minut"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\forms.py:29 .\apps\users\presentation\forms.py:30
|
||||||
|
msgid "The email address or password is incorrect."
|
||||||
|
msgstr "Sähköpostiosoite tai salasana on väärin."
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\forms.py:31
|
||||||
|
msgid "Too many login attempts. Try again in a few minutes."
|
||||||
|
msgstr "Liian monta kirjautumisyritystä. Yritä uudelleen muutaman minuutin kuluttua."
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\forms.py:65
|
||||||
|
#: .\apps\users\presentation\templates\users\partials\user_table.html:8
|
||||||
|
msgid "Name"
|
||||||
|
msgstr "Nimi"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\forms.py:67 .\apps\users\presentation\forms.py:110
|
||||||
|
#: .\apps\users\presentation\templates\users\partials\user_table.html:10
|
||||||
|
msgid "Role"
|
||||||
|
msgstr "Rooli"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\forms.py:68 .\apps\users\presentation\forms.py:115
|
||||||
|
#: .\apps\users\presentation\templates\users\partials\user_table.html:23
|
||||||
|
msgid "Active"
|
||||||
|
msgstr "Aktiivinen"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\forms.py:70
|
||||||
|
#: .\apps\users\presentation\templates\users\partials\user_table.html:12
|
||||||
|
msgid "Last day"
|
||||||
|
msgstr "Viimeinen päivä"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\forms.py:73
|
||||||
|
msgid "The intern cannot log in after this day."
|
||||||
|
msgstr "Harjoittelija ei voi kirjautua tämän päivän jälkeen."
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\forms.py:76
|
||||||
|
#: .\apps\users\presentation\templates\users\partials\user_table.html:13
|
||||||
|
msgid "Supervisor"
|
||||||
|
msgstr "Vastuuhenkilö"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\forms.py:87
|
||||||
|
msgid "Choose a supervisor"
|
||||||
|
msgstr "Valitse vastuuhenkilö"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\forms.py:108
|
||||||
|
msgid "Search"
|
||||||
|
msgstr "Haku"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\forms.py:110
|
||||||
|
msgid "All roles"
|
||||||
|
msgstr "Kaikki roolit"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\forms.py:113
|
||||||
|
#: .\apps\users\presentation\templates\users\partials\user_table.html:11
|
||||||
|
msgid "Status"
|
||||||
|
msgstr "Tila"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\forms.py:115
|
||||||
|
msgid "All"
|
||||||
|
msgstr "Kaikki"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\forms.py:115
|
||||||
|
#: .\apps\users\presentation\templates\users\partials\user_table.html:24
|
||||||
|
msgid "Inactive"
|
||||||
|
msgstr "Ei aktiivinen"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\labels.py:8
|
||||||
|
msgid "Admin"
|
||||||
|
msgstr "Pääkäyttäjä"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\labels.py:9
|
||||||
|
msgid "Management"
|
||||||
|
msgstr "Johto"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\labels.py:10
|
||||||
|
msgid "Employee"
|
||||||
|
msgstr "Työntekijä"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\labels.py:11
|
||||||
|
msgid "Intern"
|
||||||
|
msgstr "Harjoittelija"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\labels.py:12
|
||||||
|
msgid "Subcontractor"
|
||||||
|
msgstr "Alihankkija"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\labels.py:18
|
||||||
|
msgid "Enter a name (at most 150 characters)."
|
||||||
|
msgstr "Anna nimi (enintään 150 merkkiä)."
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\labels.py:19
|
||||||
|
msgid "Enter a valid email address."
|
||||||
|
msgstr "Anna kelvollinen sähköpostiosoite."
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\labels.py:20
|
||||||
|
msgid "A user with this email address already exists."
|
||||||
|
msgstr "Tällä sähköpostiosoitteella on jo käyttäjä."
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\labels.py:21
|
||||||
|
msgid "An intern must have an end date."
|
||||||
|
msgstr "Harjoittelijalla on oltava viimeinen päivä."
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\labels.py:22
|
||||||
|
msgid "An intern must have a supervisor."
|
||||||
|
msgstr "Harjoittelijalla on oltava vastuuhenkilö."
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\labels.py:23
|
||||||
|
msgid "The supervisor must be an active management or employee user."
|
||||||
|
msgstr "Vastuuhenkilön on oltava aktiivinen johdon jäsen tai työntekijä."
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\labels.py:25
|
||||||
|
msgid ""
|
||||||
|
"This is the last active admin. It cannot be deactivated or moved to another "
|
||||||
|
"role."
|
||||||
|
msgstr "Tämä on viimeinen aktiivinen pääkäyttäjä. Sitä ei voi poistaa käytöstä eikä siirtää toiseen rooliin."
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\labels.py:28
|
||||||
|
msgid "This user supervises active interns. Change their supervisor first."
|
||||||
|
msgstr "Käyttäjä on aktiivisten harjoittelijoiden vastuuhenkilö. Vaihda ensin heidän vastuuhenkilönsä."
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\labels.py:30
|
||||||
|
msgid "The user was not found."
|
||||||
|
msgstr "Käyttäjää ei löytynyt."
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\labels.py:31
|
||||||
|
msgid "The change could not be saved."
|
||||||
|
msgstr "Muutosta ei voitu tallentaa."
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\email\password_link.txt:1
|
||||||
|
#, python-format
|
||||||
|
msgid "Hello %(name)s,"
|
||||||
|
msgstr "Hei %(name)s,"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\email\password_link.txt:3
|
||||||
|
msgid "You asked for a link for setting a new password."
|
||||||
|
msgstr "Pyysit linkkiä uuden salasanan asettamiseen."
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\email\password_link.txt:3
|
||||||
|
msgid ""
|
||||||
|
"An account has been created or a new password link has been requested for "
|
||||||
|
"you."
|
||||||
|
msgstr "Sinulle on luotu käyttäjätunnus tai pyydetty uusi salasanalinkki."
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\email\password_link.txt:4
|
||||||
|
msgid "Set your password with this link:"
|
||||||
|
msgstr "Aseta salasanasi tällä linkillä:"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\email\password_link.txt:8
|
||||||
|
#, python-format
|
||||||
|
msgid "The link can be used once and it is valid until %(expires)s."
|
||||||
|
msgstr "Linkin voi käyttää kerran, ja se on voimassa %(expires)s asti."
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\email\password_link.txt:9
|
||||||
|
msgid "If you did not expect this message, you can ignore it."
|
||||||
|
msgstr "Jos et odottanut tätä viestiä, voit jättää sen huomiotta."
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\email\password_link_subject.txt:1
|
||||||
|
msgid "Set a new password"
|
||||||
|
msgstr "Aseta uusi salasana"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\email\password_link_subject.txt:1
|
||||||
|
msgid "Set your password"
|
||||||
|
msgstr "Aseta salasanasi"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\forgot_password.html:2
|
||||||
|
#: .\apps\users\presentation\templates\users\forgot_password.html:4
|
||||||
|
#: .\apps\users\presentation\templates\users\login.html:16
|
||||||
|
msgid "Forgot your password?"
|
||||||
|
msgstr "Unohtuiko salasana?"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\forgot_password.html:5
|
||||||
|
msgid ""
|
||||||
|
"Enter your email address. We will send you a link for setting a new password."
|
||||||
|
msgstr "Anna sähköpostiosoitteesi. Lähetämme sinulle linkin uuden salasanan asettamiseen."
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\forgot_password.html:9
|
||||||
|
msgid "Send link"
|
||||||
|
msgstr "Lähetä linkki"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\forgot_password.html:11
|
||||||
|
msgid "Back to login"
|
||||||
|
msgstr "Takaisin kirjautumiseen"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\form.html:2
|
||||||
|
#: .\apps\users\presentation\templates\users\form.html:8
|
||||||
|
#: .\apps\users\presentation\templates\users\password_link_page.html:9
|
||||||
|
msgid "Edit user"
|
||||||
|
msgstr "Muokkaa käyttäjää"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\form.html:2
|
||||||
|
#: .\apps\users\presentation\templates\users\form.html:6
|
||||||
|
#: .\apps\users\presentation\templates\users\form.html:8
|
||||||
|
#: .\apps\users\presentation\templates\users\list.html:6
|
||||||
|
msgid "New user"
|
||||||
|
msgstr "Uusi käyttäjä"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\form.html:4
|
||||||
|
msgid "Breadcrumbs"
|
||||||
|
msgstr "Murupolku"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\form.html:5
|
||||||
|
#: .\apps\users\presentation\templates\users\list.html:2
|
||||||
|
#: .\apps\users\presentation\templates\users\list.html:5
|
||||||
|
#: .\apps\users\presentation\templates\users\partials\user_table.html:5
|
||||||
|
#: .\templates\base.html:56
|
||||||
|
msgid "Users"
|
||||||
|
msgstr "Käyttäjät"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\form.html:20
|
||||||
|
msgid "An intern must have a last day and a supervisor."
|
||||||
|
msgstr "Harjoittelijalla on oltava viimeinen päivä ja vastuuhenkilö."
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\form.html:26
|
||||||
|
#: .\templates\components\confirm_dialog.html:8
|
||||||
|
msgid "Cancel"
|
||||||
|
msgstr "Peruuta"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\form.html:27
|
||||||
|
msgid "Save"
|
||||||
|
msgstr "Tallenna"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\form.html:35
|
||||||
|
#: .\apps\users\presentation\templates\users\password_link_page.html:2
|
||||||
|
msgid "Password link"
|
||||||
|
msgstr "Salasanalinkki"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\form.html:36
|
||||||
|
msgid ""
|
||||||
|
"Creates a new link for setting the password. The link is emailed to the user "
|
||||||
|
"and shown here for copying. Earlier links stop working."
|
||||||
|
msgstr "Luo uuden linkin salasanan asettamiseen. Linkki lähetetään käyttäjälle sähköpostilla ja näytetään tässä kopioitavaksi. Aiemmat linkit lakkaavat toimimasta."
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\form.html:37
|
||||||
|
msgid "Create password link"
|
||||||
|
msgstr "Luo salasanalinkki"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\form.html:42
|
||||||
|
msgid "Create a new password link?"
|
||||||
|
msgstr "Luodaanko uusi salasanalinkki?"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\form.html:43
|
||||||
|
msgid "Earlier links of this user stop working."
|
||||||
|
msgstr "Käyttäjän aiemmat linkit lakkaavat toimimasta."
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\form.html:44
|
||||||
|
msgid "Create link"
|
||||||
|
msgstr "Luo linkki"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\list.html:9
|
||||||
|
msgid "Filter users"
|
||||||
|
msgstr "Suodata käyttäjiä"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\list.html:17
|
||||||
|
msgid "Filter"
|
||||||
|
msgstr "Suodata"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\login.html:2
|
||||||
|
#: .\apps\users\presentation\templates\users\login.html:4
|
||||||
|
#: .\apps\users\presentation\templates\users\login.html:14
|
||||||
|
msgid "Log in"
|
||||||
|
msgstr "Kirjaudu"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\login.html:7
|
||||||
|
msgid ""
|
||||||
|
"Your access has ended: the account has been deactivated or the internship "
|
||||||
|
"has ended. Contact the admin if you think this is a mistake."
|
||||||
|
msgstr "Käyttöoikeutesi on päättynyt: tunnus on poistettu käytöstä tai harjoittelu on päättynyt. Ota yhteyttä pääkäyttäjään, jos tämä on mielestäsi virhe."
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\partials\password_link.html:4
|
||||||
|
#, python-format
|
||||||
|
msgid "The link has been emailed to %(email)s."
|
||||||
|
msgstr "Linkki on lähetetty osoitteeseen %(email)s."
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\partials\password_link.html:6
|
||||||
|
msgid "Sending the email failed."
|
||||||
|
msgstr "Sähköpostin lähetys epäonnistui."
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\partials\password_link.html:7
|
||||||
|
msgid "Deliver the link to the user in another way."
|
||||||
|
msgstr "Toimita linkki käyttäjälle muuta kautta."
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\partials\password_link.html:9
|
||||||
|
#, python-format
|
||||||
|
msgid "Valid until %(expires)s."
|
||||||
|
msgstr "Voimassa %(expires)s asti."
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\partials\password_link.html:11
|
||||||
|
msgid "Link"
|
||||||
|
msgstr "Linkki"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\partials\password_link.html:15
|
||||||
|
#: .\apps\users\presentation\templates\users\partials\password_link.html:19
|
||||||
|
msgid "Link copied"
|
||||||
|
msgstr "Linkki kopioitu"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\partials\password_link.html:16
|
||||||
|
msgid "Copy"
|
||||||
|
msgstr "Kopioi"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\partials\user_table.html:2
|
||||||
|
#, python-format
|
||||||
|
msgid "%(counter)s user found"
|
||||||
|
msgid_plural "%(counter)s users found"
|
||||||
|
msgstr[0] "%(counter)s käyttäjä löytyi"
|
||||||
|
msgstr[1] "%(counter)s käyttäjää löytyi"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\partials\user_table.html:30
|
||||||
|
msgid "No users match the filters."
|
||||||
|
msgstr "Hakuehtoja vastaavia käyttäjiä ei löytynyt."
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\partials\user_table.html:36
|
||||||
|
msgid "Pages"
|
||||||
|
msgstr "Sivut"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\partials\user_table.html:39
|
||||||
|
msgid "Previous"
|
||||||
|
msgstr "Edellinen"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\partials\user_table.html:41
|
||||||
|
#, python-format
|
||||||
|
msgid "Page %(n)s / %(total)s"
|
||||||
|
msgstr "Sivu %(n)s / %(total)s"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\partials\user_table.html:44
|
||||||
|
msgid "Next"
|
||||||
|
msgstr "Seuraava"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\password_link_page.html:4
|
||||||
|
#, python-format
|
||||||
|
msgid "Password link for %(name)s"
|
||||||
|
msgstr "Salasanalinkki: %(name)s"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\password_link_page.html:10
|
||||||
|
msgid "Back to users"
|
||||||
|
msgstr "Takaisin käyttäjiin"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\set_password.html:2
|
||||||
|
#: .\apps\users\presentation\templates\users\set_password.html:4
|
||||||
|
#: .\apps\users\presentation\templates\users\set_password.html:8
|
||||||
|
msgid "Set password"
|
||||||
|
msgstr "Aseta salasana"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\set_password_invalid.html:2
|
||||||
|
#: .\apps\users\presentation\templates\users\set_password_invalid.html:4
|
||||||
|
msgid "The link is not valid"
|
||||||
|
msgstr "Linkki ei ole voimassa"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\set_password_invalid.html:5
|
||||||
|
msgid ""
|
||||||
|
"The link has expired, it has already been used, or a newer link has been "
|
||||||
|
"created. Request a new link or ask the admin to create one."
|
||||||
|
msgstr "Linkki on vanhentunut, sitä on jo käytetty tai sen jälkeen on luotu uusi linkki. Tilaa uusi linkki tai pyydä pääkäyttäjää luomaan se."
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\templates\users\set_password_invalid.html:6
|
||||||
|
msgid "Request a new link"
|
||||||
|
msgstr "Tilaa uusi linkki"
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\views.py:58
|
||||||
|
msgid ""
|
||||||
|
"If the address belongs to a user who may log in, a link for setting the "
|
||||||
|
"password has been sent to it. The link is valid for 60 minutes."
|
||||||
|
msgstr "Jos osoite kuuluu käyttäjälle, joka saa kirjautua, siihen on lähetetty linkki salasanan asettamiseen. Linkki on voimassa 60 minuuttia."
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\views.py:95
|
||||||
|
msgid "Your password has been set. You can now log in."
|
||||||
|
msgstr "Salasana on asetettu. Voit nyt kirjautua."
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\views.py:144
|
||||||
|
msgid "User created."
|
||||||
|
msgstr "Käyttäjä luotu."
|
||||||
|
|
||||||
|
#: .\apps\users\presentation\views.py:196
|
||||||
|
msgid "Changes saved."
|
||||||
|
msgstr "Muutokset tallennettu."
|
||||||
|
|
||||||
|
#: .\templates\403.html:2 .\templates\403.html:4
|
||||||
|
msgid "Access denied"
|
||||||
|
msgstr "Ei käyttöoikeutta"
|
||||||
|
|
||||||
|
#: .\templates\403.html:5
|
||||||
|
msgid "You do not have permission to view this page."
|
||||||
|
msgstr "Sinulla ei ole oikeutta tähän sivuun."
|
||||||
|
|
||||||
|
#: .\templates\403.html:6 .\templates\404.html:6
|
||||||
|
msgid "Back to home"
|
||||||
|
msgstr "Takaisin etusivulle"
|
||||||
|
|
||||||
|
#: .\templates\404.html:2 .\templates\404.html:4
|
||||||
|
msgid "Page not found"
|
||||||
|
msgstr "Sivua ei löydy"
|
||||||
|
|
||||||
|
#: .\templates\404.html:5
|
||||||
|
msgid "The page you requested does not exist."
|
||||||
|
msgstr "Pyytämääsi sivua ei ole olemassa."
|
||||||
|
|
||||||
|
#: .\templates\base.html:20
|
||||||
|
msgid "Skip to content"
|
||||||
|
msgstr "Siirry sisältöön"
|
||||||
|
|
||||||
|
#: .\templates\base.html:23
|
||||||
|
msgid "Show menu"
|
||||||
|
msgstr "Näytä valikko"
|
||||||
|
|
||||||
|
#: .\templates\base.html:26
|
||||||
|
msgid "Open menu"
|
||||||
|
msgstr "Avaa valikko"
|
||||||
|
|
||||||
|
#: .\templates\base.html:38
|
||||||
|
msgid "Log out"
|
||||||
|
msgstr "Kirjaudu ulos"
|
||||||
|
|
||||||
|
#: .\templates\base.html:50
|
||||||
|
msgid "Close menu"
|
||||||
|
msgstr "Sulje valikko"
|
||||||
|
|
||||||
|
#: .\templates\base.html:51
|
||||||
|
msgid "Main menu"
|
||||||
|
msgstr "Päävalikko"
|
||||||
|
|
||||||
|
#: .\templates\base.html:53 .\templates\home.html:2
|
||||||
|
msgid "Home"
|
||||||
|
msgstr "Etusivu"
|
||||||
|
|
||||||
|
#: .\templates\base.html:55
|
||||||
|
msgid "Administration"
|
||||||
|
msgstr "Hallinto"
|
||||||
|
|
||||||
|
#: .\templates\components\field.html:10
|
||||||
|
msgid "(required)"
|
||||||
|
msgstr "(pakollinen)"
|
||||||
|
|
||||||
|
#: .\templates\components\theme_toggle.html:5
|
||||||
|
msgid "Dark theme"
|
||||||
|
msgstr "Tumma teema"
|
||||||
|
|
||||||
|
#: .\templates\home.html:4
|
||||||
|
#, python-format
|
||||||
|
msgid "Welcome, %(name)s"
|
||||||
|
msgstr "Tervetuloa, %(name)s"
|
||||||
|
|
||||||
|
#: .\templates\home.html:5
|
||||||
|
msgid "The dashboard will be built in a later step."
|
||||||
|
|
||||||
|
msgstr "Työpöytä rakennetaan myöhemmässä vaiheessa."
|
||||||
@@ -1,12 +1,13 @@
|
|||||||
#!/usr/bin/env python
|
#!/usr/bin/env python
|
||||||
"""Django's command-line utility for administrative tasks."""
|
"""Django's command-line utility for administrative tasks."""
|
||||||
|
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
"""Run administrative tasks."""
|
"""Run administrative tasks."""
|
||||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
|
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
|
||||||
try:
|
try:
|
||||||
from django.core.management import execute_from_command_line
|
from django.core.management import execute_from_command_line
|
||||||
except ImportError as exc:
|
except ImportError as exc:
|
||||||
@@ -18,5 +19,5 @@ def main():
|
|||||||
execute_from_command_line(sys.argv)
|
execute_from_command_line(sys.argv)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
|
|||||||
Generated
+1654
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"name": "toiminnanohjaus",
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"build:css": "tailwindcss -i static/src/app.css -o static/dist/app.css --minify",
|
||||||
|
"dev:css": "tailwindcss -i static/src/app.css -o static/dist/app.css --watch",
|
||||||
|
"vendor": "node scripts/copy-vendor.mjs",
|
||||||
|
"build": "npm run vendor && npm run build:css",
|
||||||
|
"dev": "npm run vendor && npm run dev:css"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@tailwindcss/cli": "^4.3.5",
|
||||||
|
"alpinejs": "^3.17.5",
|
||||||
|
"daisyui": "^5.8.3",
|
||||||
|
"htmx.org": "^2.0.11",
|
||||||
|
"tailwindcss": "^4.3.5"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
[project]
|
||||||
|
name = "toiminnanohjaus"
|
||||||
|
version = "0.1.0"
|
||||||
|
requires-python = ">=3.14"
|
||||||
|
|
||||||
|
[tool.pytest.ini_options]
|
||||||
|
DJANGO_SETTINGS_MODULE = "config.settings"
|
||||||
|
python_files = ["test_*.py"]
|
||||||
|
testpaths = ["apps"]
|
||||||
|
addopts = "-p no:cacheprovider --strict-markers"
|
||||||
|
markers = [
|
||||||
|
"browser: Playwright browser tests (run: pytest tests/browser -m browser)",
|
||||||
|
]
|
||||||
|
|
||||||
|
[tool.ruff]
|
||||||
|
line-length = 100
|
||||||
|
target-version = "py314"
|
||||||
|
extend-exclude = ["*/migrations/*", "node_modules", "static"]
|
||||||
|
|
||||||
|
[tool.ruff.lint]
|
||||||
|
select = ["E", "F", "W", "I", "UP", "B", "DJ", "SIM", "RUF"]
|
||||||
|
ignore = ["RUF001", "RUF002", "RUF003", "RUF012", "DJ008"]
|
||||||
|
|
||||||
|
[tool.mypy]
|
||||||
|
python_version = "3.14"
|
||||||
|
plugins = ["mypy_django_plugin.main"]
|
||||||
|
ignore_missing_imports = true
|
||||||
|
exclude = ["migrations/", "tests/"]
|
||||||
|
|
||||||
|
[[tool.mypy.overrides]]
|
||||||
|
module = ["apps.*.domain.*", "apps.*.application.*"]
|
||||||
|
strict = true
|
||||||
|
|
||||||
|
[tool.django-stubs]
|
||||||
|
django_settings_module = "config.settings"
|
||||||
|
|
||||||
|
[tool.importlinter]
|
||||||
|
root_package = "apps"
|
||||||
|
include_external_packages = true
|
||||||
|
|
||||||
|
[[tool.importlinter.contracts]]
|
||||||
|
name = "Domain and application layers do not depend on Django"
|
||||||
|
type = "forbidden"
|
||||||
|
source_modules = [
|
||||||
|
"apps.shared.domain",
|
||||||
|
"apps.shared.application",
|
||||||
|
"apps.users.domain",
|
||||||
|
"apps.users.application",
|
||||||
|
]
|
||||||
|
forbidden_modules = ["django"]
|
||||||
|
allow_indirect_imports = true
|
||||||
|
|
||||||
|
[[tool.importlinter.contracts]]
|
||||||
|
name = "users layers"
|
||||||
|
type = "layers"
|
||||||
|
layers = [
|
||||||
|
"apps.users.container",
|
||||||
|
"apps.users.presentation",
|
||||||
|
"apps.users.infrastructure",
|
||||||
|
"apps.users.application",
|
||||||
|
"apps.users.domain",
|
||||||
|
]
|
||||||
|
ignore_imports = [
|
||||||
|
# Composition root and presentation may both see the container.
|
||||||
|
"apps.users.presentation.** -> apps.users.container",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[tool.importlinter.contracts]]
|
||||||
|
name = "Presentation does not use infrastructure directly"
|
||||||
|
type = "forbidden"
|
||||||
|
source_modules = ["apps.users.presentation"]
|
||||||
|
forbidden_modules = ["apps.users.infrastructure"]
|
||||||
|
allow_indirect_imports = true
|
||||||
|
|
||||||
|
[[tool.importlinter.contracts]]
|
||||||
|
name = "shared layers"
|
||||||
|
type = "layers"
|
||||||
|
layers = [
|
||||||
|
"apps.shared.presentation",
|
||||||
|
"apps.shared.infrastructure",
|
||||||
|
"apps.shared.application",
|
||||||
|
"apps.shared.domain",
|
||||||
|
]
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
-r requirements.txt
|
||||||
|
pytest
|
||||||
|
pytest-django
|
||||||
|
factory-boy
|
||||||
|
ruff
|
||||||
|
mypy
|
||||||
|
django-stubs[compatible-mypy]
|
||||||
|
import-linter
|
||||||
|
pytest-playwright
|
||||||
|
axe-playwright-python
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
Django>=5.2,<5.3
|
Django>=5.2,<5.3
|
||||||
mysqlclient
|
mysqlclient
|
||||||
python-dotenv
|
python-dotenv
|
||||||
|
django-htmx
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
// Copies HTMX and Alpine.js builds from node_modules to static/dist.
|
||||||
|
import { copyFileSync, mkdirSync } from "node:fs";
|
||||||
|
|
||||||
|
const files = [
|
||||||
|
["node_modules/htmx.org/dist/htmx.min.js", "static/dist/htmx.min.js"],
|
||||||
|
["node_modules/alpinejs/dist/cdn.min.js", "static/dist/alpine.min.js"],
|
||||||
|
];
|
||||||
|
mkdirSync("static/dist", { recursive: true });
|
||||||
|
for (const [from, to] of files) {
|
||||||
|
copyFileSync(from, to);
|
||||||
|
console.log(`${from} -> ${to}`);
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
@import "tailwindcss";
|
||||||
|
@plugin "daisyui" {
|
||||||
|
themes: light --default, dark --prefersdark;
|
||||||
|
}
|
||||||
|
|
||||||
|
@source "../../apps";
|
||||||
|
@source "../../templates";
|
||||||
|
|
||||||
|
/* Visible focus for all interactive elements (WCAG 2.4.7 / 2.4.11). */
|
||||||
|
:focus-visible {
|
||||||
|
outline: 3px solid var(--color-primary);
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
[x-cloak] {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* WCAG AA: daisyUI soft variants colour their text with the variant colour,
|
||||||
|
which is too light on the tinted background. Keep the tint, use body text colour. */
|
||||||
|
.alert-soft,
|
||||||
|
.badge-soft {
|
||||||
|
color: var(--color-base-content);
|
||||||
|
}
|
||||||
|
|
||||||
|
.menu-title {
|
||||||
|
color: var(--color-base-content);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Status colours used as text must reach 4.5:1 on the light background. */
|
||||||
|
@plugin "daisyui/theme" {
|
||||||
|
name: "light";
|
||||||
|
default: true;
|
||||||
|
--color-error: oklch(50% 0.19 25);
|
||||||
|
--color-error-content: oklch(100% 0 0);
|
||||||
|
--color-success: oklch(48% 0.12 155);
|
||||||
|
--color-success-content: oklch(100% 0 0);
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
// Shared client behaviour: theme toggle and focus management after HTMX swaps.
|
||||||
|
(function () {
|
||||||
|
const THEME_KEY = "theme";
|
||||||
|
|
||||||
|
window.setTheme = function (theme) {
|
||||||
|
document.documentElement.setAttribute("data-theme", theme);
|
||||||
|
localStorage.setItem(THEME_KEY, theme);
|
||||||
|
};
|
||||||
|
|
||||||
|
document.addEventListener("htmx:afterSettle", function (event) {
|
||||||
|
const target = event.detail.target;
|
||||||
|
if (!target) return;
|
||||||
|
const focusable = target.querySelector("[data-autofocus]");
|
||||||
|
if (focusable) {
|
||||||
|
focusable.focus();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Announce HX-Trigger "notify" events in the live region and as a toast.
|
||||||
|
document.body.addEventListener("notify", function (event) {
|
||||||
|
window.notify(event.detail.value || event.detail.message || "");
|
||||||
|
});
|
||||||
|
|
||||||
|
window.notify = function (message) {
|
||||||
|
const live = document.getElementById("live-region");
|
||||||
|
if (live) {
|
||||||
|
live.textContent = "";
|
||||||
|
window.setTimeout(function () { live.textContent = message; }, 50);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
})();
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
{% extends "layouts/auth.html" %}{% load i18n %}
|
||||||
|
{% block title %}{% translate "Access denied" %}{% endblock %}
|
||||||
|
{% block content %}
|
||||||
|
<h1 class="card-title text-2xl">{% translate "Access denied" %}</h1>
|
||||||
|
<p>{% translate "You do not have permission to view this page." %}</p>
|
||||||
|
<a class="btn btn-primary mt-4" href="/">{% translate "Back to home" %}</a>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
{% extends "layouts/auth.html" %}{% load i18n %}
|
||||||
|
{% block title %}{% translate "Page not found" %}{% endblock %}
|
||||||
|
{% block content %}
|
||||||
|
<h1 class="card-title text-2xl">{% translate "Page not found" %}</h1>
|
||||||
|
<p>{% translate "The page you requested does not exist." %}</p>
|
||||||
|
<a class="btn btn-primary mt-4" href="/">{% translate "Back to home" %}</a>
|
||||||
|
{% endblock %}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user