Lege Einstellungen je Konto mit Erbung vom Hauptnutzer an und biete die Prüfstufe für doppelte Dokumente in Mein Konto an.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
bee48bf4a5
commit
a6dc24d8fe
11 files changed
+339
-1
No files matched your search
@@ -0,0 +1,41 @@
|
||||
"""Account preferences: read the effective value, change the own value, bind the team."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from fastapi.responses import JSONResponse
|
||||
from psycopg import Connection
|
||||
|
||||
from app.access.policy import audit
|
||||
from app.api.deps import Principal, get_conn, get_principal
|
||||
from app.api.schemas import PreferenceIn
|
||||
from app.preferences import preference_state, store_preference
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
_NO_STORE = {"Cache-Control": "no-store"}
|
||||
|
||||
|
||||
@router.get("/api/v1/auth/preferences/{key}")
|
||||
def get_preference(key: str, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
return JSONResponse(preference_state(conn, principal.account_id, key), headers=_NO_STORE)
|
||||
|
||||
|
||||
@router.put("/api/v1/auth/preferences/{key}")
|
||||
def put_preference(
|
||||
key: str,
|
||||
body: PreferenceIn,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
state = store_preference(conn, principal.account_id, key, body.value, body.team_mode)
|
||||
audit(
|
||||
conn,
|
||||
principal.account_id,
|
||||
None,
|
||||
"preference_changed",
|
||||
"account",
|
||||
principal.account_id,
|
||||
detail={"key": key, "value": body.value, "team_mode": body.team_mode},
|
||||
)
|
||||
return JSONResponse(state, headers=_NO_STORE)
|
||||
@@ -521,6 +521,13 @@ class DispatchCorrectIn(APIModel):
|
||||
clear_counterpart: bool = False
|
||||
|
||||
|
||||
class PreferenceIn(APIModel):
|
||||
"""`value` replaces the own value; null means: inherit. `team_mode` is for main users and stays as it is when absent."""
|
||||
|
||||
value: str | None = Field(default=None, max_length=40)
|
||||
team_mode: Literal["free", "locked"] | None = None
|
||||
|
||||
|
||||
class DownloadPolicyIn(APIModel):
|
||||
"""Who may save or open the original outside of Tsumugu. `direct` only applies to the account default."""
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ from app.api.correspondence import router as correspondence_router
|
||||
from app.api.downloads import router as downloads_router
|
||||
from app.api.export import router as export_router
|
||||
from app.api.library import router as library_router
|
||||
from app.api.preferences import router as preferences_router
|
||||
from app.api.rooms import router as rooms_router
|
||||
from app.api.roomshare import router as roomshare_router
|
||||
from app.api.team import router as team_router
|
||||
@@ -130,6 +131,7 @@ def create_app() -> FastAPI:
|
||||
app.include_router(sources_router)
|
||||
app.include_router(export_router)
|
||||
app.include_router(downloads_router)
|
||||
app.include_router(preferences_router)
|
||||
app.include_router(correspondence_router)
|
||||
return app
|
||||
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
"""Account preferences with inheritance.
|
||||
|
||||
An employee inherits the value of the main user who sponsors the account and may change it,
|
||||
unless the main user made the preference binding for the team. A binding value overrides an own
|
||||
value without deleting it: it applies again once the binding is lifted.
|
||||
Allowed values, default and lockability of each key are fixed here.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from uuid import UUID
|
||||
|
||||
from psycopg.types.json import Json
|
||||
|
||||
from app.core.errors import forbidden, not_found, unprocessable
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Preference:
|
||||
default: str
|
||||
allowed: tuple[str, ...]
|
||||
team_lockable: bool = True
|
||||
|
||||
|
||||
PREFERENCES: dict[str, Preference] = {
|
||||
# Where an element that is inserted again counts as already present.
|
||||
"duplicate_check": Preference("case", ("off", "case", "case_matters", "case_tree")),
|
||||
}
|
||||
|
||||
|
||||
def spec(key: str) -> Preference:
|
||||
found = PREFERENCES.get(key)
|
||||
if found is None:
|
||||
raise not_found()
|
||||
return found
|
||||
|
||||
|
||||
def _valid(wanted: Preference, value) -> str | None:
|
||||
return value if isinstance(value, str) and value in wanted.allowed else None
|
||||
|
||||
|
||||
def preference_state(conn, account_id: UUID, key: str) -> dict:
|
||||
"""The effective value and where it comes from: locked, own, team or default."""
|
||||
wanted = spec(key)
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT a.account_kind,
|
||||
own.value AS own_value, own.team_mode AS own_mode,
|
||||
sp.value AS team_value, sp.team_mode AS team_mode
|
||||
FROM auth_accounts a
|
||||
LEFT JOIN account_preferences own ON own.account_id = a.id AND own.key = %s
|
||||
LEFT JOIN account_preferences sp ON sp.account_id = a.sponsor_id AND sp.key = %s
|
||||
WHERE a.id = %s
|
||||
""",
|
||||
(key, key, account_id),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise not_found()
|
||||
employee = row["account_kind"] == "employee"
|
||||
own = _valid(wanted, row["own_value"])
|
||||
team = _valid(wanted, row["team_value"]) if employee else None
|
||||
locked = employee and wanted.team_lockable and row["team_mode"] == "locked"
|
||||
inherited = team or wanted.default
|
||||
if locked:
|
||||
value, source = inherited, "locked"
|
||||
elif own is not None:
|
||||
value, source = own, "own"
|
||||
elif team is not None:
|
||||
value, source = team, "team"
|
||||
else:
|
||||
value, source = wanted.default, "default"
|
||||
return {
|
||||
"key": key,
|
||||
"value": value,
|
||||
"source": source,
|
||||
"own": own,
|
||||
"inherited": inherited,
|
||||
"locked": locked,
|
||||
"allowed": list(wanted.allowed),
|
||||
"default": wanted.default,
|
||||
"can_lock": row["account_kind"] == "main" and wanted.team_lockable,
|
||||
"team_mode": row["own_mode"] if row["own_mode"] and not employee else "free",
|
||||
}
|
||||
|
||||
|
||||
def effective_preference(conn, account_id: UUID, key: str) -> str:
|
||||
return preference_state(conn, account_id, key)["value"]
|
||||
|
||||
|
||||
def store_preference(conn, account_id: UUID, key: str, value: str | None, team_mode: str | None) -> dict:
|
||||
"""Own value (None: inherit) and, for a main user, the binding for the team."""
|
||||
wanted = spec(key)
|
||||
state = preference_state(conn, account_id, key)
|
||||
if value is not None and value not in wanted.allowed:
|
||||
raise unprocessable("Dieser Wert ist für die Einstellung nicht vorgesehen.")
|
||||
if team_mode is not None and not state["can_lock"]:
|
||||
raise forbidden("Nur der Hauptnutzer kann eine Einstellung für das Team verbindlich setzen.")
|
||||
if state["locked"]:
|
||||
raise forbidden("Der Hauptnutzer hat diese Einstellung für das Team vorgegeben.")
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO account_preferences (account_id, key, value, team_mode)
|
||||
VALUES (%s, %s, %s, COALESCE(%s, 'free'))
|
||||
ON CONFLICT (account_id, key) DO UPDATE
|
||||
SET value = EXCLUDED.value,
|
||||
team_mode = COALESCE(%s, account_preferences.team_mode),
|
||||
updated_at = now()
|
||||
""",
|
||||
(account_id, key, Json(value) if value is not None else None, team_mode, team_mode),
|
||||
)
|
||||
return preference_state(conn, account_id, key)
|
||||
@@ -1082,4 +1082,5 @@ LABELS = {
|
||||
"room_default_changed": "Voreinstellung des Datenraums geändert",
|
||||
"room_download_policy_changed": "Download-Regel des Datenraums geändert",
|
||||
"download_defaults_changed": "Standard für Downloads geändert",
|
||||
"preference_changed": "Einstellung des Kontos geändert",
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
-- Einstellungen je Konto. Ein Mitarbeiter erbt den Wert seines Hauptnutzers und kann ihn ändern,
|
||||
-- solange der Hauptnutzer die Einstellung nicht für das Team verbindlich gesetzt hat (team_mode).
|
||||
-- Erlaubte Werte, Standard und Verbindlichkeit je Schlüssel stehen im Code (app/preferences.py).
|
||||
-- value NULL: kein eigener Wert, es gilt die Erbung bzw. der Standard.
|
||||
|
||||
CREATE TABLE account_preferences (
|
||||
account_id uuid NOT NULL REFERENCES auth_accounts (id) ON DELETE CASCADE,
|
||||
key text NOT NULL,
|
||||
value jsonb,
|
||||
team_mode text NOT NULL DEFAULT 'free',
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (account_id, key),
|
||||
CONSTRAINT account_preferences_key_len CHECK (char_length(key) BETWEEN 1 AND 60),
|
||||
CONSTRAINT account_preferences_team_mode CHECK (team_mode IN ('free', 'locked'))
|
||||
);
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Einstellungen je Konto: Erbung vom Hauptnutzer, eigener Wert, Verbindlichkeit für das Team."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.test_team import _invite, _main
|
||||
|
||||
PATH = "/api/v1/auth/preferences/duplicate_check"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def world(client, db):
|
||||
ada = _main(client, db, "ada", main=True)
|
||||
room = ada.request("POST", "/api/v1/rooms", json={"name": "Kanzlei"}, status=201)["id"]
|
||||
ada.use_room(room)
|
||||
emp = _invite(ada, room, "emp-pref@example.test", name="Eva")
|
||||
return {"ada": ada, "emp": emp}
|
||||
|
||||
|
||||
def test_the_default_applies_without_any_choice(world):
|
||||
for person in (world["ada"], world["emp"]):
|
||||
state = person.request("GET", PATH)
|
||||
assert (state["value"], state["source"]) == ("case", "default")
|
||||
assert world["ada"].request("GET", PATH)["can_lock"] is True
|
||||
assert world["emp"].request("GET", PATH)["can_lock"] is False
|
||||
|
||||
|
||||
def test_an_employee_inherits_the_main_user_and_may_override(world):
|
||||
ada, emp = world["ada"], world["emp"]
|
||||
ada.request("PUT", PATH, json={"value": "case_matters"})
|
||||
inherited = emp.request("GET", PATH)
|
||||
assert (inherited["value"], inherited["source"]) == ("case_matters", "team")
|
||||
|
||||
own = emp.request("PUT", PATH, json={"value": "off"})
|
||||
assert (own["value"], own["source"]) == ("off", "own")
|
||||
# The main user's change does not touch an own choice.
|
||||
ada.request("PUT", PATH, json={"value": "case_tree"})
|
||||
assert emp.request("GET", PATH)["value"] == "off"
|
||||
assert ada.request("GET", PATH)["value"] == "case_tree"
|
||||
|
||||
# Inheriting again.
|
||||
back = emp.request("PUT", PATH, json={"value": None})
|
||||
assert (back["value"], back["source"]) == ("case_tree", "team")
|
||||
|
||||
|
||||
def test_a_binding_overrides_an_own_value_without_deleting_it(world):
|
||||
ada, emp = world["ada"], world["emp"]
|
||||
emp.request("PUT", PATH, json={"value": "off"})
|
||||
ada.request("PUT", PATH, json={"value": "case_matters", "team_mode": "locked"})
|
||||
|
||||
locked = emp.request("GET", PATH)
|
||||
assert (locked["value"], locked["source"], locked["locked"]) == ("case_matters", "locked", True)
|
||||
refused = emp.request("PUT", PATH, json={"value": "case"}, status=403)
|
||||
assert "vorgegeben" in refused["detail"]
|
||||
|
||||
# The main user is not bound by the own binding.
|
||||
assert ada.request("PUT", PATH, json={"value": "case"})["value"] == "case"
|
||||
assert ada.request("GET", PATH)["team_mode"] == "locked"
|
||||
assert emp.request("GET", PATH)["value"] == "case"
|
||||
|
||||
ada.request("PUT", PATH, json={"value": "case", "team_mode": "free"})
|
||||
again = emp.request("GET", PATH)
|
||||
assert (again["value"], again["source"]) == ("off", "own")
|
||||
|
||||
|
||||
def test_only_the_main_user_binds_and_values_are_checked(world):
|
||||
ada, emp = world["ada"], world["emp"]
|
||||
emp.request("PUT", PATH, json={"value": "off", "team_mode": "locked"}, status=403)
|
||||
assert emp.request("GET", PATH)["source"] == "default"
|
||||
ada.request("PUT", PATH, json={"value": "everywhere"}, status=422)
|
||||
ada.request("GET", "/api/v1/auth/preferences/unknown", status=404)
|
||||
ada.request("PUT", "/api/v1/auth/preferences/unknown", json={"value": "off"}, status=404)
|
||||
|
||||
|
||||
def test_a_binding_of_a_stranger_does_not_reach_my_employee(client, db, world):
|
||||
ben = _main(client, db, "ben")
|
||||
ben.request("PUT", PATH, json={"value": "off", "team_mode": "locked"})
|
||||
assert world["emp"].request("GET", PATH)["value"] == "case"
|
||||
Reference in new issue
Block a user