Stelle den ersten nutzbaren Ablauf zum Organisieren und Nachverfolgen bereit.
Deploy Development / deploy (push) Successful in 23s
Deploy Development / deploy (push) Successful in 23s
Anmeldung, Datenraeume, Akten, Vorgaenge, gemeinsame Notizen, Dateien, manuelle Paperless-Referenzen, Aufgaben und unabhaengige Fristen laufen damit in der Entwicklungsumgebung. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
cfe17ff909
commit
2558239bfd
60 files changed
+8467
-71
No files matched your search
@@ -0,0 +1,5 @@
|
||||
__pycache__
|
||||
.pytest_cache
|
||||
.venv
|
||||
data
|
||||
*.pyc
|
||||
+5
-1
@@ -2,11 +2,15 @@ FROM python:3.12-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1
|
||||
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY main.py .
|
||||
COPY app ./app
|
||||
COPY migrations ./migrations
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||
CMD ["python", "-m", "app.entrypoint"]
|
||||
@@ -0,0 +1 @@
|
||||
"""Tsumugu application package."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Data rooms and the case-based access policy."""
|
||||
@@ -0,0 +1,763 @@
|
||||
"""Context rights for the first delivery.
|
||||
|
||||
Provisional MVP assumptions, not final product decisions, live in docs/MVP_ANNAHMEN.md.
|
||||
The action context is the only rights path used here. A case link inherits that case's
|
||||
rights. Cross-links do not. Exceptions apply only in the context they name.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
from app.core.errors import conflict, forbidden, not_found, unprocessable
|
||||
|
||||
SHARED_NOTICE = "Diese Änderung betrifft den gemeinsamen Inhalt der Notiz."
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Rights:
|
||||
read: bool = False
|
||||
edit: bool = False
|
||||
share: bool = False
|
||||
delete: bool = False
|
||||
|
||||
@classmethod
|
||||
def full(cls) -> Rights:
|
||||
return cls(True, True, True, True)
|
||||
|
||||
@classmethod
|
||||
def from_row(cls, row: dict | None) -> Rights:
|
||||
if row is None:
|
||||
return cls()
|
||||
return cls(bool(row["can_read"]), bool(row["can_edit"]), bool(row["can_share"]), bool(row["can_delete"]))
|
||||
|
||||
def without(self, blocked: Rights) -> Rights:
|
||||
return Rights(
|
||||
self.read and not blocked.read,
|
||||
self.edit and not blocked.edit,
|
||||
self.share and not blocked.share,
|
||||
self.delete and not blocked.delete,
|
||||
)
|
||||
|
||||
def allows(self, need: str) -> bool:
|
||||
return bool(getattr(self, need))
|
||||
|
||||
def as_dict(self) -> dict[str, bool]:
|
||||
return {"read": self.read, "edit": self.edit, "share": self.share, "delete": self.delete}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Ctx:
|
||||
kind: str
|
||||
id: UUID
|
||||
|
||||
def as_dict(self) -> dict[str, str]:
|
||||
return {"kind": self.kind, "id": str(self.id)}
|
||||
|
||||
|
||||
def parse_context(payload: dict | None, *, required: bool = False) -> Ctx | None:
|
||||
if not payload:
|
||||
if required:
|
||||
raise unprocessable("Der Handlungskontext fehlt.")
|
||||
return None
|
||||
kind = payload.get("kind")
|
||||
raw = payload.get("id")
|
||||
if kind not in ("case", "matter") or not raw:
|
||||
raise unprocessable("Der Handlungskontext ist ungültig.")
|
||||
try:
|
||||
return Ctx(kind, UUID(str(raw)))
|
||||
except ValueError as exc:
|
||||
raise unprocessable("Der Handlungskontext ist ungültig.") from exc
|
||||
|
||||
|
||||
def parse_query_context(kind: str | None, raw: str | None) -> Ctx | None:
|
||||
if kind is None and raw is None:
|
||||
return None
|
||||
return parse_context({"kind": kind, "id": raw}, required=True)
|
||||
|
||||
|
||||
def audit(
|
||||
conn,
|
||||
actor_id: UUID | None,
|
||||
scope_id: UUID | None,
|
||||
action: str,
|
||||
resource_kind: str,
|
||||
resource_id: UUID,
|
||||
context: Ctx | None = None,
|
||||
occurred_on=None,
|
||||
) -> None:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO domain_events (
|
||||
actor_subject_id, scope_id, action, resource_kind, resource_id,
|
||||
context_kind, context_id, occurred_on
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
||||
""",
|
||||
(
|
||||
actor_id,
|
||||
scope_id,
|
||||
action,
|
||||
resource_kind,
|
||||
resource_id,
|
||||
context.kind if context else None,
|
||||
context.id if context else None,
|
||||
occurred_on,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def bump_version(conn, table: str, row_id: UUID, expected: int) -> int:
|
||||
if table not in {"cases", "matters", "elements", "tasks", "deadlines"}:
|
||||
raise RuntimeError("unsupported version table")
|
||||
row = conn.execute(
|
||||
f"UPDATE {table} SET version = version + 1, updated_at = now() "
|
||||
f"WHERE id = %s AND version = %s AND deleted_at IS NULL RETURNING version",
|
||||
(row_id, expected),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
current = conn.execute(
|
||||
f"SELECT version, deleted_at FROM {table} WHERE id = %s",
|
||||
(row_id,),
|
||||
).fetchone()
|
||||
if current is None or current["deleted_at"] is not None:
|
||||
raise not_found()
|
||||
raise conflict()
|
||||
return int(row["version"])
|
||||
|
||||
|
||||
def _get(conn, table: str, row_id: UUID) -> dict | None:
|
||||
if table not in {"cases", "matters", "elements", "tasks", "deadlines", "data_rooms"}:
|
||||
raise RuntimeError("unsupported lookup")
|
||||
return conn.execute(f"SELECT * FROM {table} WHERE id = %s", (row_id,)).fetchone()
|
||||
|
||||
|
||||
def get_case(conn, case_id: UUID) -> dict | None:
|
||||
row = _get(conn, "cases", case_id)
|
||||
if row is None or row["deleted_at"] is not None:
|
||||
return None
|
||||
return row
|
||||
|
||||
|
||||
def get_matter(conn, matter_id: UUID) -> dict | None:
|
||||
row = _get(conn, "matters", matter_id)
|
||||
if row is None or row["deleted_at"] is not None:
|
||||
return None
|
||||
return row
|
||||
|
||||
|
||||
def get_element(conn, element_id: UUID) -> dict | None:
|
||||
row = _get(conn, "elements", element_id)
|
||||
if row is None or row["deleted_at"] is not None:
|
||||
return None
|
||||
return row
|
||||
|
||||
|
||||
def get_task(conn, task_id: UUID) -> dict | None:
|
||||
row = _get(conn, "tasks", task_id)
|
||||
if row is None or row["deleted_at"] is not None:
|
||||
return None
|
||||
return row
|
||||
|
||||
|
||||
def get_deadline(conn, deadline_id: UUID) -> dict | None:
|
||||
row = _get(conn, "deadlines", deadline_id)
|
||||
if row is None or row["deleted_at"] is not None:
|
||||
return None
|
||||
return row
|
||||
|
||||
|
||||
def _direct_grant(conn, actor: UUID, kind: str, resource_id: UUID) -> Rights:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT can_read, can_edit, can_share, can_delete
|
||||
FROM access_grants
|
||||
WHERE NOT is_exception
|
||||
AND grantee_subject_id = %s
|
||||
AND resource_kind = %s
|
||||
AND resource_id = %s
|
||||
AND context_kind IS NULL
|
||||
""",
|
||||
(actor, kind, resource_id),
|
||||
).fetchone()
|
||||
return Rights.from_row(row)
|
||||
|
||||
|
||||
def _exceptions(conn, actor: UUID, kind: str, resource_id: UUID, context: Ctx | None) -> Rights:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT can_read, can_edit, can_share, can_delete
|
||||
FROM access_grants
|
||||
WHERE is_exception
|
||||
AND resource_kind = %s
|
||||
AND resource_id = %s
|
||||
AND context_kind IS NOT DISTINCT FROM %s
|
||||
AND context_id IS NOT DISTINCT FROM %s
|
||||
AND (grantee_subject_id IS NULL OR grantee_subject_id = %s)
|
||||
""",
|
||||
(
|
||||
kind,
|
||||
resource_id,
|
||||
context.kind if context else None,
|
||||
context.id if context else None,
|
||||
actor,
|
||||
),
|
||||
).fetchall()
|
||||
blocked = Rights()
|
||||
for row in rows:
|
||||
blocked = Rights(
|
||||
blocked.read or row["can_read"],
|
||||
blocked.edit or row["can_edit"],
|
||||
blocked.share or row["can_share"],
|
||||
blocked.delete or row["can_delete"],
|
||||
)
|
||||
return blocked
|
||||
|
||||
|
||||
def case_rights(conn, actor: UUID, case: dict) -> Rights:
|
||||
if case["parent_case_id"] is not None and case["rights_mode"] == "inherit_parent":
|
||||
parent = get_case(conn, case["parent_case_id"])
|
||||
base = case_rights(conn, actor, parent) if parent else Rights()
|
||||
elif case["owner_subject_id"] == actor:
|
||||
base = Rights.full()
|
||||
else:
|
||||
base = _direct_grant(conn, actor, "case", case["id"])
|
||||
return base.without(_exceptions(conn, actor, "case", case["id"], None))
|
||||
|
||||
|
||||
def _linked(conn, matter_id: UUID, case_id: UUID) -> bool:
|
||||
row = conn.execute(
|
||||
"SELECT 1 FROM matter_case_links WHERE matter_id = %s AND case_id = %s",
|
||||
(matter_id, case_id),
|
||||
).fetchone()
|
||||
return row is not None
|
||||
|
||||
|
||||
def matter_rights(conn, actor: UUID, matter: dict, context: Ctx | None) -> Rights:
|
||||
if context is None:
|
||||
base = Rights.full() if matter["owner_subject_id"] == actor else _direct_grant(conn, actor, "matter", matter["id"])
|
||||
return base.without(_exceptions(conn, actor, "matter", matter["id"], None))
|
||||
|
||||
if context.kind == "case":
|
||||
anchor_id = matter["id"]
|
||||
if not _linked(conn, matter["id"], context.id) and matter["parent_matter_id"] is not None:
|
||||
if _linked(conn, matter["parent_matter_id"], context.id):
|
||||
anchor_id = matter["parent_matter_id"]
|
||||
else:
|
||||
return Rights()
|
||||
elif not _linked(conn, matter["id"], context.id):
|
||||
return Rights()
|
||||
case = get_case(conn, context.id)
|
||||
if case is None:
|
||||
return Rights()
|
||||
base = case_rights(conn, actor, case)
|
||||
if anchor_id != matter["id"]:
|
||||
parent = get_matter(conn, anchor_id)
|
||||
if parent is None:
|
||||
return Rights()
|
||||
base = matter_rights(conn, actor, parent, context)
|
||||
return base.without(_exceptions(conn, actor, "matter", matter["id"], context))
|
||||
|
||||
if context.kind == "matter":
|
||||
if matter["parent_matter_id"] != context.id:
|
||||
return Rights()
|
||||
parent = get_matter(conn, context.id)
|
||||
if parent is None:
|
||||
return Rights()
|
||||
base = matter_rights(conn, actor, parent, None)
|
||||
return base.without(_exceptions(conn, actor, "matter", matter["id"], context))
|
||||
return Rights()
|
||||
|
||||
|
||||
def _bindings(conn, element_id: UUID) -> list[dict]:
|
||||
return conn.execute(
|
||||
"SELECT * FROM bindings WHERE element_id = %s ORDER BY position, created_at",
|
||||
(element_id,),
|
||||
).fetchall()
|
||||
|
||||
|
||||
def _blocked(conn, case_id: UUID, element_id: UUID) -> bool:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT 1
|
||||
FROM case_link_blocks b
|
||||
JOIN matter_case_links l ON l.id = b.link_id
|
||||
WHERE l.case_id = %s AND b.element_id = %s
|
||||
""",
|
||||
(case_id, element_id),
|
||||
).fetchone()
|
||||
return row is not None
|
||||
|
||||
|
||||
def _matter_reaches_case(conn, matter_id: UUID, case_id: UUID) -> bool:
|
||||
matter = get_matter(conn, matter_id)
|
||||
if matter is None:
|
||||
return False
|
||||
if _linked(conn, matter_id, case_id):
|
||||
return True
|
||||
return bool(matter["parent_matter_id"] and _linked(conn, matter["parent_matter_id"], case_id))
|
||||
|
||||
|
||||
def element_rights(conn, actor: UUID, element: dict, context: Ctx | None) -> Rights:
|
||||
if context is None:
|
||||
base = (
|
||||
Rights.full()
|
||||
if element["owner_subject_id"] == actor
|
||||
else _direct_grant(conn, actor, "element", element["id"])
|
||||
)
|
||||
return base.without(_exceptions(conn, actor, "element", element["id"], None))
|
||||
|
||||
bindings = _bindings(conn, element["id"])
|
||||
if context.kind == "case":
|
||||
on_case = any(item["context_kind"] == "case" and item["context_id"] == context.id for item in bindings)
|
||||
via_matter = [
|
||||
item
|
||||
for item in bindings
|
||||
if item["context_kind"] == "matter" and _matter_reaches_case(conn, item["context_id"], context.id)
|
||||
]
|
||||
if not on_case and not via_matter:
|
||||
return Rights()
|
||||
if not on_case and _blocked(conn, context.id, element["id"]):
|
||||
return Rights()
|
||||
case = get_case(conn, context.id)
|
||||
if case is None:
|
||||
return Rights()
|
||||
base = case_rights(conn, actor, case)
|
||||
return base.without(_exceptions(conn, actor, "element", element["id"], context))
|
||||
|
||||
if context.kind == "matter":
|
||||
matter = get_matter(conn, context.id)
|
||||
if matter is None:
|
||||
return Rights()
|
||||
hosted = any(
|
||||
item["context_kind"] == "matter"
|
||||
and (item["context_id"] == context.id or _child_of(conn, item["context_id"], context.id))
|
||||
for item in bindings
|
||||
)
|
||||
if not hosted:
|
||||
return Rights()
|
||||
base = matter_rights(conn, actor, matter, None)
|
||||
return base.without(_exceptions(conn, actor, "element", element["id"], context))
|
||||
return Rights()
|
||||
|
||||
|
||||
def _child_of(conn, matter_id: UUID, parent_id: UUID) -> bool:
|
||||
matter = get_matter(conn, matter_id)
|
||||
return bool(matter and matter["parent_matter_id"] == parent_id)
|
||||
|
||||
|
||||
def element_rights_via_case_or_direct(conn, actor: UUID, element: dict, context: Ctx | None) -> Rights:
|
||||
"""Rights for an element bound to a matter when the caller names a case path.
|
||||
|
||||
A matter context uses direct matter rights. A case context uses that case only.
|
||||
"""
|
||||
if context is None:
|
||||
return element_rights(conn, actor, element, None)
|
||||
if context.kind == "matter":
|
||||
return element_rights(conn, actor, element, context)
|
||||
return element_rights(conn, actor, element, context)
|
||||
|
||||
|
||||
def task_rights(conn, actor: UUID, task: dict, context: Ctx | None) -> Rights:
|
||||
if task["assignee_subject_id"] == actor and context is None:
|
||||
granted = _direct_grant(conn, actor, "task", task["id"])
|
||||
base = Rights(read=True, edit=granted.edit, share=False, delete=False)
|
||||
if task["owner_subject_id"] == actor:
|
||||
base = Rights.full()
|
||||
return base.without(_exceptions(conn, actor, "task", task["id"], None))
|
||||
if context is None:
|
||||
base = Rights.full() if task["owner_subject_id"] == actor else _direct_grant(conn, actor, "task", task["id"])
|
||||
return base.without(_exceptions(conn, actor, "task", task["id"], None))
|
||||
if task["matter_id"] is None:
|
||||
return Rights()
|
||||
matter = get_matter(conn, task["matter_id"])
|
||||
if matter is None:
|
||||
return Rights()
|
||||
if context.kind == "matter" and context.id == task["matter_id"]:
|
||||
base = matter_rights(conn, actor, matter, None)
|
||||
elif context.kind == "case":
|
||||
base = matter_rights(conn, actor, matter, context)
|
||||
elif context.kind == "matter" and matter["parent_matter_id"] == context.id:
|
||||
base = matter_rights(conn, actor, matter, context)
|
||||
else:
|
||||
return Rights()
|
||||
return base.without(_exceptions(conn, actor, "task", task["id"], context))
|
||||
|
||||
|
||||
def deadline_rights(conn, actor: UUID, deadline: dict, context: Ctx | None) -> Rights:
|
||||
if deadline["assignee_subject_id"] == actor and context is None:
|
||||
base = Rights(read=True, edit=False, share=False, delete=False)
|
||||
if deadline["owner_subject_id"] == actor:
|
||||
base = Rights.full()
|
||||
return base.without(_exceptions(conn, actor, "deadline", deadline["id"], None))
|
||||
if context is None:
|
||||
base = (
|
||||
Rights.full()
|
||||
if deadline["owner_subject_id"] == actor
|
||||
else _direct_grant(conn, actor, "deadline", deadline["id"])
|
||||
)
|
||||
return base.without(_exceptions(conn, actor, "deadline", deadline["id"], None))
|
||||
if deadline["matter_id"] is None:
|
||||
return Rights()
|
||||
matter = get_matter(conn, deadline["matter_id"])
|
||||
if matter is None:
|
||||
return Rights()
|
||||
if context.kind == "matter" and context.id == deadline["matter_id"]:
|
||||
base = matter_rights(conn, actor, matter, None)
|
||||
elif context.kind == "case":
|
||||
base = matter_rights(conn, actor, matter, context)
|
||||
else:
|
||||
return Rights()
|
||||
return base.without(_exceptions(conn, actor, "deadline", deadline["id"], context))
|
||||
|
||||
|
||||
def require_case(conn, actor: UUID, case_id: UUID, need: str) -> tuple[dict, Rights]:
|
||||
case = get_case(conn, case_id)
|
||||
if case is None:
|
||||
raise not_found()
|
||||
rights = case_rights(conn, actor, case)
|
||||
_require(rights, need)
|
||||
return case, rights
|
||||
|
||||
|
||||
def require_matter(conn, actor: UUID, matter_id: UUID, context: Ctx | None, need: str) -> tuple[dict, Rights]:
|
||||
matter = get_matter(conn, matter_id)
|
||||
if matter is None:
|
||||
raise not_found()
|
||||
rights = matter_rights(conn, actor, matter, context)
|
||||
_require(rights, need)
|
||||
return matter, rights
|
||||
|
||||
|
||||
def require_element(conn, actor: UUID, element_id: UUID, context: Ctx | None, need: str) -> tuple[dict, Rights]:
|
||||
element = get_element(conn, element_id)
|
||||
if element is None:
|
||||
raise not_found()
|
||||
rights = element_rights(conn, actor, element, context)
|
||||
_require(rights, need)
|
||||
return element, rights
|
||||
|
||||
|
||||
def _require(rights: Rights, need: str) -> None:
|
||||
if not rights.read:
|
||||
raise not_found()
|
||||
if need != "read" and not rights.allows(need):
|
||||
raise forbidden()
|
||||
|
||||
|
||||
def can_change_status(actor: UUID, row: dict, rights: Rights, assignee_key: str = "assignee_subject_id") -> bool:
|
||||
if rights.edit or row["owner_subject_id"] == actor:
|
||||
return True
|
||||
return row[assignee_key] == actor and rights.read
|
||||
|
||||
|
||||
def readable_matter_contexts(conn, actor: UUID, matter: dict) -> list[dict]:
|
||||
found: list[dict] = []
|
||||
direct = matter_rights(conn, actor, matter, None)
|
||||
if direct.read:
|
||||
found.append({"kind": "matter", "id": str(matter["id"]), "title": matter["title"], "rights": direct.as_dict()})
|
||||
links = conn.execute(
|
||||
"""
|
||||
SELECT l.case_id, c.title
|
||||
FROM matter_case_links l
|
||||
JOIN cases c ON c.id = l.case_id
|
||||
WHERE l.matter_id = %s AND c.deleted_at IS NULL
|
||||
""",
|
||||
(matter["id"],),
|
||||
).fetchall()
|
||||
if matter["parent_matter_id"] is not None:
|
||||
links = list(links) + list(
|
||||
conn.execute(
|
||||
"""
|
||||
SELECT l.case_id, c.title
|
||||
FROM matter_case_links l
|
||||
JOIN cases c ON c.id = l.case_id
|
||||
WHERE l.matter_id = %s AND c.deleted_at IS NULL
|
||||
""",
|
||||
(matter["parent_matter_id"],),
|
||||
).fetchall()
|
||||
)
|
||||
seen: set[UUID] = set()
|
||||
for link in links:
|
||||
if link["case_id"] in seen:
|
||||
continue
|
||||
seen.add(link["case_id"])
|
||||
rights = matter_rights(conn, actor, matter, Ctx("case", link["case_id"]))
|
||||
if rights.read:
|
||||
found.append(
|
||||
{
|
||||
"kind": "case",
|
||||
"id": str(link["case_id"]),
|
||||
"title": link["title"],
|
||||
"rights": rights.as_dict(),
|
||||
}
|
||||
)
|
||||
return found
|
||||
|
||||
|
||||
def list_cases(conn, actor: UUID) -> list[dict]:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT c.*
|
||||
FROM cases c
|
||||
WHERE c.deleted_at IS NULL
|
||||
AND (
|
||||
c.owner_subject_id = %(actor)s
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM access_grants g
|
||||
WHERE g.resource_kind = 'case' AND g.resource_id = c.id
|
||||
AND g.grantee_subject_id = %(actor)s AND NOT g.is_exception AND g.can_read
|
||||
AND g.context_id IS NULL
|
||||
)
|
||||
OR (
|
||||
c.rights_mode = 'inherit_parent' AND c.parent_case_id IS NOT NULL AND EXISTS (
|
||||
SELECT 1 FROM cases p
|
||||
WHERE p.id = c.parent_case_id AND p.deleted_at IS NULL
|
||||
AND (
|
||||
p.owner_subject_id = %(actor)s
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM access_grants g
|
||||
WHERE g.resource_kind = 'case' AND g.resource_id = p.id
|
||||
AND g.grantee_subject_id = %(actor)s AND NOT g.is_exception
|
||||
AND g.can_read AND g.context_id IS NULL
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
ORDER BY c.updated_at DESC, c.id DESC
|
||||
""",
|
||||
{"actor": actor},
|
||||
).fetchall()
|
||||
visible = []
|
||||
for row in rows:
|
||||
rights = case_rights(conn, actor, row)
|
||||
if rights.read:
|
||||
visible.append((row, rights))
|
||||
return visible
|
||||
|
||||
|
||||
def list_matters(conn, actor: UUID) -> list[tuple[dict, list[dict]]]:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT m.*
|
||||
FROM matters m
|
||||
WHERE m.deleted_at IS NULL
|
||||
AND (
|
||||
m.owner_subject_id = %(actor)s
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM access_grants g
|
||||
WHERE g.resource_kind = 'matter' AND g.resource_id = m.id
|
||||
AND g.grantee_subject_id = %(actor)s AND NOT g.is_exception AND g.can_read
|
||||
AND g.context_id IS NULL
|
||||
)
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM matter_case_links l
|
||||
JOIN cases c ON c.id = l.case_id AND c.deleted_at IS NULL
|
||||
WHERE l.matter_id = m.id
|
||||
AND (
|
||||
c.owner_subject_id = %(actor)s
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM access_grants g
|
||||
WHERE g.resource_kind = 'case' AND g.resource_id = c.id
|
||||
AND g.grantee_subject_id = %(actor)s AND NOT g.is_exception
|
||||
AND g.can_read AND g.context_id IS NULL
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
ORDER BY m.updated_at DESC, m.id DESC
|
||||
""",
|
||||
{"actor": actor},
|
||||
).fetchall()
|
||||
visible = []
|
||||
for row in rows:
|
||||
contexts = readable_matter_contexts(conn, actor, row)
|
||||
if contexts:
|
||||
visible.append((row, contexts))
|
||||
return visible
|
||||
|
||||
|
||||
def assert_scope_can_host(conn, scope_id: UUID) -> dict:
|
||||
room = _get(conn, "data_rooms", scope_id)
|
||||
if room is None or room["status"] != "active":
|
||||
raise forbidden("Der gewählte Datenraum ist nicht verfügbar.")
|
||||
return room
|
||||
|
||||
|
||||
def same_home(row: dict, scope_id: UUID) -> None:
|
||||
if row["home_scope_id"] != scope_id:
|
||||
raise unprocessable(
|
||||
"Unterakten, Teilvorgänge und Kapitel bleiben im Datenraum ihres Behälters. "
|
||||
"Wähle diesen Datenraum, wenn du dort Mitglied bist, oder lege einen Querverweis an."
|
||||
)
|
||||
|
||||
|
||||
def account_by_email(conn, email: str) -> dict | None:
|
||||
return conn.execute(
|
||||
"SELECT id, email, display_name, status FROM auth_accounts WHERE email = %s",
|
||||
(email.strip().lower(),),
|
||||
).fetchone()
|
||||
|
||||
|
||||
def display_name(conn, account_id: UUID | None) -> str | None:
|
||||
if account_id is None:
|
||||
return None
|
||||
row = conn.execute("SELECT display_name FROM auth_accounts WHERE id = %s", (account_id,)).fetchone()
|
||||
return row["display_name"] if row else None
|
||||
|
||||
|
||||
def room_name(conn, room_id: UUID) -> str | None:
|
||||
row = conn.execute("SELECT name FROM data_rooms WHERE id = %s", (room_id,)).fetchone()
|
||||
return row["name"] if row else None
|
||||
|
||||
|
||||
def visible_bindings_for_element(conn, actor: UUID, element: dict) -> list[dict]:
|
||||
"""Names and counts only bindings the actor can actually read."""
|
||||
result = []
|
||||
for binding in _bindings(conn, element["id"]):
|
||||
if binding["context_kind"] == "case":
|
||||
context = Ctx("case", binding["context_id"])
|
||||
rights = element_rights(conn, actor, element, context)
|
||||
if not rights.read:
|
||||
continue
|
||||
case = get_case(conn, binding["context_id"])
|
||||
if case is None:
|
||||
continue
|
||||
title = case["title"]
|
||||
else:
|
||||
matter = get_matter(conn, binding["context_id"])
|
||||
if matter is None:
|
||||
continue
|
||||
contexts = readable_matter_contexts(conn, actor, matter)
|
||||
if not contexts:
|
||||
continue
|
||||
direct = element_rights(conn, actor, element, Ctx("matter", matter["id"]))
|
||||
via_cases = []
|
||||
for item in contexts:
|
||||
if item["kind"] != "case":
|
||||
continue
|
||||
case_rights_now = element_rights(conn, actor, element, Ctx("case", UUID(item["id"])))
|
||||
if case_rights_now.read:
|
||||
via_cases.append(item)
|
||||
if not direct.read and not via_cases:
|
||||
continue
|
||||
title = matter["title"]
|
||||
context = Ctx("matter", matter["id"])
|
||||
result.append(
|
||||
{
|
||||
"id": str(binding["id"]),
|
||||
"context_kind": binding["context_kind"],
|
||||
"context_id": str(binding["context_id"]),
|
||||
"context_title": title,
|
||||
}
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def chapter_for(conn, chapter_id: UUID | None, kind: str, container_id: UUID) -> None:
|
||||
if chapter_id is None:
|
||||
return
|
||||
column = "case_id" if kind == "case" else "matter_id"
|
||||
row = conn.execute(
|
||||
f"SELECT id FROM chapters WHERE id = %s AND {column} = %s",
|
||||
(chapter_id, container_id),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise unprocessable("Das Kapitel gehört nicht zu diesem Kontext.")
|
||||
|
||||
|
||||
def next_position(conn, kind: str, container_id: UUID) -> int:
|
||||
row = conn.execute(
|
||||
"SELECT COALESCE(MAX(position), 0) + 1 AS pos FROM bindings WHERE context_kind = %s AND context_id = %s",
|
||||
(kind, container_id),
|
||||
).fetchone()
|
||||
return int(row["pos"])
|
||||
|
||||
|
||||
def insert_binding(conn, element_id: UUID, kind: str, container_id: UUID, chapter_id: UUID | None, actor: UUID) -> dict:
|
||||
existing = conn.execute(
|
||||
"""
|
||||
SELECT id FROM bindings
|
||||
WHERE element_id = %s AND context_kind = %s AND context_id = %s
|
||||
""",
|
||||
(element_id, kind, container_id),
|
||||
).fetchone()
|
||||
if existing is not None:
|
||||
raise unprocessable("Die Notiz ist in diesem Kontext bereits eingebunden.")
|
||||
chapter_for(conn, chapter_id, kind, container_id)
|
||||
row = conn.execute(
|
||||
"""
|
||||
INSERT INTO bindings (element_id, context_kind, context_id, chapter_id, position, created_by)
|
||||
VALUES (%s, %s, %s, %s, %s, %s)
|
||||
RETURNING *
|
||||
""",
|
||||
(element_id, kind, container_id, chapter_id, next_position(conn, kind, container_id), actor),
|
||||
).fetchone()
|
||||
return row
|
||||
|
||||
|
||||
def block_unsharable_matter_elements(conn, actor: UUID, link_id: UUID, matter: dict) -> None:
|
||||
"""Contents the linking actor cannot share stay invisible in that case. No titles are stored."""
|
||||
matter_ids = [matter["id"]]
|
||||
children = conn.execute(
|
||||
"SELECT id FROM matters WHERE parent_matter_id = %s AND deleted_at IS NULL",
|
||||
(matter["id"],),
|
||||
).fetchall()
|
||||
matter_ids.extend(item["id"] for item in children)
|
||||
for matter_id in matter_ids:
|
||||
bindings = conn.execute(
|
||||
"SELECT element_id FROM bindings WHERE context_kind = 'matter' AND context_id = %s",
|
||||
(matter_id,),
|
||||
).fetchall()
|
||||
container = get_matter(conn, matter_id)
|
||||
if container is None:
|
||||
continue
|
||||
for binding in bindings:
|
||||
element = get_element(conn, binding["element_id"])
|
||||
if element is None:
|
||||
continue
|
||||
rights = element_rights(conn, actor, element, Ctx("matter", matter_id))
|
||||
if matter_id != matter["id"]:
|
||||
parent_rights = element_rights(conn, actor, element, Ctx("matter", matter["id"]))
|
||||
if parent_rights.share:
|
||||
rights = parent_rights
|
||||
if rights.share:
|
||||
continue
|
||||
conn.execute(
|
||||
"INSERT INTO case_link_blocks (link_id, element_id) VALUES (%s, %s) ON CONFLICT DO NOTHING",
|
||||
(link_id, element["id"]),
|
||||
)
|
||||
|
||||
|
||||
def matter_title_if_readable(conn, actor: UUID, matter_id: UUID | None) -> str | None:
|
||||
if matter_id is None:
|
||||
return None
|
||||
matter = get_matter(conn, matter_id)
|
||||
if matter is None:
|
||||
return None
|
||||
if readable_matter_contexts(conn, actor, matter):
|
||||
return matter["title"]
|
||||
return None
|
||||
|
||||
|
||||
def ensure_member_or_personal(conn, account_id: UUID, kind: str, scope_id: UUID) -> dict:
|
||||
room = assert_scope_can_host(conn, scope_id)
|
||||
if kind == "personal":
|
||||
if room["kind"] != "personal" or room["id"] != account_id:
|
||||
raise forbidden("Der persönliche Datenraum gehört zu einem anderen Konto.")
|
||||
return room
|
||||
if kind != "organization" or room["kind"] != "organization":
|
||||
raise forbidden("Dieser Datenraum kann nicht gewählt werden.")
|
||||
membership = conn.execute(
|
||||
"""
|
||||
SELECT role FROM room_memberships
|
||||
WHERE room_id = %s AND subject_id = %s AND status = 'active'
|
||||
""",
|
||||
(scope_id, account_id),
|
||||
).fetchone()
|
||||
if membership is None:
|
||||
raise forbidden("Du bist in diesem Datenraum nicht Mitglied.")
|
||||
return room
|
||||
@@ -0,0 +1 @@
|
||||
"""HTTP adapters. Authorization stays in the domain services."""
|
||||
@@ -0,0 +1,97 @@
|
||||
"""Request scope: one transaction, a session principal, and no client-supplied identity."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import Depends, Request
|
||||
from psycopg import Connection
|
||||
|
||||
from app.access.policy import ensure_member_or_personal
|
||||
from app.auth.security import hash_secret, read_session_token
|
||||
from app.core.errors import forbidden, unauthorized
|
||||
from app.core.timeutil import utcnow
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Principal:
|
||||
account_id: UUID
|
||||
email: str
|
||||
display_name: str
|
||||
session_id: UUID
|
||||
scope_kind: str
|
||||
scope_id: UUID
|
||||
scope_name: str
|
||||
epoch: int
|
||||
|
||||
|
||||
def get_conn(request: Request):
|
||||
pool = request.app.state.pool
|
||||
with pool.connection() as conn:
|
||||
try:
|
||||
conn.execute("SET TIME ZONE 'UTC'")
|
||||
yield conn
|
||||
conn.commit()
|
||||
for path in getattr(request.state, "delete_after_commit", []):
|
||||
Path(path).unlink(missing_ok=True)
|
||||
except Exception:
|
||||
conn.rollback()
|
||||
for path in getattr(request.state, "cleanup_files", []):
|
||||
Path(path).unlink(missing_ok=True)
|
||||
raise
|
||||
|
||||
|
||||
def _session_row(conn: Connection, request: Request) -> dict:
|
||||
token = read_session_token(request)
|
||||
if not token:
|
||||
raise unauthorized()
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT s.id, s.account_id, s.csrf_token, s.scope_kind, s.scope_id, s.epoch,
|
||||
s.expires_at, s.revoked_at, a.email, a.display_name, a.status AS account_status
|
||||
FROM auth_sessions s
|
||||
JOIN auth_accounts a ON a.id = s.account_id
|
||||
WHERE s.secret_hash = %s
|
||||
""",
|
||||
(hash_secret(token),),
|
||||
).fetchone()
|
||||
if row is None or row["revoked_at"] is not None or row["expires_at"] <= utcnow():
|
||||
raise unauthorized()
|
||||
if row["account_status"] != "active":
|
||||
raise unauthorized()
|
||||
if request.method not in {"GET", "HEAD", "OPTIONS"}:
|
||||
sent = request.headers.get("x-csrf-token") or ""
|
||||
if not sent or sent != row["csrf_token"]:
|
||||
raise forbidden("Die Anfrage konnte der Sitzung nicht zugeordnet werden.")
|
||||
return row
|
||||
|
||||
|
||||
def get_session(request: Request, conn: Connection = Depends(get_conn)) -> dict:
|
||||
return _session_row(conn, request)
|
||||
|
||||
|
||||
def get_principal(request: Request, conn: Connection = Depends(get_conn)) -> Principal:
|
||||
row = _session_row(conn, request)
|
||||
kind = request.headers.get("x-scope-kind")
|
||||
raw_scope = request.headers.get("x-scope-id")
|
||||
if not kind or not raw_scope:
|
||||
raise forbidden("Der Datenraum ist nicht gewählt.")
|
||||
try:
|
||||
scope_id = UUID(raw_scope)
|
||||
except ValueError as exc:
|
||||
raise forbidden("Der Datenraum ist nicht gewählt.") from exc
|
||||
if kind != row["scope_kind"] or scope_id != row["scope_id"]:
|
||||
raise forbidden("Der gewählte Datenraum entspricht nicht mehr der Sitzung.")
|
||||
room = ensure_member_or_personal(conn, row["account_id"], kind, scope_id)
|
||||
return Principal(
|
||||
account_id=row["account_id"],
|
||||
email=row["email"],
|
||||
display_name=row["display_name"],
|
||||
session_id=row["id"],
|
||||
scope_kind=kind,
|
||||
scope_id=scope_id,
|
||||
scope_name=room["name"],
|
||||
epoch=row["epoch"],
|
||||
)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,203 @@
|
||||
"""Request bodies. Unknown fields are rejected."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from typing import Annotated, Literal
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
Email = Annotated[str, Field(min_length=3, max_length=320, pattern=r"^[^@\s]+@[^@\s]+\.[^@\s]+$")]
|
||||
|
||||
|
||||
class APIModel(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
|
||||
class LoginIn(APIModel):
|
||||
email: Email
|
||||
password: str = Field(min_length=1, max_length=200)
|
||||
|
||||
|
||||
class ScopeIn(APIModel):
|
||||
kind: Literal["personal", "organization"]
|
||||
id: UUID
|
||||
|
||||
|
||||
class AcceptInviteIn(APIModel):
|
||||
token: str = Field(min_length=20, max_length=200)
|
||||
display_name: str = Field(min_length=1, max_length=120)
|
||||
password: str = Field(min_length=10, max_length=200)
|
||||
|
||||
|
||||
class InvitationIn(APIModel):
|
||||
email: Email
|
||||
room_id: UUID
|
||||
|
||||
|
||||
class RoomIn(APIModel):
|
||||
name: str = Field(min_length=1, max_length=160)
|
||||
|
||||
|
||||
class MemberIn(APIModel):
|
||||
email: Email
|
||||
role: Literal["member", "manager"]
|
||||
|
||||
|
||||
class ContextIn(APIModel):
|
||||
kind: Literal["case", "matter"]
|
||||
id: UUID
|
||||
|
||||
|
||||
class CaseIn(APIModel):
|
||||
title: str = Field(min_length=1, max_length=200)
|
||||
parent_case_id: UUID | None = None
|
||||
rights_mode: Literal["inherit_parent", "explicit"] = "inherit_parent"
|
||||
|
||||
|
||||
class CasePatch(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
title: str | None = Field(default=None, min_length=1, max_length=200)
|
||||
status: Literal["open", "closed"] | None = None
|
||||
|
||||
|
||||
class ChapterIn(APIModel):
|
||||
title: str = Field(min_length=1, max_length=200)
|
||||
position: int | None = Field(default=None, ge=0, le=10000)
|
||||
|
||||
|
||||
class MatterIn(APIModel):
|
||||
title: str = Field(min_length=1, max_length=200)
|
||||
parent_matter_id: UUID | None = None
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class MatterPatch(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
title: str | None = Field(default=None, min_length=1, max_length=200)
|
||||
status: Literal["open", "closed"] | None = None
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class CaseLinkIn(APIModel):
|
||||
case_id: UUID
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class CrossLinkIn(APIModel):
|
||||
target_matter_id: UUID
|
||||
target_context: ContextIn
|
||||
source_context: ContextIn | None = None
|
||||
|
||||
|
||||
class GrantIn(APIModel):
|
||||
email: Email
|
||||
can_read: bool = True
|
||||
can_edit: bool = False
|
||||
can_share: bool = False
|
||||
|
||||
|
||||
class ExceptionIn(APIModel):
|
||||
resource_kind: Literal["element", "matter", "task", "deadline"]
|
||||
resource_id: UUID
|
||||
context: ContextIn
|
||||
remove_read: bool = False
|
||||
remove_edit: bool = False
|
||||
remove_share: bool = False
|
||||
|
||||
|
||||
class DocumentIn(APIModel):
|
||||
version: Literal[1] = 1
|
||||
blocks: list[dict]
|
||||
|
||||
|
||||
class NoteIn(APIModel):
|
||||
title: str = Field(min_length=1, max_length=200)
|
||||
document: DocumentIn
|
||||
context: ContextIn
|
||||
placement: ContextIn | None = None
|
||||
chapter_id: UUID | None = None
|
||||
|
||||
|
||||
class NotePatch(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
document: DocumentIn
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class BindingIn(APIModel):
|
||||
element_id: UUID
|
||||
source_context: ContextIn
|
||||
target: ContextIn
|
||||
target_context: ContextIn | None = None
|
||||
chapter_id: UUID | None = None
|
||||
|
||||
|
||||
class AnnotationIn(APIModel):
|
||||
body: str = Field(min_length=1, max_length=4000)
|
||||
|
||||
|
||||
class DatesIn(APIModel):
|
||||
document_on: date | None = None
|
||||
sent_on: date | None = None
|
||||
received_on: date | None = None
|
||||
|
||||
|
||||
class ExternalIn(APIModel):
|
||||
title: str = Field(min_length=1, max_length=200)
|
||||
source: Literal["paperless", "url"]
|
||||
external_id: str = Field(min_length=1, max_length=200)
|
||||
context: ContextIn
|
||||
placement: ContextIn | None = None
|
||||
chapter_id: UUID | None = None
|
||||
dates: DatesIn = DatesIn()
|
||||
|
||||
|
||||
class DeleteElementIn(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
|
||||
|
||||
class TaskIn(APIModel):
|
||||
title: str = Field(min_length=1, max_length=200)
|
||||
due_on: date | None = None
|
||||
matter_id: UUID | None = None
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class TaskPatch(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
title: str | None = Field(default=None, min_length=1, max_length=200)
|
||||
due_on: date | None = None
|
||||
clear_due_on: bool = False
|
||||
status: Literal["open", "done"] | None = None
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class AssigneeIn(APIModel):
|
||||
email: str | None = None
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class DeadlineIn(APIModel):
|
||||
title: str = Field(min_length=1, max_length=200)
|
||||
due_on: date
|
||||
matter_id: UUID | None = None
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class DeadlinePatch(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
title: str | None = Field(default=None, min_length=1, max_length=200)
|
||||
due_on: date | None = None
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class FulfillIn(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class TaskDeadlineIn(APIModel):
|
||||
deadline_id: UUID
|
||||
context: ContextIn | None = None
|
||||
@@ -0,0 +1 @@
|
||||
"""Accounts, sessions and cookies."""
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Accounts, personal rooms and sessions."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from app.auth.security import hash_password, hash_secret, new_secret, session_expiry
|
||||
from app.core.errors import unprocessable
|
||||
from app.core.settings import Settings
|
||||
|
||||
|
||||
def normalize_email(email: str) -> str:
|
||||
return email.strip().lower()
|
||||
|
||||
|
||||
def create_account(conn, email: str, display_name: str, password: str) -> dict:
|
||||
email = normalize_email(email)
|
||||
display_name = display_name.strip()
|
||||
if conn.execute("SELECT 1 FROM auth_accounts WHERE email = %s", (email,)).fetchone():
|
||||
raise unprocessable("Für diese E-Mail gibt es bereits ein Konto.")
|
||||
account_id = uuid4()
|
||||
password_hash = hash_password(password)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO auth_accounts (id, email, display_name, password_hash)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
""",
|
||||
(account_id, email, display_name, password_hash),
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO data_rooms (id, kind, name, created_by)
|
||||
VALUES (%s, 'personal', 'Persönlicher Raum', %s)
|
||||
""",
|
||||
(account_id, account_id),
|
||||
)
|
||||
return conn.execute(
|
||||
"SELECT id, email, display_name FROM auth_accounts WHERE id = %s",
|
||||
(account_id,),
|
||||
).fetchone()
|
||||
|
||||
|
||||
def start_session(conn, settings: Settings, account_id: UUID) -> tuple[str, str]:
|
||||
token = new_secret()
|
||||
csrf = new_secret()
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO auth_sessions (
|
||||
account_id, secret_hash, csrf_token, scope_kind, scope_id, expires_at
|
||||
)
|
||||
VALUES (%s, %s, %s, 'personal', %s, %s)
|
||||
""",
|
||||
(account_id, hash_secret(token), csrf, account_id, session_expiry(settings)),
|
||||
)
|
||||
return token, csrf
|
||||
|
||||
|
||||
def list_rooms(conn, account_id: UUID) -> list[dict]:
|
||||
personal = conn.execute(
|
||||
"SELECT id, kind, name FROM data_rooms WHERE id = %s AND kind = 'personal'",
|
||||
(account_id,),
|
||||
).fetchone()
|
||||
rooms = []
|
||||
if personal is not None:
|
||||
rooms.append({"id": str(personal["id"]), "kind": personal["kind"], "name": personal["name"], "role": "owner"})
|
||||
shared = conn.execute(
|
||||
"""
|
||||
SELECT r.id, r.kind, r.name, m.role
|
||||
FROM room_memberships m
|
||||
JOIN data_rooms r ON r.id = m.room_id
|
||||
WHERE m.subject_id = %s AND m.status = 'active' AND r.status = 'active' AND r.kind = 'organization'
|
||||
ORDER BY r.name, r.id
|
||||
""",
|
||||
(account_id,),
|
||||
).fetchall()
|
||||
for room in shared:
|
||||
rooms.append({"id": str(room["id"]), "kind": room["kind"], "name": room["name"], "role": room["role"]})
|
||||
return rooms
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Password hashing, session cookies and CSRF."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import secrets
|
||||
from datetime import timedelta
|
||||
|
||||
import bcrypt
|
||||
from fastapi import Request, Response
|
||||
|
||||
from app.core.settings import Settings
|
||||
from app.core.timeutil import utcnow
|
||||
|
||||
HOST_COOKIE = "__Host-jinkendo-session"
|
||||
PLAIN_COOKIE = "jinkendo-session"
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt(rounds=12)).decode("utf-8")
|
||||
|
||||
|
||||
def verify_password(password: str, password_hash: str) -> bool:
|
||||
try:
|
||||
return bcrypt.checkpw(password.encode("utf-8"), password_hash.encode("utf-8"))
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def new_secret() -> str:
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def hash_secret(secret: str) -> str:
|
||||
return hashlib.sha256(secret.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def cookie_name_and_secure(request: Request, settings: Settings) -> tuple[str, bool]:
|
||||
# __Host- cookies require Secure. Production is only published behind HTTPS.
|
||||
# Development also serves the documented plain HTTP LAN addresses, which cannot store them.
|
||||
if settings.tsumugu_env == "production":
|
||||
return HOST_COOKIE, True
|
||||
forwarded = request.headers.get("x-forwarded-proto", request.url.scheme)
|
||||
if forwarded == "https":
|
||||
return HOST_COOKIE, True
|
||||
return PLAIN_COOKIE, False
|
||||
|
||||
|
||||
def read_session_token(request: Request) -> str | None:
|
||||
return request.cookies.get(HOST_COOKIE) or request.cookies.get(PLAIN_COOKIE)
|
||||
|
||||
|
||||
def set_session_cookie(response: Response, request: Request, settings: Settings, token: str) -> None:
|
||||
name, secure = cookie_name_and_secure(request, settings)
|
||||
response.set_cookie(
|
||||
key=name,
|
||||
value=token,
|
||||
httponly=True,
|
||||
secure=secure,
|
||||
samesite="lax",
|
||||
path="/",
|
||||
max_age=settings.session_ttl_hours * 3600,
|
||||
)
|
||||
|
||||
|
||||
def clear_session_cookie(response: Response, request: Request, settings: Settings) -> None:
|
||||
name, secure = cookie_name_and_secure(request, settings)
|
||||
response.delete_cookie(key=name, path="/", secure=secure, httponly=True, samesite="lax")
|
||||
if name != PLAIN_COOKIE:
|
||||
response.delete_cookie(key=PLAIN_COOKIE, path="/", httponly=True, samesite="lax")
|
||||
|
||||
|
||||
def session_expiry(settings: Settings):
|
||||
return utcnow() + timedelta(hours=settings.session_ttl_hours)
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Operator commands: migrate, seed demo data, create the first account."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
|
||||
from app.auth.accounts import create_account
|
||||
from app.core.settings import get_settings
|
||||
from app.db.migrate import migrate
|
||||
from app.seed import seed_demo
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(prog="tsumugu")
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
sub.add_parser("migrate")
|
||||
sub.add_parser("seed-demo")
|
||||
create = sub.add_parser("create-account")
|
||||
create.add_argument("--email", required=True)
|
||||
create.add_argument("--name", required=True)
|
||||
create.add_argument("--password", required=True)
|
||||
args = parser.parse_args()
|
||||
settings = get_settings()
|
||||
if args.command == "migrate":
|
||||
applied = migrate(settings)
|
||||
print("applied" if applied else "up to date")
|
||||
return
|
||||
if args.command == "seed-demo":
|
||||
created = seed_demo(settings)
|
||||
print("seeded" if created else "unchanged")
|
||||
return
|
||||
if len(args.password) < 10:
|
||||
raise SystemExit("password must be at least 10 characters")
|
||||
with psycopg.connect(settings.dsn(), row_factory=dict_row) as conn:
|
||||
account = create_account(conn, args.email, args.name, args.password)
|
||||
conn.commit()
|
||||
print(account["id"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1 @@
|
||||
"""Notes, bindings, files and external references."""
|
||||
@@ -0,0 +1,25 @@
|
||||
"""Bounded note documents. Only paragraph text is stored."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.core.errors import unprocessable
|
||||
|
||||
|
||||
def clean_document(document: dict) -> dict:
|
||||
blocks = document.get("blocks")
|
||||
if not isinstance(blocks, list) or len(blocks) > 400:
|
||||
raise unprocessable("Die Notiz hat kein gültiges Dokument.")
|
||||
clean = []
|
||||
for block in blocks:
|
||||
if not isinstance(block, dict) or set(block) - {"type", "text"}:
|
||||
raise unprocessable("Die Notiz enthält einen nicht unterstützten Block.")
|
||||
if block.get("type") != "paragraph" or not isinstance(block.get("text"), str):
|
||||
raise unprocessable("Die Notiz enthält einen nicht unterstützten Block.")
|
||||
if len(block["text"]) > 20000:
|
||||
raise unprocessable("Ein Absatz ist zu lang.")
|
||||
clean.append({"type": "paragraph", "text": block["text"]})
|
||||
return {"version": 1, "blocks": clean}
|
||||
|
||||
|
||||
def document_text(document: dict) -> str:
|
||||
return "\n".join(block["text"] for block in document.get("blocks", []))
|
||||
@@ -0,0 +1 @@
|
||||
"""Core settings, errors and request helpers."""
|
||||
@@ -0,0 +1,71 @@
|
||||
"""RFC 9457 problem responses. Hidden objects use the same 404 as missing ones."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
|
||||
class Problem(Exception):
|
||||
def __init__(self, status: int, title: str, detail: str, code: str) -> None:
|
||||
super().__init__(detail)
|
||||
self.status = status
|
||||
self.title = title
|
||||
self.detail = detail
|
||||
self.code = code
|
||||
|
||||
def body(self, instance: str) -> dict:
|
||||
return {
|
||||
"type": "about:blank",
|
||||
"title": self.title,
|
||||
"status": self.status,
|
||||
"detail": self.detail,
|
||||
"instance": instance,
|
||||
"code": self.code,
|
||||
}
|
||||
|
||||
|
||||
def unauthorized() -> Problem:
|
||||
return Problem(401, "Anmeldung erforderlich", "Die Sitzung fehlt oder ist abgelaufen.", "unauthorized")
|
||||
|
||||
|
||||
def forbidden(detail: str = "Diese Aktion ist im gewählten Kontext nicht erlaubt.") -> Problem:
|
||||
return Problem(403, "Keine Berechtigung", detail, "forbidden")
|
||||
|
||||
|
||||
def not_found() -> Problem:
|
||||
return Problem(404, "Nicht gefunden", "Der Eintrag ist nicht vorhanden.", "not_found")
|
||||
|
||||
|
||||
def conflict() -> Problem:
|
||||
return Problem(
|
||||
409,
|
||||
"Versionskonflikt",
|
||||
"Der Stand hat sich geändert. Bitte neu laden.",
|
||||
"conflict",
|
||||
)
|
||||
|
||||
|
||||
def unprocessable(detail: str) -> Problem:
|
||||
return Problem(422, "Eingabe ungültig", detail, "unprocessable")
|
||||
|
||||
|
||||
def too_many() -> Problem:
|
||||
return Problem(429, "Zu viele Versuche", "Bitte kurz warten und es erneut versuchen.", "too_many_requests")
|
||||
|
||||
|
||||
def storage_unavailable() -> Problem:
|
||||
return Problem(
|
||||
503,
|
||||
"Speicher nicht verfügbar",
|
||||
"Die Datei kann gerade nicht gelesen oder geschrieben werden.",
|
||||
"storage_unavailable",
|
||||
)
|
||||
|
||||
|
||||
def problem_response(problem: Problem, request: Request) -> JSONResponse:
|
||||
return JSONResponse(
|
||||
status_code=problem.status,
|
||||
content=problem.body(request.url.path),
|
||||
media_type="application/problem+json",
|
||||
)
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Process settings. Unknown environments refuse to start."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from functools import lru_cache
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import field_validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(extra="ignore")
|
||||
|
||||
tsumugu_env: Literal["development", "production"]
|
||||
db_host: str = "localhost"
|
||||
db_port: int = 5432
|
||||
db_name: str
|
||||
db_user: str
|
||||
db_password: str
|
||||
db_runtime_user: str = "tsumugu_runtime"
|
||||
app_url: str = "http://localhost:5173"
|
||||
allowed_origins: str = "http://localhost:5173,http://localhost:3094"
|
||||
media_root: str = "data/media"
|
||||
seed_demo: bool = False
|
||||
session_ttl_hours: int = 336
|
||||
upload_max_bytes: int = 20 * 1024 * 1024
|
||||
|
||||
@field_validator("allowed_origins")
|
||||
@classmethod
|
||||
def strip_origins(cls, value: str) -> str:
|
||||
return value.strip()
|
||||
|
||||
@property
|
||||
def origin_set(self) -> set[str]:
|
||||
return {item.strip() for item in self.allowed_origins.split(",") if item.strip()}
|
||||
|
||||
def dsn(self, user: str | None = None) -> str:
|
||||
return (
|
||||
f"host={self.db_host} port={self.db_port} dbname={self.db_name} "
|
||||
f"user={user or self.db_user} password={self.db_password} connect_timeout=5"
|
||||
)
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_settings() -> Settings:
|
||||
return Settings()
|
||||
@@ -0,0 +1,23 @@
|
||||
"""UTC formatting for API values."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
|
||||
def utcnow() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def dump_dt(value: datetime | None) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
if value.tzinfo is None:
|
||||
value = value.replace(tzinfo=timezone.utc)
|
||||
return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
|
||||
def dump_date(value: date | None) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
return value.isoformat()
|
||||
@@ -0,0 +1 @@
|
||||
"""Database pool and migrations."""
|
||||
@@ -0,0 +1,90 @@
|
||||
"""SQL migrations with a checksum ledger, then a runtime role without DDL."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
from psycopg import ClientCursor, sql
|
||||
|
||||
from app.core.settings import Settings, get_settings
|
||||
|
||||
MIGRATIONS = Path(__file__).resolve().parent.parent.parent / "migrations"
|
||||
|
||||
|
||||
def _checksum(path: Path) -> str:
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def migrate(settings: Settings | None = None) -> list[str]:
|
||||
settings = settings or get_settings()
|
||||
applied: list[str] = []
|
||||
with psycopg.connect(settings.dsn(), autocommit=True, cursor_factory=ClientCursor) as conn:
|
||||
conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version text PRIMARY KEY,
|
||||
checksum text NOT NULL,
|
||||
applied_at timestamptz NOT NULL DEFAULT now()
|
||||
)
|
||||
"""
|
||||
)
|
||||
for path in sorted(MIGRATIONS.glob("*.sql")):
|
||||
version = path.name
|
||||
checksum = _checksum(path)
|
||||
row = conn.execute(
|
||||
"SELECT checksum FROM schema_migrations WHERE version = %s",
|
||||
(version,),
|
||||
).fetchone()
|
||||
if row is not None:
|
||||
if row[0] != checksum:
|
||||
raise RuntimeError(f"checksum mismatch for migration {version}")
|
||||
continue
|
||||
with conn.transaction():
|
||||
conn.execute(path.read_text(encoding="utf-8"))
|
||||
conn.execute(
|
||||
"INSERT INTO schema_migrations (version, checksum) VALUES (%s, %s)",
|
||||
(version, checksum),
|
||||
)
|
||||
applied.append(version)
|
||||
_ensure_runtime_role(conn, settings)
|
||||
return applied
|
||||
|
||||
|
||||
def _ensure_runtime_role(conn: psycopg.Connection, settings: Settings) -> None:
|
||||
role = sql.Identifier(settings.db_runtime_user)
|
||||
database = sql.Identifier(settings.db_name)
|
||||
owner = sql.Identifier(settings.db_user)
|
||||
password = sql.Literal(settings.db_password)
|
||||
exists = conn.execute(
|
||||
"SELECT 1 FROM pg_roles WHERE rolname = %s",
|
||||
(settings.db_runtime_user,),
|
||||
).fetchone()
|
||||
if exists is None:
|
||||
conn.execute(
|
||||
sql.SQL(
|
||||
"CREATE ROLE {} LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT PASSWORD {}"
|
||||
).format(role, password)
|
||||
)
|
||||
else:
|
||||
conn.execute(
|
||||
sql.SQL(
|
||||
"ALTER ROLE {} WITH LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT PASSWORD {}"
|
||||
).format(role, password)
|
||||
)
|
||||
conn.execute(sql.SQL("GRANT CONNECT ON DATABASE {} TO {}").format(database, role))
|
||||
conn.execute(sql.SQL("GRANT USAGE ON SCHEMA public TO {}").format(role))
|
||||
conn.execute(sql.SQL("REVOKE CREATE ON SCHEMA public FROM {}").format(role))
|
||||
conn.execute(
|
||||
sql.SQL(
|
||||
"GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO {}"
|
||||
).format(role)
|
||||
)
|
||||
conn.execute(sql.SQL("REVOKE ALL ON TABLE schema_migrations FROM {}").format(role))
|
||||
conn.execute(
|
||||
sql.SQL(
|
||||
"ALTER DEFAULT PRIVILEGES FOR ROLE {} IN SCHEMA public "
|
||||
"GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO {}"
|
||||
).format(owner, role)
|
||||
)
|
||||
@@ -0,0 +1,19 @@
|
||||
"""Runtime connection pool. Importing the app does not open it."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
from app.core.settings import Settings
|
||||
|
||||
|
||||
def open_pool(settings: Settings) -> ConnectionPool:
|
||||
return ConnectionPool(
|
||||
conninfo=settings.dsn(settings.db_runtime_user),
|
||||
kwargs={"row_factory": dict_row},
|
||||
min_size=1,
|
||||
max_size=10,
|
||||
open=True,
|
||||
timeout=10,
|
||||
)
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Migrate, optionally seed development data, then serve."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
from app.db.migrate import migrate
|
||||
from app.seed import seed_demo
|
||||
|
||||
|
||||
def main() -> None:
|
||||
migrate()
|
||||
seed_demo()
|
||||
os.execvp("uvicorn", ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,119 @@
|
||||
"""Application factory. Importing this module does not open a database connection."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from app.api.routes import router
|
||||
from app.core.errors import Problem, problem_response
|
||||
from app.core.settings import get_settings
|
||||
from app.db.pool import open_pool
|
||||
|
||||
logger = logging.getLogger("tsumugu")
|
||||
|
||||
|
||||
def _database_ok(app: FastAPI) -> bool:
|
||||
pool = getattr(app.state, "pool", None)
|
||||
if pool is None:
|
||||
return False
|
||||
try:
|
||||
with pool.connection() as conn:
|
||||
conn.execute("SELECT 1")
|
||||
conn.rollback()
|
||||
return True
|
||||
except Exception:
|
||||
logger.warning("database check failed")
|
||||
return False
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
settings = get_settings()
|
||||
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s %(message)s")
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
app.state.pool = open_pool(settings)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
app.state.pool.close()
|
||||
|
||||
app = FastAPI(title="Tsumugu", docs_url=None, redoc_url=None, openapi_url=None, lifespan=lifespan)
|
||||
app.state.settings = settings
|
||||
|
||||
@app.middleware("http")
|
||||
async def origin_guard(request: Request, call_next):
|
||||
if request.method not in {"GET", "HEAD", "OPTIONS"} and request.url.path.startswith("/api/"):
|
||||
origin = request.headers.get("origin")
|
||||
if origin not in settings.origin_set:
|
||||
problem = Problem(403, "Keine Berechtigung", "Der Ursprung der Anfrage ist nicht erlaubt.", "forbidden")
|
||||
return problem_response(problem, request)
|
||||
response = await call_next(request)
|
||||
logger.info("%s %s -> %s", request.method, request.url.path, response.status_code)
|
||||
return response
|
||||
|
||||
@app.exception_handler(Problem)
|
||||
async def handle_problem(request: Request, exc: Problem):
|
||||
return problem_response(exc, request)
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def handle_validation(request: Request, exc: RequestValidationError):
|
||||
return JSONResponse(
|
||||
status_code=422,
|
||||
content={
|
||||
"type": "about:blank",
|
||||
"title": "Eingabe ungültig",
|
||||
"status": 422,
|
||||
"detail": "Die Eingabe ist unvollständig oder ungültig.",
|
||||
"instance": request.url.path,
|
||||
"code": "unprocessable",
|
||||
},
|
||||
media_type="application/problem+json",
|
||||
)
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def handle_unexpected(request: Request, exc: Exception):
|
||||
logger.exception("unhandled error")
|
||||
return JSONResponse(
|
||||
status_code=500,
|
||||
content={
|
||||
"type": "about:blank",
|
||||
"title": "Unerwarteter Fehler",
|
||||
"status": 500,
|
||||
"detail": "Die Aktion konnte nicht abgeschlossen werden.",
|
||||
"instance": request.url.path,
|
||||
"code": "internal",
|
||||
},
|
||||
media_type="application/problem+json",
|
||||
)
|
||||
|
||||
@app.get("/api/health")
|
||||
def api_health():
|
||||
ok = _database_ok(app)
|
||||
return JSONResponse(
|
||||
status_code=200 if ok else 503,
|
||||
content={"status": "ok" if ok else "degraded", "app": "tsumugu"},
|
||||
)
|
||||
|
||||
@app.get("/health/live")
|
||||
def health_live():
|
||||
return {"status": "ok", "app": "tsumugu"}
|
||||
|
||||
@app.get("/health/ready")
|
||||
def health_ready():
|
||||
ok = _database_ok(app)
|
||||
return JSONResponse(
|
||||
status_code=200 if ok else 503,
|
||||
content={"status": "ok" if ok else "degraded", "app": "tsumugu"},
|
||||
)
|
||||
|
||||
app.include_router(router)
|
||||
return app
|
||||
|
||||
|
||||
app = create_app()
|
||||
@@ -0,0 +1 @@
|
||||
"""Private file storage. Paths are server-generated."""
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Sniff uploads and keep client names out of the storage path."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
from uuid import UUID
|
||||
|
||||
from app.core.errors import storage_unavailable, unprocessable
|
||||
|
||||
ALLOWED = {
|
||||
"application/pdf": "pdf",
|
||||
"image/png": "png",
|
||||
"image/jpeg": "jpg",
|
||||
"image/webp": "webp",
|
||||
}
|
||||
|
||||
|
||||
def sniff(data: bytes) -> str:
|
||||
if data.startswith(b"%PDF"):
|
||||
return "application/pdf"
|
||||
if data.startswith(b"\x89PNG\r\n\x1a\n"):
|
||||
return "image/png"
|
||||
if data.startswith(b"\xff\xd8\xff"):
|
||||
return "image/jpeg"
|
||||
if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WEBP":
|
||||
return "image/webp"
|
||||
raise unprocessable("Erlaubt sind PDF, PNG, JPEG und WebP.")
|
||||
|
||||
|
||||
def asset_path(media_root: str, asset_id: UUID) -> Path:
|
||||
root = Path(media_root).resolve()
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
target = (root / str(asset_id)).resolve()
|
||||
if target.parent != root:
|
||||
raise unprocessable("Ungültiger Speicherpfad.")
|
||||
return target
|
||||
|
||||
|
||||
def write_bytes(path: Path, data: bytes) -> None:
|
||||
try:
|
||||
path.write_bytes(data)
|
||||
except OSError as exc:
|
||||
raise storage_unavailable() from exc
|
||||
|
||||
|
||||
def read_bytes(path: Path) -> bytes:
|
||||
try:
|
||||
if not path.is_file():
|
||||
raise storage_unavailable()
|
||||
return path.read_bytes()
|
||||
except OSError as exc:
|
||||
raise storage_unavailable() from exc
|
||||
|
||||
|
||||
def sha256(data: bytes) -> str:
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def display_filename(name: str) -> str:
|
||||
cleaned = []
|
||||
for char in name.replace("\\", "/").split("/")[-1]:
|
||||
if char.isprintable() and char not in {'"', "\r", "\n", ":"}:
|
||||
cleaned.append(char)
|
||||
text = "".join(cleaned).strip() or "datei"
|
||||
return text[:240]
|
||||
|
||||
|
||||
def content_disposition(filename: str) -> str:
|
||||
safe = display_filename(filename).replace('"', "")
|
||||
return f'attachment; filename="{safe}"'
|
||||
@@ -0,0 +1,784 @@
|
||||
"""Use-cases for organisation, content and tracking. One transaction is the caller's."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from psycopg.types.json import Json
|
||||
|
||||
from app.access.policy import (
|
||||
Ctx,
|
||||
Rights,
|
||||
audit,
|
||||
block_unsharable_matter_elements,
|
||||
bump_version,
|
||||
can_change_status,
|
||||
case_rights,
|
||||
chapter_for,
|
||||
deadline_rights,
|
||||
display_name,
|
||||
element_rights,
|
||||
get_case,
|
||||
get_deadline,
|
||||
get_element,
|
||||
get_matter,
|
||||
get_task,
|
||||
insert_binding,
|
||||
matter_rights,
|
||||
require_case,
|
||||
require_element,
|
||||
require_matter,
|
||||
task_rights,
|
||||
)
|
||||
from app.content.documents import clean_document
|
||||
from app.core.errors import forbidden, not_found, unprocessable
|
||||
from app.core.timeutil import utcnow
|
||||
from app.media.storage import asset_path, display_filename, sha256, sniff, write_bytes
|
||||
|
||||
|
||||
def _ctx(value) -> Ctx | None:
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, Ctx):
|
||||
return value
|
||||
return Ctx(value.kind, value.id)
|
||||
|
||||
|
||||
def require_container_edit(conn, actor: UUID, target: Ctx, rights_context: Ctx | None) -> None:
|
||||
if target.kind == "case":
|
||||
if rights_context is not None and (rights_context.kind != "case" or rights_context.id != target.id):
|
||||
raise unprocessable("Der Handlungskontext passt nicht zur Akte.")
|
||||
require_case(conn, actor, target.id, "edit")
|
||||
return
|
||||
if rights_context is None or (rights_context.kind == "matter" and rights_context.id == target.id):
|
||||
require_matter(conn, actor, target.id, None, "edit")
|
||||
return
|
||||
require_matter(conn, actor, target.id, rights_context, "edit")
|
||||
|
||||
|
||||
def _placement(context: Ctx, placement: Ctx | None) -> tuple[Ctx, Ctx]:
|
||||
target = placement or context
|
||||
rights_context = None if placement is None and context.kind == "matter" else context
|
||||
if placement is None and context.kind == "matter":
|
||||
return target, None
|
||||
if placement is not None and placement.kind == "matter" and context.kind == "case":
|
||||
return placement, context
|
||||
if placement is not None and placement == context:
|
||||
return target, None if context.kind == "matter" else context
|
||||
return target, context if context.kind == "case" or placement is not None else None
|
||||
|
||||
|
||||
def create_case(conn, actor: UUID, scope_id: UUID, title: str, parent_case_id: UUID | None, rights_mode: str) -> dict:
|
||||
title = title.strip()
|
||||
if parent_case_id is None:
|
||||
row = conn.execute(
|
||||
"""
|
||||
INSERT INTO cases (
|
||||
home_scope_id, owner_subject_id, created_by, title, rights_mode
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, 'explicit')
|
||||
RETURNING *
|
||||
""",
|
||||
(scope_id, actor, actor, title),
|
||||
).fetchone()
|
||||
else:
|
||||
parent, _rights = require_case(conn, actor, parent_case_id, "edit")
|
||||
if parent["parent_case_id"] is not None:
|
||||
raise unprocessable("Im ersten Schnitt hat eine Unterakte keine weitere Unterakte.")
|
||||
if rights_mode not in {"inherit_parent", "explicit"}:
|
||||
raise unprocessable("Die Rechteart der Unterakte ist ungültig.")
|
||||
row = conn.execute(
|
||||
"""
|
||||
INSERT INTO cases (
|
||||
home_scope_id, owner_subject_id, created_by, title, parent_case_id, rights_mode
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s)
|
||||
RETURNING *
|
||||
""",
|
||||
(parent["home_scope_id"], actor, actor, title, parent["id"], rights_mode),
|
||||
).fetchone()
|
||||
audit(conn, actor, row["home_scope_id"], "case_created", "case", row["id"])
|
||||
return row
|
||||
|
||||
|
||||
def patch_case(conn, actor: UUID, case_id: UUID, expected: int, title: str | None, status: str | None) -> dict:
|
||||
case, rights = require_case(conn, actor, case_id, "edit")
|
||||
if title is None and status is None:
|
||||
raise unprocessable("Es fehlt eine Änderung.")
|
||||
if not rights.edit:
|
||||
raise forbidden()
|
||||
version = bump_version(conn, "cases", case_id, expected)
|
||||
if title is not None:
|
||||
conn.execute("UPDATE cases SET title = %s WHERE id = %s", (title.strip(), case_id))
|
||||
if status is not None:
|
||||
conn.execute("UPDATE cases SET record_status = %s WHERE id = %s", (status, case_id))
|
||||
updated = get_case(conn, case_id)
|
||||
updated["version"] = version
|
||||
return updated
|
||||
|
||||
|
||||
def create_chapter(conn, actor: UUID, kind: str, container_id: UUID, title: str, position: int | None, context: Ctx | None) -> dict:
|
||||
if kind == "case":
|
||||
container, _rights = require_case(conn, actor, container_id, "edit")
|
||||
else:
|
||||
container, _rights = require_matter(conn, actor, container_id, context, "edit")
|
||||
if position is None:
|
||||
column = "case_id" if kind == "case" else "matter_id"
|
||||
current = conn.execute(
|
||||
f"SELECT COALESCE(MAX(position), -1) + 1 AS pos FROM chapters WHERE {column} = %s",
|
||||
(container_id,),
|
||||
).fetchone()
|
||||
position = int(current["pos"])
|
||||
if kind == "case":
|
||||
row = conn.execute(
|
||||
"""
|
||||
INSERT INTO chapters (home_scope_id, case_id, title, position)
|
||||
VALUES (%s, %s, %s, %s) RETURNING *
|
||||
""",
|
||||
(container["home_scope_id"], container_id, title.strip(), position),
|
||||
).fetchone()
|
||||
else:
|
||||
row = conn.execute(
|
||||
"""
|
||||
INSERT INTO chapters (home_scope_id, matter_id, title, position)
|
||||
VALUES (%s, %s, %s, %s) RETURNING *
|
||||
""",
|
||||
(container["home_scope_id"], container_id, title.strip(), position),
|
||||
).fetchone()
|
||||
audit(conn, actor, container["home_scope_id"], "chapter_created", kind, container_id, context)
|
||||
return row
|
||||
|
||||
|
||||
def create_matter(conn, actor: UUID, scope_id: UUID, title: str, parent_matter_id: UUID | None, context: Ctx | None) -> dict:
|
||||
title = title.strip()
|
||||
if parent_matter_id is None:
|
||||
row = conn.execute(
|
||||
"""
|
||||
INSERT INTO matters (home_scope_id, owner_subject_id, created_by, title)
|
||||
VALUES (%s, %s, %s, %s) RETURNING *
|
||||
""",
|
||||
(scope_id, actor, actor, title),
|
||||
).fetchone()
|
||||
else:
|
||||
parent, _rights = require_matter(conn, actor, parent_matter_id, context, "edit")
|
||||
if parent["parent_matter_id"] is not None:
|
||||
raise unprocessable("Im ersten Schnitt hat ein Teilvorgang keinen weiteren Teilvorgang.")
|
||||
row = conn.execute(
|
||||
"""
|
||||
INSERT INTO matters (
|
||||
home_scope_id, owner_subject_id, created_by, title, parent_matter_id
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s) RETURNING *
|
||||
""",
|
||||
(parent["home_scope_id"], actor, actor, title, parent["id"]),
|
||||
).fetchone()
|
||||
audit(conn, actor, row["home_scope_id"], "matter_created", "matter", row["id"], context)
|
||||
return row
|
||||
|
||||
|
||||
def patch_matter(conn, actor: UUID, matter_id: UUID, expected: int, title: str | None, status: str | None, context: Ctx | None) -> dict:
|
||||
if title is None and status is None:
|
||||
raise unprocessable("Es fehlt eine Änderung.")
|
||||
_matter, _rights = require_matter(conn, actor, matter_id, context, "edit")
|
||||
bump_version(conn, "matters", matter_id, expected)
|
||||
if title is not None:
|
||||
conn.execute("UPDATE matters SET title = %s WHERE id = %s", (title.strip(), matter_id))
|
||||
if status is not None:
|
||||
conn.execute("UPDATE matters SET record_status = %s WHERE id = %s", (status, matter_id))
|
||||
return get_matter(conn, matter_id)
|
||||
|
||||
|
||||
def link_matter_to_case(conn, actor: UUID, matter_id: UUID, case_id: UUID, matter_context: Ctx | None) -> dict:
|
||||
matter, matter_right = require_matter(conn, actor, matter_id, matter_context, "share")
|
||||
case, _case_right = require_case(conn, actor, case_id, "edit")
|
||||
if not matter_right.share:
|
||||
raise forbidden()
|
||||
try:
|
||||
link = conn.execute(
|
||||
"""
|
||||
INSERT INTO matter_case_links (matter_id, case_id, created_by)
|
||||
VALUES (%s, %s, %s) RETURNING *
|
||||
""",
|
||||
(matter["id"], case["id"], actor),
|
||||
).fetchone()
|
||||
except Exception as exc:
|
||||
if exc.__class__.__name__ == "UniqueViolation":
|
||||
raise unprocessable("Der Vorgang ist dieser Akte bereits zugeordnet.") from exc
|
||||
raise
|
||||
block_unsharable_matter_elements(conn, actor, link["id"], matter)
|
||||
audit(conn, actor, case["home_scope_id"], "matter_linked", "matter", matter["id"], Ctx("case", case["id"]))
|
||||
return link
|
||||
|
||||
|
||||
def unlink_matter_case(conn, actor: UUID, link_id: UUID) -> None:
|
||||
link = conn.execute("SELECT * FROM matter_case_links WHERE id = %s", (link_id,)).fetchone()
|
||||
if link is None:
|
||||
raise not_found()
|
||||
matter_direct = matter_rights(conn, actor, get_matter(conn, link["matter_id"]), None)
|
||||
case_right = case_rights(conn, actor, get_case(conn, link["case_id"]))
|
||||
if not case_right.read and not matter_direct.read:
|
||||
raise not_found()
|
||||
if not case_right.edit and not matter_direct.share:
|
||||
raise forbidden()
|
||||
conn.execute("DELETE FROM matter_case_links WHERE id = %s", (link_id,))
|
||||
audit(conn, actor, None, "matter_unlinked", "matter", link["matter_id"], Ctx("case", link["case_id"]))
|
||||
|
||||
|
||||
def create_cross_link(conn, actor: UUID, source_id: UUID, target_id: UUID, source_context: Ctx | None, target_context: Ctx) -> dict:
|
||||
if source_id == target_id:
|
||||
raise unprocessable("Ein Vorgang kann nicht auf sich selbst verweisen.")
|
||||
source, _rights = require_matter(conn, actor, source_id, source_context, "edit")
|
||||
target, target_rights = require_matter(conn, actor, target_id, target_context, "read")
|
||||
if not target_rights.read:
|
||||
raise not_found()
|
||||
try:
|
||||
row = conn.execute(
|
||||
"""
|
||||
INSERT INTO matter_cross_links (from_matter_id, to_matter_id, created_by)
|
||||
VALUES (%s, %s, %s) RETURNING *
|
||||
""",
|
||||
(source["id"], target["id"], actor),
|
||||
).fetchone()
|
||||
except Exception as exc:
|
||||
if exc.__class__.__name__ == "UniqueViolation":
|
||||
raise unprocessable("Dieser Querverweis besteht bereits.") from exc
|
||||
raise
|
||||
audit(conn, actor, source["home_scope_id"], "cross_linked", "matter", source["id"], source_context)
|
||||
return row
|
||||
|
||||
|
||||
def delete_cross_link(conn, actor: UUID, link_id: UUID, source_context: Ctx | None) -> None:
|
||||
link = conn.execute("SELECT * FROM matter_cross_links WHERE id = %s", (link_id,)).fetchone()
|
||||
if link is None:
|
||||
raise not_found()
|
||||
require_matter(conn, actor, link["from_matter_id"], source_context, "edit")
|
||||
conn.execute("DELETE FROM matter_cross_links WHERE id = %s", (link_id,))
|
||||
|
||||
|
||||
def _actor_rights_for(conn, actor: UUID, kind: str, resource_id: UUID, context: Ctx | None) -> Rights:
|
||||
if kind == "case":
|
||||
_row, rights = require_case(conn, actor, resource_id, "read")
|
||||
return rights
|
||||
if kind == "matter":
|
||||
_row, rights = require_matter(conn, actor, resource_id, context, "read")
|
||||
return rights
|
||||
if kind == "element":
|
||||
_row, rights = require_element(conn, actor, resource_id, context, "read")
|
||||
return rights
|
||||
if kind == "task":
|
||||
task = get_task(conn, resource_id)
|
||||
if task is None:
|
||||
raise not_found()
|
||||
rights = task_rights(conn, actor, task, context)
|
||||
if not rights.read:
|
||||
raise not_found()
|
||||
return rights
|
||||
deadline = get_deadline(conn, resource_id)
|
||||
if deadline is None:
|
||||
raise not_found()
|
||||
rights = deadline_rights(conn, actor, deadline, context)
|
||||
if not rights.read:
|
||||
raise not_found()
|
||||
return rights
|
||||
|
||||
|
||||
def grant_access(conn, actor: UUID, kind: str, resource_id: UUID, grantee_id: UUID, can_read: bool, can_edit: bool, can_share: bool, context: Ctx | None) -> dict:
|
||||
if grantee_id == actor:
|
||||
raise unprocessable("Die eigene Berechtigung wird nicht als Freigabe gespeichert.")
|
||||
if not can_read:
|
||||
raise unprocessable("Eine Freigabe braucht mindestens Lesen.")
|
||||
if kind == "case":
|
||||
resource = get_case(conn, resource_id)
|
||||
rights = case_rights(conn, actor, resource) if resource else Rights()
|
||||
elif kind == "matter":
|
||||
resource = get_matter(conn, resource_id)
|
||||
rights = matter_rights(conn, actor, resource, context) if resource else Rights()
|
||||
else:
|
||||
raise unprocessable("Freigaben werden an der Akte oder am Vorgang erteilt.")
|
||||
if resource is None or not rights.read:
|
||||
raise not_found()
|
||||
owner = resource["owner_subject_id"] == actor
|
||||
if not owner and not rights.share:
|
||||
raise forbidden()
|
||||
if can_edit and not (owner or rights.edit):
|
||||
raise forbidden()
|
||||
if can_share and not (owner or rights.share):
|
||||
raise forbidden()
|
||||
account = conn.execute(
|
||||
"SELECT id FROM auth_accounts WHERE id = %s AND status = 'active'",
|
||||
(grantee_id,),
|
||||
).fetchone()
|
||||
if account is None:
|
||||
raise not_found()
|
||||
existing = conn.execute(
|
||||
"""
|
||||
SELECT id FROM access_grants
|
||||
WHERE NOT is_exception AND grantee_subject_id = %s
|
||||
AND resource_kind = %s AND resource_id = %s AND context_kind IS NULL
|
||||
""",
|
||||
(grantee_id, kind, resource_id),
|
||||
).fetchone()
|
||||
if existing is None:
|
||||
row = conn.execute(
|
||||
"""
|
||||
INSERT INTO access_grants (
|
||||
grantee_subject_id, resource_kind, resource_id,
|
||||
can_read, can_edit, can_share, can_delete, is_exception, created_by
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, false, false, %s)
|
||||
RETURNING *
|
||||
""",
|
||||
(grantee_id, kind, resource_id, can_read, can_edit, can_share, actor),
|
||||
).fetchone()
|
||||
else:
|
||||
row = conn.execute(
|
||||
"""
|
||||
UPDATE access_grants
|
||||
SET can_read = %s, can_edit = %s, can_share = %s
|
||||
WHERE id = %s
|
||||
RETURNING *
|
||||
""",
|
||||
(can_read, can_edit, can_share, existing["id"]),
|
||||
).fetchone()
|
||||
audit(conn, actor, resource["home_scope_id"], "grant_created", kind, resource_id, context)
|
||||
return row
|
||||
|
||||
|
||||
def revoke_grant(conn, actor: UUID, grant_id: UUID) -> None:
|
||||
grant = conn.execute("SELECT * FROM access_grants WHERE id = %s AND NOT is_exception", (grant_id,)).fetchone()
|
||||
if grant is None:
|
||||
raise not_found()
|
||||
kind = grant["resource_kind"]
|
||||
if kind == "case":
|
||||
resource = get_case(conn, grant["resource_id"])
|
||||
rights = case_rights(conn, actor, resource) if resource else Rights()
|
||||
elif kind == "matter":
|
||||
resource = get_matter(conn, grant["resource_id"])
|
||||
rights = matter_rights(conn, actor, resource, None) if resource else Rights()
|
||||
elif kind == "task":
|
||||
resource = get_task(conn, grant["resource_id"])
|
||||
rights = task_rights(conn, actor, resource, None) if resource else Rights()
|
||||
elif kind == "deadline":
|
||||
resource = get_deadline(conn, grant["resource_id"])
|
||||
rights = deadline_rights(conn, actor, resource, None) if resource else Rights()
|
||||
else:
|
||||
resource = get_element(conn, grant["resource_id"])
|
||||
rights = element_rights(conn, actor, resource, None) if resource else Rights()
|
||||
if resource is None or not rights.read:
|
||||
raise not_found()
|
||||
if resource["owner_subject_id"] != actor and not rights.share:
|
||||
raise forbidden()
|
||||
conn.execute("DELETE FROM access_grants WHERE id = %s", (grant_id,))
|
||||
audit(conn, actor, resource["home_scope_id"], "grant_revoked", kind, grant["resource_id"])
|
||||
|
||||
|
||||
def set_exception(conn, actor: UUID, kind: str, resource_id: UUID, context: Ctx, remove_read: bool, remove_edit: bool, remove_share: bool) -> None:
|
||||
if kind == "element":
|
||||
resource = get_element(conn, resource_id)
|
||||
elif kind == "matter":
|
||||
resource = get_matter(conn, resource_id)
|
||||
elif kind == "task":
|
||||
resource = get_task(conn, resource_id)
|
||||
else:
|
||||
resource = get_deadline(conn, resource_id)
|
||||
if resource is None:
|
||||
raise not_found()
|
||||
if resource["owner_subject_id"] != actor:
|
||||
raise forbidden()
|
||||
conn.execute(
|
||||
"""
|
||||
DELETE FROM access_grants
|
||||
WHERE is_exception AND grantee_subject_id IS NULL
|
||||
AND resource_kind = %s AND resource_id = %s
|
||||
AND context_kind = %s AND context_id = %s
|
||||
""",
|
||||
(kind, resource_id, context.kind, context.id),
|
||||
)
|
||||
if remove_read or remove_edit or remove_share:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO access_grants (
|
||||
grantee_subject_id, resource_kind, resource_id, context_kind, context_id,
|
||||
can_read, can_edit, can_share, can_delete, is_exception, created_by
|
||||
)
|
||||
VALUES (NULL, %s, %s, %s, %s, %s, %s, %s, false, true, %s)
|
||||
""",
|
||||
(kind, resource_id, context.kind, context.id, remove_read, remove_edit, remove_share, actor),
|
||||
)
|
||||
|
||||
|
||||
def _new_element(conn, actor: UUID, scope_id: UUID, title: str, kind: str) -> dict:
|
||||
return conn.execute(
|
||||
"""
|
||||
INSERT INTO elements (home_scope_id, owner_subject_id, created_by, title, kind)
|
||||
VALUES (%s, %s, %s, %s, %s) RETURNING *
|
||||
""",
|
||||
(scope_id, actor, actor, title.strip(), kind),
|
||||
).fetchone()
|
||||
|
||||
|
||||
def record_dates(conn, actor: UUID, scope_id: UUID, element_id: UUID, context: Ctx, document_on: date | None, sent_on: date | None, received_on: date | None) -> None:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO correspondence_dates (element_id, document_on, sent_on, received_on)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
ON CONFLICT (element_id) DO UPDATE
|
||||
SET document_on = EXCLUDED.document_on,
|
||||
sent_on = EXCLUDED.sent_on,
|
||||
received_on = EXCLUDED.received_on
|
||||
""",
|
||||
(element_id, document_on, sent_on, received_on),
|
||||
)
|
||||
if document_on is not None:
|
||||
audit(conn, actor, scope_id, "correspondence_document", "element", element_id, context, document_on)
|
||||
if sent_on is not None:
|
||||
audit(conn, actor, scope_id, "correspondence_sent", "element", element_id, context, sent_on)
|
||||
if received_on is not None:
|
||||
audit(conn, actor, scope_id, "correspondence_received", "element", element_id, context, received_on)
|
||||
audit(conn, actor, scope_id, "correspondence_recorded", "element", element_id, context)
|
||||
|
||||
|
||||
def create_note(conn, actor: UUID, scope_id: UUID, title: str, document: dict, context: Ctx, placement: Ctx | None, chapter_id: UUID | None) -> dict:
|
||||
document = clean_document(document)
|
||||
target, rights_context = _placement(context, placement)
|
||||
require_container_edit(conn, actor, target, rights_context)
|
||||
element = _new_element(conn, actor, scope_id, title, "note")
|
||||
conn.execute(
|
||||
"INSERT INTO note_bodies (element_id, document_json, version) VALUES (%s, %s, 1)",
|
||||
(element["id"], Json(document)),
|
||||
)
|
||||
binding = insert_binding(conn, element["id"], target.kind, target.id, chapter_id, actor)
|
||||
audit(conn, actor, scope_id, "note_created", "element", element["id"], rights_context or target)
|
||||
return {"element": element, "binding": binding, "document": document}
|
||||
|
||||
|
||||
def update_note(conn, actor: UUID, element_id: UUID, expected: int, document: dict, context: Ctx | None) -> dict:
|
||||
document = clean_document(document)
|
||||
element, rights = require_element(conn, actor, element_id, context, "edit")
|
||||
if element["kind"] != "note":
|
||||
raise not_found()
|
||||
if not rights.edit:
|
||||
raise forbidden()
|
||||
version = bump_version(conn, "elements", element_id, expected)
|
||||
conn.execute(
|
||||
"UPDATE note_bodies SET document_json = %s, version = %s, updated_at = now() WHERE element_id = %s",
|
||||
(Json(document), version, element_id),
|
||||
)
|
||||
audit(conn, actor, element["home_scope_id"], "note_updated", "element", element_id, context)
|
||||
element = get_element(conn, element_id)
|
||||
return {"element": element, "document": document}
|
||||
|
||||
|
||||
def bind_element(conn, actor: UUID, element_id: UUID, source: Ctx, target: Ctx, target_context: Ctx | None, chapter_id: UUID | None) -> dict:
|
||||
_element, source_rights = require_element(conn, actor, element_id, source, "share")
|
||||
if not source_rights.share:
|
||||
raise forbidden()
|
||||
require_container_edit(conn, actor, target, target_context)
|
||||
binding = insert_binding(conn, element_id, target.kind, target.id, chapter_id, actor)
|
||||
audit(conn, actor, None, "binding_created", "element", element_id, target_context or target)
|
||||
return binding
|
||||
|
||||
|
||||
def detach_binding(conn, actor: UUID, binding_id: UUID, context: Ctx | None) -> None:
|
||||
binding = conn.execute("SELECT * FROM bindings WHERE id = %s", (binding_id,)).fetchone()
|
||||
if binding is None:
|
||||
raise not_found()
|
||||
element = get_element(conn, binding["element_id"])
|
||||
if element is None:
|
||||
raise not_found()
|
||||
action_context = context or Ctx(binding["context_kind"], binding["context_id"])
|
||||
_element, rights = require_element(conn, actor, element["id"], action_context, "edit")
|
||||
if binding["context_kind"] != action_context.kind and not (
|
||||
action_context.kind == "case" and binding["context_kind"] == "matter"
|
||||
):
|
||||
raise not_found()
|
||||
if not rights.edit:
|
||||
raise forbidden()
|
||||
conn.execute("DELETE FROM bindings WHERE id = %s", (binding_id,))
|
||||
audit(conn, actor, element["home_scope_id"], "binding_removed", "element", element["id"], action_context)
|
||||
|
||||
|
||||
def add_annotation(conn, actor: UUID, binding_id: UUID, body: str, context: Ctx | None) -> dict:
|
||||
binding = conn.execute("SELECT * FROM bindings WHERE id = %s", (binding_id,)).fetchone()
|
||||
if binding is None:
|
||||
raise not_found()
|
||||
element = get_element(conn, binding["element_id"])
|
||||
if element is None:
|
||||
raise not_found()
|
||||
action_context = context or Ctx(binding["context_kind"], binding["context_id"])
|
||||
_element, rights = require_element(conn, actor, element["id"], action_context, "edit")
|
||||
if not rights.edit:
|
||||
raise forbidden()
|
||||
if binding["context_id"] != action_context.id and not (
|
||||
action_context.kind == "case" and binding["context_kind"] == "matter"
|
||||
):
|
||||
raise not_found()
|
||||
row = conn.execute(
|
||||
"""
|
||||
INSERT INTO context_annotations (binding_id, body, author_subject_id)
|
||||
VALUES (%s, %s, %s) RETURNING *
|
||||
""",
|
||||
(binding_id, body.strip(), actor),
|
||||
).fetchone()
|
||||
audit(conn, actor, element["home_scope_id"], "annotation_created", "element", element["id"], action_context)
|
||||
return row
|
||||
|
||||
|
||||
def create_external(conn, actor: UUID, scope_id: UUID, title: str, source: str, external_id: str, context: Ctx, placement: Ctx | None, chapter_id: UUID | None, document_on, sent_on, received_on) -> dict:
|
||||
target, rights_context = _placement(context, placement)
|
||||
require_container_edit(conn, actor, target, rights_context)
|
||||
element = _new_element(conn, actor, scope_id, title, "external_ref")
|
||||
conn.execute(
|
||||
"INSERT INTO external_references (element_id, source, external_id) VALUES (%s, %s, %s)",
|
||||
(element["id"], source, external_id.strip()),
|
||||
)
|
||||
binding = insert_binding(conn, element["id"], target.kind, target.id, chapter_id, actor)
|
||||
record_dates(conn, actor, scope_id, element["id"], rights_context or target, document_on, sent_on, received_on)
|
||||
audit(conn, actor, scope_id, "external_ref_added", "element", element["id"], rights_context or target)
|
||||
return element | {"binding_id": binding["id"]}
|
||||
|
||||
|
||||
def create_file(conn, actor: UUID, scope_id: UUID, title: str, filename: str, data: bytes, context: Ctx, placement: Ctx | None, chapter_id: UUID | None, document_on, sent_on, received_on, media_root: str, max_bytes: int, rollback_files: list[Path]) -> dict:
|
||||
if not data or len(data) > max_bytes:
|
||||
raise unprocessable("Die Datei ist leer oder zu groß.")
|
||||
content_type = sniff(data)
|
||||
target, rights_context = _placement(context, placement)
|
||||
require_container_edit(conn, actor, target, rights_context)
|
||||
element = _new_element(conn, actor, scope_id, title, "file")
|
||||
asset_id = uuid4()
|
||||
path = asset_path(media_root, asset_id)
|
||||
write_bytes(path, data)
|
||||
rollback_files.append(path)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO media_assets (
|
||||
id, element_id, owner_subject_id, home_scope_id, original_filename,
|
||||
content_type, byte_size, sha256, status
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, 'active')
|
||||
""",
|
||||
(
|
||||
asset_id,
|
||||
element["id"],
|
||||
actor,
|
||||
scope_id,
|
||||
display_filename(filename),
|
||||
content_type,
|
||||
len(data),
|
||||
sha256(data),
|
||||
),
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO media_operations (element_id, asset_id, phase, status)
|
||||
VALUES (%s, %s, 'active', 'committed')
|
||||
""",
|
||||
(element["id"], asset_id),
|
||||
)
|
||||
binding = insert_binding(conn, element["id"], target.kind, target.id, chapter_id, actor)
|
||||
record_dates(conn, actor, scope_id, element["id"], rights_context or target, document_on, sent_on, received_on)
|
||||
audit(conn, actor, scope_id, "file_added", "element", element["id"], rights_context or target)
|
||||
return element | {"binding_id": binding["id"], "asset_id": asset_id}
|
||||
|
||||
|
||||
def delete_element(conn, actor: UUID, element_id: UUID, expected: int, media_root: str, delete_after: list[Path]) -> None:
|
||||
element = get_element(conn, element_id)
|
||||
if element is None or element["owner_subject_id"] != actor:
|
||||
raise not_found()
|
||||
bump_version(conn, "elements", element_id, expected)
|
||||
asset = conn.execute("SELECT * FROM media_assets WHERE element_id = %s", (element_id,)).fetchone()
|
||||
conn.execute("DELETE FROM bindings WHERE element_id = %s", (element_id,))
|
||||
conn.execute(
|
||||
"UPDATE elements SET deleted_at = now(), updated_at = now() WHERE id = %s",
|
||||
(element_id,),
|
||||
)
|
||||
if asset is not None and asset["status"] == "active":
|
||||
conn.execute("UPDATE media_assets SET status = 'purging' WHERE id = %s", (asset["id"],))
|
||||
delete_after.append(asset_path(media_root, asset["id"]))
|
||||
conn.execute("UPDATE media_assets SET status = 'purged' WHERE id = %s", (asset["id"],))
|
||||
audit(conn, actor, element["home_scope_id"], "element_deleted", "element", element_id)
|
||||
|
||||
|
||||
def create_task(conn, actor: UUID, scope_id: UUID, title: str, due_on: date | None, matter_id: UUID | None, context: Ctx | None) -> dict:
|
||||
if matter_id is not None:
|
||||
require_matter(conn, actor, matter_id, context, "edit")
|
||||
row = conn.execute(
|
||||
"""
|
||||
INSERT INTO tasks (
|
||||
home_scope_id, owner_subject_id, created_by, title, matter_id, due_on
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s) RETURNING *
|
||||
""",
|
||||
(scope_id, actor, actor, title.strip(), matter_id, due_on),
|
||||
).fetchone()
|
||||
audit(conn, actor, scope_id, "task_created", "task", row["id"], context)
|
||||
return row
|
||||
|
||||
|
||||
def patch_task(conn, actor: UUID, task_id: UUID, expected: int, title: str | None, due_on: date | None, clear_due: bool, status: str | None, context: Ctx | None) -> dict:
|
||||
task = get_task(conn, task_id)
|
||||
if task is None:
|
||||
raise not_found()
|
||||
rights = task_rights(conn, actor, task, context)
|
||||
if not rights.read:
|
||||
raise not_found()
|
||||
structural = title is not None or due_on is not None or clear_due
|
||||
if structural and not rights.edit:
|
||||
raise forbidden()
|
||||
if status is not None and not can_change_status(actor, task, rights):
|
||||
raise forbidden()
|
||||
if title is None and due_on is None and not clear_due and status is None:
|
||||
raise unprocessable("Es fehlt eine Änderung.")
|
||||
bump_version(conn, "tasks", task_id, expected)
|
||||
if title is not None:
|
||||
conn.execute("UPDATE tasks SET title = %s WHERE id = %s", (title.strip(), task_id))
|
||||
if clear_due:
|
||||
conn.execute("UPDATE tasks SET due_on = NULL WHERE id = %s", (task_id,))
|
||||
elif due_on is not None:
|
||||
conn.execute("UPDATE tasks SET due_on = %s WHERE id = %s", (due_on, task_id))
|
||||
if status is not None:
|
||||
conn.execute("UPDATE tasks SET task_status = %s WHERE id = %s", (status, task_id))
|
||||
audit(
|
||||
conn,
|
||||
actor,
|
||||
task["home_scope_id"],
|
||||
"task_done" if status == "done" else "task_reopened",
|
||||
"task",
|
||||
task_id,
|
||||
context,
|
||||
)
|
||||
return get_task(conn, task_id)
|
||||
|
||||
|
||||
def assign_task(conn, actor: UUID, task_id: UUID, assignee_id: UUID | None, context: Ctx | None) -> dict:
|
||||
task = get_task(conn, task_id)
|
||||
if task is None:
|
||||
raise not_found()
|
||||
rights = task_rights(conn, actor, task, context)
|
||||
if not rights.read:
|
||||
raise not_found()
|
||||
if task["owner_subject_id"] != actor and not rights.share:
|
||||
raise forbidden()
|
||||
if assignee_id is not None:
|
||||
account = conn.execute(
|
||||
"SELECT id FROM auth_accounts WHERE id = %s AND status = 'active'",
|
||||
(assignee_id,),
|
||||
).fetchone()
|
||||
if account is None:
|
||||
raise not_found()
|
||||
existing = conn.execute(
|
||||
"""
|
||||
SELECT * FROM access_grants
|
||||
WHERE NOT is_exception AND grantee_subject_id = %s
|
||||
AND resource_kind = 'task' AND resource_id = %s AND context_kind IS NULL
|
||||
""",
|
||||
(assignee_id, task_id),
|
||||
).fetchone()
|
||||
if existing is None:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO access_grants (
|
||||
grantee_subject_id, resource_kind, resource_id,
|
||||
can_read, can_edit, can_share, can_delete, is_exception, created_by
|
||||
)
|
||||
VALUES (%s, 'task', %s, true, false, false, false, false, %s)
|
||||
""",
|
||||
(assignee_id, task_id, actor),
|
||||
)
|
||||
elif not existing["can_read"]:
|
||||
conn.execute("UPDATE access_grants SET can_read = true WHERE id = %s", (existing["id"],))
|
||||
elif task["assignee_subject_id"] is not None:
|
||||
conn.execute(
|
||||
"""
|
||||
DELETE FROM access_grants
|
||||
WHERE NOT is_exception AND grantee_subject_id = %s
|
||||
AND resource_kind = 'task' AND resource_id = %s
|
||||
AND context_kind IS NULL AND can_read AND NOT can_edit AND NOT can_share AND NOT can_delete
|
||||
""",
|
||||
(task["assignee_subject_id"], task_id),
|
||||
)
|
||||
conn.execute(
|
||||
"UPDATE tasks SET assignee_subject_id = %s, updated_at = now() WHERE id = %s",
|
||||
(assignee_id, task_id),
|
||||
)
|
||||
return get_task(conn, task_id)
|
||||
|
||||
|
||||
def create_deadline(conn, actor: UUID, scope_id: UUID, title: str, due_on: date, matter_id: UUID | None, context: Ctx | None) -> dict:
|
||||
if matter_id is not None:
|
||||
require_matter(conn, actor, matter_id, context, "edit")
|
||||
row = conn.execute(
|
||||
"""
|
||||
INSERT INTO deadlines (
|
||||
home_scope_id, owner_subject_id, created_by, title, matter_id, due_on
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s) RETURNING *
|
||||
""",
|
||||
(scope_id, actor, actor, title.strip(), matter_id, due_on),
|
||||
).fetchone()
|
||||
audit(conn, actor, scope_id, "deadline_created", "deadline", row["id"], context)
|
||||
return row
|
||||
|
||||
|
||||
def patch_deadline(conn, actor: UUID, deadline_id: UUID, expected: int, title: str | None, due_on: date | None, context: Ctx | None) -> dict:
|
||||
deadline = get_deadline(conn, deadline_id)
|
||||
if deadline is None:
|
||||
raise not_found()
|
||||
rights = deadline_rights(conn, actor, deadline, context)
|
||||
if not rights.read:
|
||||
raise not_found()
|
||||
if not rights.edit:
|
||||
raise forbidden()
|
||||
if title is None and due_on is None:
|
||||
raise unprocessable("Es fehlt eine Änderung.")
|
||||
bump_version(conn, "deadlines", deadline_id, expected)
|
||||
if title is not None:
|
||||
conn.execute("UPDATE deadlines SET title = %s WHERE id = %s", (title.strip(), deadline_id))
|
||||
if due_on is not None:
|
||||
conn.execute("UPDATE deadlines SET due_on = %s WHERE id = %s", (due_on, deadline_id))
|
||||
return get_deadline(conn, deadline_id)
|
||||
|
||||
|
||||
def fulfill_deadline(conn, actor: UUID, deadline_id: UUID, expected: int, context: Ctx | None) -> dict:
|
||||
deadline = get_deadline(conn, deadline_id)
|
||||
if deadline is None:
|
||||
raise not_found()
|
||||
rights = deadline_rights(conn, actor, deadline, context)
|
||||
if not rights.read:
|
||||
raise not_found()
|
||||
if not can_change_status(actor, deadline, rights):
|
||||
raise forbidden()
|
||||
bump_version(conn, "deadlines", deadline_id, expected)
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE deadlines
|
||||
SET deadline_status = 'fulfilled', fulfilled_at = %s, updated_at = now()
|
||||
WHERE id = %s
|
||||
""",
|
||||
(utcnow(), deadline_id),
|
||||
)
|
||||
audit(conn, actor, deadline["home_scope_id"], "deadline_fulfilled", "deadline", deadline_id, context)
|
||||
return get_deadline(conn, deadline_id)
|
||||
|
||||
|
||||
def link_task_deadline(conn, actor: UUID, task_id: UUID, deadline_id: UUID, context: Ctx | None) -> None:
|
||||
task = get_task(conn, task_id)
|
||||
deadline = get_deadline(conn, deadline_id)
|
||||
if task is None or deadline is None:
|
||||
raise not_found()
|
||||
task_right = task_rights(conn, actor, task, context)
|
||||
deadline_right = deadline_rights(conn, actor, deadline, context)
|
||||
if not task_right.read or not deadline_right.read:
|
||||
raise not_found()
|
||||
if not task_right.edit:
|
||||
raise forbidden()
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO task_deadline_links (task_id, deadline_id, created_by)
|
||||
VALUES (%s, %s, %s)
|
||||
ON CONFLICT DO NOTHING
|
||||
""",
|
||||
(task_id, deadline_id, actor),
|
||||
)
|
||||
@@ -0,0 +1,490 @@
|
||||
"""Response shapes. Hidden objects are omitted, not counted and not titled."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from uuid import UUID
|
||||
|
||||
from app.access.policy import (
|
||||
Ctx,
|
||||
case_rights,
|
||||
deadline_rights,
|
||||
display_name,
|
||||
element_rights,
|
||||
get_case,
|
||||
get_element,
|
||||
get_matter,
|
||||
matter_rights,
|
||||
matter_title_if_readable,
|
||||
readable_matter_contexts,
|
||||
room_name,
|
||||
task_rights,
|
||||
visible_bindings_for_element,
|
||||
)
|
||||
from app.access.policy import SHARED_NOTICE
|
||||
from app.core.timeutil import dump_date, dump_dt
|
||||
|
||||
|
||||
def rights_dict(rights) -> dict:
|
||||
return rights.as_dict()
|
||||
|
||||
|
||||
def _chapters(conn, kind: str, container_id: UUID) -> list[dict]:
|
||||
column = "case_id" if kind == "case" else "matter_id"
|
||||
rows = conn.execute(
|
||||
f"SELECT id, title, position FROM chapters WHERE {column} = %s ORDER BY position, created_at",
|
||||
(container_id,),
|
||||
).fetchall()
|
||||
return [{"id": str(row["id"]), "title": row["title"], "position": row["position"]} for row in rows]
|
||||
|
||||
|
||||
def _annotations(conn, binding_id: UUID) -> list[dict]:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT a.id, a.body, a.created_at, p.display_name
|
||||
FROM context_annotations a
|
||||
JOIN auth_accounts p ON p.id = a.author_subject_id
|
||||
WHERE a.binding_id = %s
|
||||
ORDER BY a.created_at, a.id
|
||||
""",
|
||||
(binding_id,),
|
||||
).fetchall()
|
||||
return [
|
||||
{
|
||||
"id": str(row["id"]),
|
||||
"body": row["body"],
|
||||
"author_display_name": row["display_name"],
|
||||
"created_at": dump_dt(row["created_at"]),
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
|
||||
|
||||
def _dates(conn, element: dict) -> dict:
|
||||
row = conn.execute(
|
||||
"SELECT document_on, sent_on, received_on FROM correspondence_dates WHERE element_id = %s",
|
||||
(element["id"],),
|
||||
).fetchone()
|
||||
return {
|
||||
"document_on": dump_date(row["document_on"]) if row else None,
|
||||
"sent_on": dump_date(row["sent_on"]) if row else None,
|
||||
"received_on": dump_date(row["received_on"]) if row else None,
|
||||
"recorded_at": dump_dt(element["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def _element_body(conn, element: dict) -> dict:
|
||||
payload = {
|
||||
"id": str(element["id"]),
|
||||
"kind": element["kind"],
|
||||
"title": element["title"],
|
||||
"version": element["version"],
|
||||
"owner_subject_id": str(element["owner_subject_id"]),
|
||||
"dates": _dates(conn, element),
|
||||
}
|
||||
if element["kind"] == "note":
|
||||
body = conn.execute(
|
||||
"SELECT document_json FROM note_bodies WHERE element_id = %s",
|
||||
(element["id"],),
|
||||
).fetchone()
|
||||
payload["document"] = body["document_json"] if body else {"version": 1, "blocks": []}
|
||||
elif element["kind"] == "file":
|
||||
asset = conn.execute(
|
||||
"""
|
||||
SELECT original_filename, content_type, byte_size, status
|
||||
FROM media_assets WHERE element_id = %s
|
||||
""",
|
||||
(element["id"],),
|
||||
).fetchone()
|
||||
if asset is not None:
|
||||
payload["file"] = {
|
||||
"filename": asset["original_filename"],
|
||||
"content_type": asset["content_type"],
|
||||
"byte_size": asset["byte_size"],
|
||||
"status": asset["status"],
|
||||
}
|
||||
elif element["kind"] == "external_ref":
|
||||
ref = conn.execute(
|
||||
"SELECT source, external_id FROM external_references WHERE element_id = %s",
|
||||
(element["id"],),
|
||||
).fetchone()
|
||||
if ref is not None:
|
||||
payload["external"] = {"source": ref["source"], "external_id": ref["external_id"]}
|
||||
return payload
|
||||
|
||||
|
||||
def _exception(conn, kind: str, resource_id: UUID, context: Ctx | None) -> dict | None:
|
||||
if context is None:
|
||||
return None
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT can_read, can_edit, can_share
|
||||
FROM access_grants
|
||||
WHERE is_exception AND grantee_subject_id IS NULL
|
||||
AND resource_kind = %s AND resource_id = %s
|
||||
AND context_kind = %s AND context_id = %s
|
||||
""",
|
||||
(kind, resource_id, context.kind, context.id),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return {"remove_read": False, "remove_edit": False, "remove_share": False}
|
||||
return {"remove_read": row["can_read"], "remove_edit": row["can_edit"], "remove_share": row["can_share"]}
|
||||
|
||||
|
||||
def binding_payload(conn, actor: UUID, binding: dict, context: Ctx) -> dict | None:
|
||||
element = get_element(conn, binding["element_id"])
|
||||
if element is None:
|
||||
return None
|
||||
rights = element_rights(conn, actor, element, context)
|
||||
if not rights.read:
|
||||
return None
|
||||
payload = {
|
||||
"id": str(binding["id"]),
|
||||
"position": binding["position"],
|
||||
"chapter_id": str(binding["chapter_id"]) if binding["chapter_id"] else None,
|
||||
"rights": rights.as_dict(),
|
||||
"annotations": _annotations(conn, binding["id"]),
|
||||
"element": _element_body(conn, element),
|
||||
}
|
||||
if element["owner_subject_id"] == actor:
|
||||
payload["exception"] = _exception(conn, "element", element["id"], context)
|
||||
return payload
|
||||
|
||||
|
||||
def _grants(conn, kind: str, resource_id: UUID) -> list[dict]:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT g.id, g.grantee_subject_id, g.can_read, g.can_edit, g.can_share, a.email, a.display_name
|
||||
FROM access_grants g
|
||||
JOIN auth_accounts a ON a.id = g.grantee_subject_id
|
||||
WHERE NOT g.is_exception AND g.resource_kind = %s AND g.resource_id = %s AND g.context_kind IS NULL
|
||||
ORDER BY a.display_name, g.id
|
||||
""",
|
||||
(kind, resource_id),
|
||||
).fetchall()
|
||||
return [
|
||||
{
|
||||
"id": str(row["id"]),
|
||||
"grantee_subject_id": str(row["grantee_subject_id"]),
|
||||
"email": row["email"],
|
||||
"display_name": row["display_name"],
|
||||
"can_read": row["can_read"],
|
||||
"can_edit": row["can_edit"],
|
||||
"can_share": row["can_share"],
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
|
||||
|
||||
def case_summary(case: dict, rights) -> dict:
|
||||
return {
|
||||
"id": str(case["id"]),
|
||||
"title": case["title"],
|
||||
"status": case["record_status"],
|
||||
"version": case["version"],
|
||||
"rights_mode": case["rights_mode"],
|
||||
"parent_case_id": str(case["parent_case_id"]) if case["parent_case_id"] else None,
|
||||
"home_scope_id": str(case["home_scope_id"]),
|
||||
"rights": rights.as_dict(),
|
||||
}
|
||||
|
||||
|
||||
def case_detail(conn, actor: UUID, case: dict, rights) -> dict:
|
||||
payload = case_summary(case, rights)
|
||||
payload["home_scope_name"] = room_name(conn, case["home_scope_id"])
|
||||
payload["is_owner"] = case["owner_subject_id"] == actor
|
||||
payload["chapters"] = _chapters(conn, "case", case["id"])
|
||||
subcases = []
|
||||
for row in conn.execute(
|
||||
"""
|
||||
SELECT * FROM cases
|
||||
WHERE parent_case_id = %s AND deleted_at IS NULL
|
||||
ORDER BY title, id
|
||||
""",
|
||||
(case["id"],),
|
||||
).fetchall():
|
||||
child_rights = case_rights(conn, actor, row)
|
||||
if child_rights.read:
|
||||
subcases.append(case_summary(row, child_rights))
|
||||
payload["subcases"] = subcases
|
||||
matters = []
|
||||
for link in conn.execute(
|
||||
"""
|
||||
SELECT l.id AS link_id, m.*
|
||||
FROM matter_case_links l
|
||||
JOIN matters m ON m.id = l.matter_id
|
||||
WHERE l.case_id = %s AND m.deleted_at IS NULL
|
||||
ORDER BY m.title, m.id
|
||||
""",
|
||||
(case["id"],),
|
||||
).fetchall():
|
||||
matter_right = matter_rights(conn, actor, link, Ctx("case", case["id"]))
|
||||
if not matter_right.read:
|
||||
continue
|
||||
matters.append(
|
||||
{
|
||||
"id": str(link["id"]),
|
||||
"link_id": str(link["link_id"]),
|
||||
"title": link["title"],
|
||||
"status": link["record_status"],
|
||||
}
|
||||
)
|
||||
payload["matters"] = matters
|
||||
context = Ctx("case", case["id"])
|
||||
bindings = []
|
||||
for binding in conn.execute(
|
||||
"""
|
||||
SELECT * FROM bindings
|
||||
WHERE context_kind = 'case' AND context_id = %s
|
||||
ORDER BY position, created_at
|
||||
""",
|
||||
(case["id"],),
|
||||
).fetchall():
|
||||
item = binding_payload(conn, actor, binding, context)
|
||||
if item is not None:
|
||||
bindings.append(item)
|
||||
payload["bindings"] = bindings
|
||||
if rights.share or case["owner_subject_id"] == actor:
|
||||
payload["grants"] = _grants(conn, "case", case["id"])
|
||||
return payload
|
||||
|
||||
|
||||
def matter_contexts(conn, actor: UUID, matter: dict) -> list[dict]:
|
||||
contexts = []
|
||||
for item in readable_matter_contexts(conn, actor, matter):
|
||||
kind = "direct" if item["kind"] == "matter" and item["id"] == str(matter["id"]) else item["kind"]
|
||||
contexts.append({"kind": kind, "id": item["id"], "title": item["title"]})
|
||||
return contexts
|
||||
|
||||
|
||||
def matter_summary(conn, actor: UUID, matter: dict) -> dict:
|
||||
return {
|
||||
"id": str(matter["id"]),
|
||||
"title": matter["title"],
|
||||
"status": matter["record_status"],
|
||||
"version": matter["version"],
|
||||
"parent_matter_id": str(matter["parent_matter_id"]) if matter["parent_matter_id"] else None,
|
||||
"home_scope_id": str(matter["home_scope_id"]),
|
||||
"contexts": matter_contexts(conn, actor, matter),
|
||||
}
|
||||
|
||||
|
||||
def _page_context(matter_id: UUID, context: Ctx | None) -> Ctx:
|
||||
if context is None:
|
||||
return Ctx("matter", matter_id)
|
||||
return context
|
||||
|
||||
|
||||
def matter_detail(conn, actor: UUID, matter: dict, rights, context: Ctx | None) -> dict:
|
||||
page = _page_context(matter["id"], context)
|
||||
payload = {
|
||||
"id": str(matter["id"]),
|
||||
"title": matter["title"],
|
||||
"status": matter["record_status"],
|
||||
"version": matter["version"],
|
||||
"parent_matter_id": str(matter["parent_matter_id"]) if matter["parent_matter_id"] else None,
|
||||
"home_scope_id": str(matter["home_scope_id"]),
|
||||
"home_scope_name": room_name(conn, matter["home_scope_id"]),
|
||||
"is_owner": matter["owner_subject_id"] == actor,
|
||||
"rights": rights.as_dict(),
|
||||
"context": None if context is None else context.as_dict(),
|
||||
"chapters": _chapters(conn, "matter", matter["id"]),
|
||||
}
|
||||
submatters = []
|
||||
for child in conn.execute(
|
||||
"SELECT * FROM matters WHERE parent_matter_id = %s AND deleted_at IS NULL ORDER BY title, id",
|
||||
(matter["id"],),
|
||||
).fetchall():
|
||||
child_rights = matter_rights(conn, actor, child, page)
|
||||
if child_rights.read:
|
||||
submatters.append({"id": str(child["id"]), "title": child["title"], "status": child["record_status"]})
|
||||
payload["submatters"] = submatters
|
||||
case_links = []
|
||||
for link in conn.execute(
|
||||
"""
|
||||
SELECT l.id, l.case_id, c.title
|
||||
FROM matter_case_links l
|
||||
JOIN cases c ON c.id = l.case_id AND c.deleted_at IS NULL
|
||||
WHERE l.matter_id = %s
|
||||
ORDER BY c.title, c.id
|
||||
""",
|
||||
(matter["id"],),
|
||||
).fetchall():
|
||||
linked_case = get_case(conn, link["case_id"])
|
||||
if linked_case is not None and case_rights(conn, actor, linked_case).read:
|
||||
case_links.append({"id": str(link["id"]), "case_id": str(link["case_id"]), "title": link["title"]})
|
||||
payload["case_links"] = case_links
|
||||
crosses = []
|
||||
for link in conn.execute(
|
||||
"""
|
||||
SELECT l.id, l.to_matter_id
|
||||
FROM matter_cross_links l
|
||||
WHERE l.from_matter_id = %s
|
||||
""",
|
||||
(matter["id"],),
|
||||
).fetchall():
|
||||
title = matter_title_if_readable(conn, actor, link["to_matter_id"])
|
||||
if title is not None:
|
||||
crosses.append({"id": str(link["id"]), "matter_id": str(link["to_matter_id"]), "title": title})
|
||||
payload["cross_links"] = crosses
|
||||
bindings = []
|
||||
for binding in conn.execute(
|
||||
"""
|
||||
SELECT * FROM bindings
|
||||
WHERE context_kind = 'matter' AND context_id = %s
|
||||
ORDER BY position, created_at
|
||||
""",
|
||||
(matter["id"],),
|
||||
).fetchall():
|
||||
item = binding_payload(conn, actor, binding, page)
|
||||
if item is not None:
|
||||
bindings.append(item)
|
||||
payload["bindings"] = bindings
|
||||
payload["tasks"] = []
|
||||
for task in conn.execute(
|
||||
"""
|
||||
SELECT * FROM tasks
|
||||
WHERE matter_id = %s AND deleted_at IS NULL
|
||||
ORDER BY due_on NULLS LAST, created_at
|
||||
""",
|
||||
(matter["id"],),
|
||||
).fetchall():
|
||||
task_right = task_rights(conn, actor, task, context)
|
||||
if task_right.read:
|
||||
payload["tasks"].append(task_payload(conn, actor, task, task_right))
|
||||
payload["deadlines"] = []
|
||||
visible_deadlines = set()
|
||||
for deadline in conn.execute(
|
||||
"""
|
||||
SELECT * FROM deadlines
|
||||
WHERE matter_id = %s AND deleted_at IS NULL
|
||||
ORDER BY due_on, created_at
|
||||
""",
|
||||
(matter["id"],),
|
||||
).fetchall():
|
||||
deadline_right = deadline_rights(conn, actor, deadline, context)
|
||||
if deadline_right.read:
|
||||
payload["deadlines"].append(deadline_payload(conn, actor, deadline))
|
||||
visible_deadlines.add(deadline["id"])
|
||||
visible_tasks = {UUID(item["id"]) for item in payload["tasks"]}
|
||||
links = []
|
||||
if visible_tasks and visible_deadlines:
|
||||
for link in conn.execute(
|
||||
"SELECT task_id, deadline_id FROM task_deadline_links WHERE task_id = ANY(%s::uuid[])",
|
||||
(list(visible_tasks),),
|
||||
).fetchall():
|
||||
if link["deadline_id"] in visible_deadlines:
|
||||
links.append({"task_id": str(link["task_id"]), "deadline_id": str(link["deadline_id"])})
|
||||
payload["task_deadline_links"] = links
|
||||
if rights.share or matter["owner_subject_id"] == actor:
|
||||
payload["grants"] = _grants(conn, "matter", matter["id"])
|
||||
if matter["owner_subject_id"] == actor:
|
||||
payload["exception"] = _exception(conn, "matter", matter["id"], context)
|
||||
return payload
|
||||
|
||||
|
||||
def task_payload(conn, actor: UUID, task: dict, rights=None) -> dict:
|
||||
payload = {
|
||||
"id": str(task["id"]),
|
||||
"title": task["title"],
|
||||
"status": task["task_status"],
|
||||
"version": task["version"],
|
||||
"due_on": dump_date(task["due_on"]),
|
||||
"assignee_display_name": display_name(conn, task["assignee_subject_id"]),
|
||||
}
|
||||
if rights is not None:
|
||||
payload["rights"] = rights.as_dict()
|
||||
title = matter_title_if_readable(conn, actor, task["matter_id"])
|
||||
if title is not None and task["matter_id"] is not None:
|
||||
payload["matter_id"] = str(task["matter_id"])
|
||||
payload["matter_title"] = title
|
||||
action = _task_action_context(conn, actor, task)
|
||||
if action is not None:
|
||||
payload["action_context"] = action
|
||||
return payload
|
||||
|
||||
|
||||
def _task_action_context(conn, actor: UUID, task: dict) -> dict | None:
|
||||
direct = task_rights(conn, actor, task, None)
|
||||
if direct.read and (direct.edit or task["owner_subject_id"] == actor or task["assignee_subject_id"] == actor):
|
||||
return None
|
||||
if task["matter_id"] is None:
|
||||
return None
|
||||
matter = get_matter(conn, task["matter_id"])
|
||||
if matter is None:
|
||||
return None
|
||||
for item in readable_matter_contexts(conn, actor, matter):
|
||||
if item["kind"] != "case":
|
||||
continue
|
||||
rights = task_rights(conn, actor, task, Ctx("case", UUID(item["id"])))
|
||||
if rights.edit or (rights.read and task["assignee_subject_id"] == actor):
|
||||
return {"kind": "case", "id": item["id"]}
|
||||
return None
|
||||
|
||||
|
||||
def deadline_payload(conn, actor: UUID, deadline: dict) -> dict:
|
||||
payload = {
|
||||
"id": str(deadline["id"]),
|
||||
"title": deadline["title"],
|
||||
"status": deadline["deadline_status"],
|
||||
"version": deadline["version"],
|
||||
"due_on": dump_date(deadline["due_on"]),
|
||||
"fulfilled_at": dump_dt(deadline["fulfilled_at"]),
|
||||
"assignee_display_name": display_name(conn, deadline["assignee_subject_id"]),
|
||||
}
|
||||
title = matter_title_if_readable(conn, actor, deadline["matter_id"])
|
||||
if title is not None and deadline["matter_id"] is not None:
|
||||
payload["matter_id"] = str(deadline["matter_id"])
|
||||
payload["matter_title"] = title
|
||||
direct = deadline_rights(conn, actor, deadline, None)
|
||||
if not (direct.read and (direct.edit or deadline["owner_subject_id"] == actor or deadline["assignee_subject_id"] == actor)):
|
||||
if deadline["matter_id"] is not None:
|
||||
matter = get_matter(conn, deadline["matter_id"])
|
||||
if matter is not None:
|
||||
for item in readable_matter_contexts(conn, actor, matter):
|
||||
if item["kind"] != "case":
|
||||
continue
|
||||
rights = deadline_rights(conn, actor, deadline, Ctx("case", UUID(item["id"])))
|
||||
if rights.edit or (rights.read and deadline["assignee_subject_id"] == actor):
|
||||
payload["action_context"] = {"kind": "case", "id": item["id"]}
|
||||
break
|
||||
return payload
|
||||
|
||||
|
||||
def note_update_payload(conn, actor: UUID, element: dict, document: dict) -> dict:
|
||||
return {
|
||||
"id": str(element["id"]),
|
||||
"title": element["title"],
|
||||
"version": element["version"],
|
||||
"document": document,
|
||||
"visible_bindings": visible_bindings_for_element(conn, actor, element),
|
||||
"notice": SHARED_NOTICE,
|
||||
}
|
||||
|
||||
|
||||
LABELS = {
|
||||
"case_created": "Akte angelegt",
|
||||
"matter_created": "Vorgang angelegt",
|
||||
"matter_linked": "Vorgang einer Akte zugeordnet",
|
||||
"matter_unlinked": "Aktenzuordnung gelöst",
|
||||
"cross_linked": "Querverweis erfasst",
|
||||
"note_created": "Notiz angelegt",
|
||||
"note_updated": "Gemeinsamer Notizinhalt geändert",
|
||||
"annotation_created": "Kontextbezogene Anmerkung erfasst",
|
||||
"file_added": "Datei hinzugefügt",
|
||||
"external_ref_added": "Externe Referenz erfasst",
|
||||
"binding_created": "Einbindung ergänzt",
|
||||
"binding_removed": "Einbindung entfernt",
|
||||
"element_deleted": "Element gelöscht",
|
||||
"task_created": "Aufgabe angelegt",
|
||||
"task_done": "Aufgabe erledigt",
|
||||
"task_reopened": "Aufgabe wieder geöffnet",
|
||||
"deadline_created": "Frist erfasst",
|
||||
"deadline_fulfilled": "Frist erfüllt",
|
||||
"grant_created": "Freigabe erteilt",
|
||||
"grant_revoked": "Freigabe entzogen",
|
||||
"correspondence_document": "Dokumentdatum",
|
||||
"correspondence_sent": "Versand",
|
||||
"correspondence_received": "Zugang",
|
||||
"correspondence_recorded": "Erfassung",
|
||||
"chapter_created": "Kapitel angelegt",
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
"""Synthetic development accounts and a rental matter. Never runs in production."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
from app.access.policy import Ctx
|
||||
from app.auth.accounts import create_account
|
||||
from app.core.errors import not_found
|
||||
from app.core.settings import Settings, get_settings
|
||||
from app.ops import (
|
||||
add_annotation,
|
||||
assign_task,
|
||||
bind_element,
|
||||
create_case,
|
||||
create_chapter,
|
||||
create_deadline,
|
||||
create_external,
|
||||
create_file,
|
||||
create_matter,
|
||||
create_note,
|
||||
create_task,
|
||||
grant_access,
|
||||
link_matter_to_case,
|
||||
link_task_deadline,
|
||||
)
|
||||
|
||||
ADA_EMAIL = "ada@example.test"
|
||||
BEN_EMAIL = "ben@example.test"
|
||||
ADA_PASSWORD = "Beispiel-Ada-2026"
|
||||
BEN_PASSWORD = "Beispiel-Ben-2026"
|
||||
|
||||
SAMPLE_PDF = b"""%PDF-1.1
|
||||
1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj
|
||||
2 0 obj<</Type/Pages/Count 1/Kids[3 0 R]>>endobj
|
||||
3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 320 160]/Contents 4 0 R>>endobj
|
||||
4 0 obj<</Length 55>>stream
|
||||
BT /F1 12 Tf 40 90 Td (Mietschreiben Beispiel) Tj ET
|
||||
endstream
|
||||
endobj
|
||||
trailer<</Root 1 0 R>>
|
||||
%%EOF
|
||||
"""
|
||||
|
||||
|
||||
def demo_public(settings: Settings) -> dict:
|
||||
if settings.tsumugu_env != "development" or not settings.seed_demo:
|
||||
raise not_found()
|
||||
return {
|
||||
"accounts": [
|
||||
{"email": ADA_EMAIL, "password": ADA_PASSWORD, "display_name": "Ada Beispiel"},
|
||||
{"email": BEN_EMAIL, "password": BEN_PASSWORD, "display_name": "Ben Beispiel"},
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def seed_demo(settings: Settings | None = None) -> bool:
|
||||
settings = settings or get_settings()
|
||||
if settings.tsumugu_env != "development" or not settings.seed_demo:
|
||||
return False
|
||||
cleanup: list[Path] = []
|
||||
with psycopg.connect(settings.dsn(), row_factory=dict_row) as conn:
|
||||
try:
|
||||
if conn.execute("SELECT 1 FROM auth_accounts WHERE email = %s", (ADA_EMAIL,)).fetchone():
|
||||
return False
|
||||
ada = create_account(conn, ADA_EMAIL, "Ada Beispiel", ADA_PASSWORD)
|
||||
ben = create_account(conn, BEN_EMAIL, "Ben Beispiel", BEN_PASSWORD)
|
||||
room = conn.execute(
|
||||
"""
|
||||
INSERT INTO data_rooms (id, kind, name, created_by)
|
||||
VALUES (gen_random_uuid(), 'organization', 'Haushalt Musterstraße', %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(ada["id"],),
|
||||
).fetchone()
|
||||
conn.execute(
|
||||
"INSERT INTO room_memberships (room_id, subject_id, role) VALUES (%s, %s, 'manager'), (%s, %s, 'member')",
|
||||
(room["id"], ada["id"], room["id"], ben["id"]),
|
||||
)
|
||||
private_case = create_case(conn, ada["id"], ada["id"], "Persönliche Verhandlungsstrategie", None, "explicit")
|
||||
shared_case = create_case(conn, ada["id"], ada["id"], "Mietstreit Musterstraße 12", None, "explicit")
|
||||
grant_access(conn, ada["id"], "case", shared_case["id"], ben["id"], True, True, False, None)
|
||||
strategy = create_matter(conn, ada["id"], ada["id"], "Interne Verhandlungsstrategie", None, None)
|
||||
moisture = create_matter(conn, ada["id"], ada["id"], "Mängelanzeige Feuchtigkeit", None, None)
|
||||
link_matter_to_case(conn, ada["id"], moisture["id"], shared_case["id"], None)
|
||||
link_matter_to_case(conn, ada["id"], strategy["id"], private_case["id"], None)
|
||||
note = create_note(
|
||||
conn,
|
||||
ada["id"],
|
||||
ada["id"],
|
||||
"Gespräch mit der Hausverwaltung",
|
||||
{
|
||||
"version": 1,
|
||||
"blocks": [
|
||||
{
|
||||
"type": "paragraph",
|
||||
"text": (
|
||||
"Am 1. Oktober die Feuchtigkeit im Schlafzimmer angezeigt. "
|
||||
"Die Verwaltung will bis Ende November antworten."
|
||||
),
|
||||
}
|
||||
],
|
||||
},
|
||||
Ctx("case", shared_case["id"]),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
matter_binding = bind_element(
|
||||
conn,
|
||||
ada["id"],
|
||||
note["element"]["id"],
|
||||
Ctx("case", shared_case["id"]),
|
||||
Ctx("matter", moisture["id"]),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
add_annotation(
|
||||
conn,
|
||||
ada["id"],
|
||||
note["binding"]["id"],
|
||||
"Nur in der Akte: Original im blauen Ordner.",
|
||||
Ctx("case", shared_case["id"]),
|
||||
)
|
||||
add_annotation(
|
||||
conn,
|
||||
ada["id"],
|
||||
matter_binding["id"],
|
||||
"Nur in diesem Vorgang: Zeugin Frau Keller erinnern.",
|
||||
Ctx("matter", moisture["id"]),
|
||||
)
|
||||
create_note(
|
||||
conn,
|
||||
ada["id"],
|
||||
ada["id"],
|
||||
"Nicht weitergeben",
|
||||
{
|
||||
"version": 1,
|
||||
"blocks": [
|
||||
{
|
||||
"type": "paragraph",
|
||||
"text": "Vergleich nur anbieten, wenn die Gegenseite zuerst einen Betrag nennt.",
|
||||
}
|
||||
],
|
||||
},
|
||||
Ctx("case", private_case["id"]),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
chapter = create_chapter(conn, ada["id"], "matter", moisture["id"], "Schriftwechsel", 0, None)
|
||||
create_file(
|
||||
conn,
|
||||
ada["id"],
|
||||
ada["id"],
|
||||
"Schreiben an die Hausverwaltung",
|
||||
"Schreiben-Hausverwaltung.pdf",
|
||||
SAMPLE_PDF,
|
||||
Ctx("matter", moisture["id"]),
|
||||
None,
|
||||
chapter["id"],
|
||||
date(2026, 10, 1),
|
||||
date(2026, 10, 2),
|
||||
None,
|
||||
settings.media_root,
|
||||
settings.upload_max_bytes,
|
||||
cleanup,
|
||||
)
|
||||
create_external(
|
||||
conn,
|
||||
ada["id"],
|
||||
ada["id"],
|
||||
"Antwort der Hausverwaltung",
|
||||
"paperless",
|
||||
"4821",
|
||||
Ctx("matter", moisture["id"]),
|
||||
None,
|
||||
chapter["id"],
|
||||
date(2026, 10, 8),
|
||||
None,
|
||||
date(2026, 10, 10),
|
||||
)
|
||||
task = create_task(
|
||||
conn,
|
||||
ada["id"],
|
||||
ada["id"],
|
||||
"Unterlagen für die Antwort zusammenstellen",
|
||||
date(2026, 11, 25),
|
||||
moisture["id"],
|
||||
None,
|
||||
)
|
||||
assign_task(conn, ada["id"], task["id"], ben["id"], None)
|
||||
deadline = create_deadline(
|
||||
conn,
|
||||
ada["id"],
|
||||
ada["id"],
|
||||
"Antwort an die Gegenseite",
|
||||
date(2026, 11, 30),
|
||||
moisture["id"],
|
||||
None,
|
||||
)
|
||||
link_task_deadline(conn, ada["id"], task["id"], deadline["id"], None)
|
||||
conn.commit()
|
||||
return True
|
||||
except Exception:
|
||||
conn.rollback()
|
||||
for path in cleanup:
|
||||
path.unlink(missing_ok=True)
|
||||
raise
|
||||
+3
-40
@@ -1,42 +1,5 @@
|
||||
"""Tsumugu — schmales Startgerüst, damit der Pi-Deploy einen Health-Check hat."""
|
||||
"""Uvicorn entry: `uvicorn main:app`."""
|
||||
|
||||
from __future__ import annotations
|
||||
from app.main import app
|
||||
|
||||
import os
|
||||
|
||||
import psycopg2
|
||||
from fastapi import FastAPI
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
app = FastAPI(title="Tsumugu", docs_url=None, redoc_url=None)
|
||||
|
||||
|
||||
def _database_status() -> str:
|
||||
try:
|
||||
connection = psycopg2.connect(
|
||||
host=os.environ.get("DB_HOST", "postgres"),
|
||||
port=os.environ.get("DB_PORT", "5432"),
|
||||
dbname=os.environ.get("DB_NAME", "tsumugu"),
|
||||
user=os.environ.get("DB_USER", "tsumugu"),
|
||||
password=os.environ.get("DB_PASSWORD", ""),
|
||||
connect_timeout=3,
|
||||
)
|
||||
connection.close()
|
||||
except Exception:
|
||||
return "error"
|
||||
return "ok"
|
||||
|
||||
|
||||
@app.get("/api/health")
|
||||
def api_health():
|
||||
database = _database_status()
|
||||
status = "ok" if database == "ok" else "degraded"
|
||||
return JSONResponse(
|
||||
status_code=200 if database == "ok" else 503,
|
||||
content={
|
||||
"status": status,
|
||||
"app": "tsumugu",
|
||||
"env": os.environ.get("TSUMUGU_ENV", "development"),
|
||||
"db": database,
|
||||
},
|
||||
)
|
||||
__all__ = ["app"]
|
||||
@@ -0,0 +1,356 @@
|
||||
-- Erster Fachschnitt: Identität, Struktur, Inhalte, Nachverfolgung, eigene Dateien.
|
||||
-- Finanz-, Zusammenstellungs- und Paperless-Abgleichstabellen gehören nicht in diese Lieferung.
|
||||
|
||||
CREATE TABLE auth_accounts (
|
||||
id uuid PRIMARY KEY,
|
||||
email text NOT NULL UNIQUE,
|
||||
display_name text NOT NULL,
|
||||
password_hash text NOT NULL,
|
||||
status text NOT NULL DEFAULT 'active',
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT auth_accounts_status CHECK (status IN ('active', 'disabled')),
|
||||
CONSTRAINT auth_accounts_email_len CHECK (char_length(email) <= 320),
|
||||
CONSTRAINT auth_accounts_name_len CHECK (char_length(display_name) BETWEEN 1 AND 120)
|
||||
);
|
||||
|
||||
CREATE TABLE data_rooms (
|
||||
id uuid PRIMARY KEY,
|
||||
kind text NOT NULL,
|
||||
name text NOT NULL,
|
||||
status text NOT NULL DEFAULT 'active',
|
||||
created_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT data_rooms_kind CHECK (kind IN ('personal', 'organization')),
|
||||
CONSTRAINT data_rooms_status CHECK (status IN ('active', 'archived')),
|
||||
CONSTRAINT data_rooms_name_len CHECK (char_length(name) BETWEEN 1 AND 160)
|
||||
);
|
||||
|
||||
CREATE TABLE auth_sessions (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
account_id uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
secret_hash text NOT NULL UNIQUE,
|
||||
csrf_token text NOT NULL,
|
||||
scope_kind text NOT NULL,
|
||||
scope_id uuid NOT NULL REFERENCES data_rooms (id),
|
||||
epoch integer NOT NULL DEFAULT 1,
|
||||
expires_at timestamptz NOT NULL,
|
||||
revoked_at timestamptz,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT auth_sessions_scope_kind CHECK (scope_kind IN ('personal', 'organization'))
|
||||
);
|
||||
|
||||
CREATE INDEX auth_sessions_account ON auth_sessions (account_id);
|
||||
|
||||
CREATE TABLE auth_invitations (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
email text NOT NULL,
|
||||
room_id uuid NOT NULL REFERENCES data_rooms (id),
|
||||
token_hash text NOT NULL UNIQUE,
|
||||
invited_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
expires_at timestamptz NOT NULL,
|
||||
accepted_at timestamptz,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE room_memberships (
|
||||
room_id uuid NOT NULL REFERENCES data_rooms (id),
|
||||
subject_id uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
role text NOT NULL,
|
||||
status text NOT NULL DEFAULT 'active',
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (room_id, subject_id),
|
||||
CONSTRAINT room_memberships_role CHECK (role IN ('member', 'manager')),
|
||||
CONSTRAINT room_memberships_status CHECK (status IN ('active', 'removed'))
|
||||
);
|
||||
|
||||
CREATE TABLE cases (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
home_scope_id uuid NOT NULL REFERENCES data_rooms (id),
|
||||
owner_subject_id uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
created_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
version integer NOT NULL DEFAULT 1,
|
||||
title text NOT NULL,
|
||||
parent_case_id uuid,
|
||||
rights_mode text NOT NULL DEFAULT 'explicit',
|
||||
record_status text NOT NULL DEFAULT 'open',
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
deleted_at timestamptz,
|
||||
CONSTRAINT cases_title_len CHECK (char_length(title) BETWEEN 1 AND 200),
|
||||
CONSTRAINT cases_rights_mode CHECK (rights_mode IN ('inherit_parent', 'explicit')),
|
||||
CONSTRAINT cases_status CHECK (record_status IN ('open', 'closed')),
|
||||
CONSTRAINT cases_root_explicit CHECK (
|
||||
(parent_case_id IS NULL AND rights_mode = 'explicit')
|
||||
OR parent_case_id IS NOT NULL
|
||||
),
|
||||
UNIQUE (id, home_scope_id)
|
||||
);
|
||||
|
||||
ALTER TABLE cases
|
||||
ADD CONSTRAINT cases_parent_same_scope
|
||||
FOREIGN KEY (parent_case_id, home_scope_id) REFERENCES cases (id, home_scope_id);
|
||||
|
||||
CREATE INDEX cases_owner ON cases (owner_subject_id) WHERE deleted_at IS NULL;
|
||||
CREATE INDEX cases_home ON cases (home_scope_id) WHERE deleted_at IS NULL;
|
||||
|
||||
CREATE TABLE matters (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
home_scope_id uuid NOT NULL REFERENCES data_rooms (id),
|
||||
owner_subject_id uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
created_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
version integer NOT NULL DEFAULT 1,
|
||||
title text NOT NULL,
|
||||
parent_matter_id uuid,
|
||||
record_status text NOT NULL DEFAULT 'open',
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
deleted_at timestamptz,
|
||||
CONSTRAINT matters_title_len CHECK (char_length(title) BETWEEN 1 AND 200),
|
||||
CONSTRAINT matters_status CHECK (record_status IN ('open', 'closed')),
|
||||
UNIQUE (id, home_scope_id)
|
||||
);
|
||||
|
||||
ALTER TABLE matters
|
||||
ADD CONSTRAINT matters_parent_same_scope
|
||||
FOREIGN KEY (parent_matter_id, home_scope_id) REFERENCES matters (id, home_scope_id);
|
||||
|
||||
CREATE INDEX matters_owner ON matters (owner_subject_id) WHERE deleted_at IS NULL;
|
||||
|
||||
CREATE TABLE chapters (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
home_scope_id uuid NOT NULL REFERENCES data_rooms (id),
|
||||
case_id uuid,
|
||||
matter_id uuid,
|
||||
title text NOT NULL,
|
||||
position integer NOT NULL DEFAULT 0,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT chapters_title_len CHECK (char_length(title) BETWEEN 1 AND 200),
|
||||
CONSTRAINT chapters_one_container CHECK ((case_id IS NULL) <> (matter_id IS NULL))
|
||||
);
|
||||
|
||||
ALTER TABLE chapters
|
||||
ADD CONSTRAINT chapters_case_same_scope
|
||||
FOREIGN KEY (case_id, home_scope_id) REFERENCES cases (id, home_scope_id);
|
||||
|
||||
ALTER TABLE chapters
|
||||
ADD CONSTRAINT chapters_matter_same_scope
|
||||
FOREIGN KEY (matter_id, home_scope_id) REFERENCES matters (id, home_scope_id);
|
||||
|
||||
CREATE TABLE matter_case_links (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
matter_id uuid NOT NULL REFERENCES matters (id),
|
||||
case_id uuid NOT NULL REFERENCES cases (id),
|
||||
created_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (matter_id, case_id)
|
||||
);
|
||||
|
||||
CREATE INDEX matter_case_links_case ON matter_case_links (case_id);
|
||||
|
||||
CREATE TABLE case_link_blocks (
|
||||
link_id uuid NOT NULL REFERENCES matter_case_links (id) ON DELETE CASCADE,
|
||||
element_id uuid NOT NULL,
|
||||
PRIMARY KEY (link_id, element_id)
|
||||
);
|
||||
|
||||
CREATE TABLE matter_cross_links (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
from_matter_id uuid NOT NULL REFERENCES matters (id),
|
||||
to_matter_id uuid NOT NULL REFERENCES matters (id),
|
||||
created_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (from_matter_id, to_matter_id),
|
||||
CONSTRAINT matter_cross_links_distinct CHECK (from_matter_id <> to_matter_id)
|
||||
);
|
||||
|
||||
CREATE TABLE elements (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
home_scope_id uuid NOT NULL REFERENCES data_rooms (id),
|
||||
owner_subject_id uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
created_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
version integer NOT NULL DEFAULT 1,
|
||||
title text NOT NULL,
|
||||
kind text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
deleted_at timestamptz,
|
||||
CONSTRAINT elements_title_len CHECK (char_length(title) BETWEEN 1 AND 200),
|
||||
CONSTRAINT elements_kind CHECK (kind IN ('note', 'file', 'external_ref')),
|
||||
UNIQUE (id, home_scope_id)
|
||||
);
|
||||
|
||||
CREATE INDEX elements_owner ON elements (owner_subject_id) WHERE deleted_at IS NULL;
|
||||
|
||||
CREATE TABLE note_bodies (
|
||||
element_id uuid PRIMARY KEY REFERENCES elements (id),
|
||||
document_json jsonb NOT NULL,
|
||||
version integer NOT NULL DEFAULT 1,
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE correspondence_dates (
|
||||
element_id uuid PRIMARY KEY REFERENCES elements (id),
|
||||
document_on date,
|
||||
sent_on date,
|
||||
received_on date
|
||||
);
|
||||
|
||||
CREATE TABLE external_references (
|
||||
element_id uuid PRIMARY KEY REFERENCES elements (id),
|
||||
source text NOT NULL,
|
||||
external_id text NOT NULL,
|
||||
CONSTRAINT external_references_source CHECK (source IN ('paperless', 'url')),
|
||||
CONSTRAINT external_references_id_len CHECK (char_length(external_id) BETWEEN 1 AND 200)
|
||||
);
|
||||
|
||||
CREATE TABLE bindings (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
element_id uuid NOT NULL REFERENCES elements (id),
|
||||
context_kind text NOT NULL,
|
||||
context_id uuid NOT NULL,
|
||||
chapter_id uuid REFERENCES chapters (id),
|
||||
position integer NOT NULL DEFAULT 0,
|
||||
created_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (element_id, context_kind, context_id),
|
||||
CONSTRAINT bindings_context_kind CHECK (context_kind IN ('case', 'matter'))
|
||||
);
|
||||
|
||||
CREATE INDEX bindings_context ON bindings (context_kind, context_id);
|
||||
|
||||
CREATE TABLE context_annotations (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
binding_id uuid NOT NULL REFERENCES bindings (id) ON DELETE CASCADE,
|
||||
body text NOT NULL,
|
||||
author_subject_id uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT context_annotations_body CHECK (char_length(body) BETWEEN 1 AND 4000)
|
||||
);
|
||||
|
||||
CREATE TABLE access_grants (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
grantee_subject_id uuid REFERENCES auth_accounts (id),
|
||||
resource_kind text NOT NULL,
|
||||
resource_id uuid NOT NULL,
|
||||
context_kind text,
|
||||
context_id uuid,
|
||||
can_read boolean NOT NULL DEFAULT false,
|
||||
can_edit boolean NOT NULL DEFAULT false,
|
||||
can_share boolean NOT NULL DEFAULT false,
|
||||
can_delete boolean NOT NULL DEFAULT false,
|
||||
is_exception boolean NOT NULL DEFAULT false,
|
||||
created_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT access_grants_kind CHECK (resource_kind IN ('case', 'matter', 'element', 'task', 'deadline')),
|
||||
CONSTRAINT access_grants_context_pair CHECK ((context_kind IS NULL) = (context_id IS NULL)),
|
||||
CONSTRAINT access_grants_context_kind CHECK (context_kind IS NULL OR context_kind IN ('case', 'matter')),
|
||||
CONSTRAINT access_grants_grantee CHECK (is_exception OR grantee_subject_id IS NOT NULL),
|
||||
CONSTRAINT access_grants_exception_flag CHECK (
|
||||
NOT is_exception OR can_read OR can_edit OR can_share OR can_delete
|
||||
)
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX access_grants_identity ON access_grants (
|
||||
resource_kind,
|
||||
resource_id,
|
||||
COALESCE(grantee_subject_id, '00000000-0000-0000-0000-000000000000'::uuid),
|
||||
COALESCE(context_kind, ''),
|
||||
COALESCE(context_id, '00000000-0000-0000-0000-000000000000'::uuid),
|
||||
is_exception
|
||||
);
|
||||
|
||||
CREATE INDEX access_grants_grantee ON access_grants (grantee_subject_id);
|
||||
CREATE INDEX access_grants_resource ON access_grants (resource_kind, resource_id);
|
||||
|
||||
CREATE TABLE tasks (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
home_scope_id uuid NOT NULL REFERENCES data_rooms (id),
|
||||
owner_subject_id uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
created_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
version integer NOT NULL DEFAULT 1,
|
||||
title text NOT NULL,
|
||||
matter_id uuid REFERENCES matters (id),
|
||||
assignee_subject_id uuid REFERENCES auth_accounts (id),
|
||||
due_on date,
|
||||
task_status text NOT NULL DEFAULT 'open',
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
deleted_at timestamptz,
|
||||
CONSTRAINT tasks_title_len CHECK (char_length(title) BETWEEN 1 AND 200),
|
||||
CONSTRAINT tasks_status CHECK (task_status IN ('open', 'done'))
|
||||
);
|
||||
|
||||
CREATE INDEX tasks_open ON tasks (task_status) WHERE deleted_at IS NULL;
|
||||
|
||||
CREATE TABLE deadlines (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
home_scope_id uuid NOT NULL REFERENCES data_rooms (id),
|
||||
owner_subject_id uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
created_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
version integer NOT NULL DEFAULT 1,
|
||||
title text NOT NULL,
|
||||
matter_id uuid REFERENCES matters (id),
|
||||
element_id uuid REFERENCES elements (id),
|
||||
assignee_subject_id uuid REFERENCES auth_accounts (id),
|
||||
due_on date NOT NULL,
|
||||
deadline_status text NOT NULL DEFAULT 'open',
|
||||
fulfilled_at timestamptz,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
deleted_at timestamptz,
|
||||
CONSTRAINT deadlines_title_len CHECK (char_length(title) BETWEEN 1 AND 200),
|
||||
CONSTRAINT deadlines_status CHECK (deadline_status IN ('open', 'fulfilled'))
|
||||
);
|
||||
|
||||
CREATE INDEX deadlines_open ON deadlines (deadline_status) WHERE deleted_at IS NULL;
|
||||
|
||||
CREATE TABLE task_deadline_links (
|
||||
task_id uuid NOT NULL REFERENCES tasks (id),
|
||||
deadline_id uuid NOT NULL REFERENCES deadlines (id),
|
||||
created_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (task_id, deadline_id)
|
||||
);
|
||||
|
||||
CREATE TABLE media_assets (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
element_id uuid NOT NULL UNIQUE REFERENCES elements (id),
|
||||
owner_subject_id uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
home_scope_id uuid NOT NULL REFERENCES data_rooms (id),
|
||||
original_filename text NOT NULL,
|
||||
content_type text NOT NULL,
|
||||
byte_size bigint NOT NULL,
|
||||
sha256 text NOT NULL,
|
||||
revision integer NOT NULL DEFAULT 1,
|
||||
status text NOT NULL DEFAULT 'active',
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT media_assets_status CHECK (status IN ('active', 'purging', 'purged')),
|
||||
CONSTRAINT media_assets_filename CHECK (char_length(original_filename) BETWEEN 1 AND 240)
|
||||
);
|
||||
|
||||
CREATE TABLE media_operations (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
element_id uuid,
|
||||
asset_id uuid,
|
||||
phase text NOT NULL,
|
||||
status text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE domain_events (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
actor_subject_id uuid REFERENCES auth_accounts (id),
|
||||
scope_id uuid,
|
||||
action text NOT NULL,
|
||||
resource_kind text NOT NULL,
|
||||
resource_id uuid NOT NULL,
|
||||
context_kind text,
|
||||
context_id uuid,
|
||||
occurred_on date,
|
||||
occurred_at timestamptz NOT NULL DEFAULT now(),
|
||||
result text NOT NULL DEFAULT 'ok'
|
||||
);
|
||||
|
||||
CREATE INDEX domain_events_resource ON domain_events (resource_kind, resource_id);
|
||||
CREATE INDEX domain_events_context ON domain_events (context_kind, context_id);
|
||||
@@ -0,0 +1,3 @@
|
||||
-r requirements.txt
|
||||
pytest==8.3.4
|
||||
httpx==0.28.1
|
||||
@@ -1,3 +1,7 @@
|
||||
fastapi==0.115.6
|
||||
uvicorn[standard]==0.34.0
|
||||
psycopg2-binary==2.9.10
|
||||
psycopg[binary]==3.2.3
|
||||
psycopg-pool==3.2.4
|
||||
bcrypt==4.2.1
|
||||
pydantic-settings==2.6.1
|
||||
python-multipart==0.0.18
|
||||
Reference in new issue
Block a user