Update .gitignore to exclude Python-related files and directories. Enhance AGENTS.md and README.md with clarifications on documentation structure and product identity. Add technical architecture references and local setup instructions. Revise privacy guardrails and product identity documents for consistency. Remove obsolete memory and context documentation. Expand reflection spaces documentation to define context boundaries and lifecycle. Ensure all changes align with the ongoing development of the Kanshō project.
This commit is contained in:
1 parent
3a367b7bcc
commit
d62673e48b
89 files changed
+13463
-241
No files matched your search
@@ -0,0 +1 @@
|
||||
# Kanshō API routers
|
||||
@@ -0,0 +1,56 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
|
||||
from auth import require_admin_dep
|
||||
from db import get_db
|
||||
from dialogue_store import StoreError, get_conversation, inventory, list_conversations, list_derived_for_conversation, list_messages
|
||||
from version import APP_VERSION, BUILD_DATE, MODULE_VERSIONS
|
||||
|
||||
router = APIRouter(prefix="/api/admin", tags=["admin"])
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
def admin_health(session: dict = Depends(require_admin_dep)):
|
||||
with get_db() as conn:
|
||||
users = conn.execute("SELECT COUNT(*) AS n FROM profiles").fetchone()["n"]
|
||||
prompts = conn.execute("SELECT COUNT(*) AS n FROM ai_prompts").fetchone()["n"]
|
||||
features = conn.execute("SELECT COUNT(*) AS n FROM features").fetchone()["n"]
|
||||
dialogue = inventory()
|
||||
return {
|
||||
"ok": True,
|
||||
"service": "kansho",
|
||||
"version": APP_VERSION,
|
||||
"build_date": BUILD_DATE,
|
||||
"modules": MODULE_VERSIONS,
|
||||
"inventory": {
|
||||
"users": users,
|
||||
"prompts": prompts,
|
||||
"features": features,
|
||||
"dialogue": dialogue,
|
||||
},
|
||||
"session": {
|
||||
"profile_id": session["profile_id"],
|
||||
"role": session["role"],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.get("/dialogue")
|
||||
def admin_dialogue(session: dict = Depends(require_admin_dep)):
|
||||
return {
|
||||
"instance": inventory(),
|
||||
"own_conversations": list_conversations(session["profile_id"]),
|
||||
"note": "Fremde Lived Experience ist kein Alltagspfad. Detailansicht nur für das eigene Profil.",
|
||||
}
|
||||
|
||||
|
||||
@router.get("/dialogue/conversations/{conversation_id}")
|
||||
def admin_conversation(conversation_id: str, session: dict = Depends(require_admin_dep)):
|
||||
try:
|
||||
conv = get_conversation(session["profile_id"], conversation_id)
|
||||
return {
|
||||
"conversation": conv,
|
||||
"original_messages": list_messages(session["profile_id"], conversation_id),
|
||||
"derived_records": list_derived_for_conversation(session["profile_id"], conversation_id),
|
||||
}
|
||||
except StoreError as exc:
|
||||
raise HTTPException(status_code=exc.status_code, detail={"code": exc.code, "message": exc.message}) from exc
|
||||
@@ -0,0 +1,103 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from auth import create_session, hash_password, require_auth, verify_password
|
||||
from db import get_db, row_to_dict
|
||||
from version import APP_VERSION
|
||||
|
||||
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
||||
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
email: str
|
||||
password: str = Field(min_length=4)
|
||||
|
||||
|
||||
class SetupRequest(BaseModel):
|
||||
email: str
|
||||
name: str = Field(min_length=1)
|
||||
password: str = Field(min_length=4)
|
||||
|
||||
|
||||
def _profile_count() -> int:
|
||||
with get_db() as conn:
|
||||
row = conn.execute("SELECT COUNT(*) AS n FROM profiles").fetchone()
|
||||
return int(row["n"])
|
||||
|
||||
|
||||
@router.get("/status")
|
||||
def auth_status():
|
||||
return {
|
||||
"status": "ok",
|
||||
"service": "kansho",
|
||||
"version": APP_VERSION,
|
||||
"needs_setup": _profile_count() == 0,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/setup")
|
||||
def setup(req: SetupRequest):
|
||||
if _profile_count() > 0:
|
||||
raise HTTPException(409, "Setup ist bereits abgeschlossen")
|
||||
profile_id = str(uuid.uuid4())
|
||||
with get_db() as conn:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO profiles (id, email, name, password_hash, role)
|
||||
VALUES (?, ?, ?, ?, 'admin')
|
||||
""",
|
||||
(profile_id, req.email.lower().strip(), req.name.strip(), hash_password(req.password)),
|
||||
)
|
||||
token, expires = create_session(profile_id)
|
||||
return {
|
||||
"token": token,
|
||||
"profile_id": profile_id,
|
||||
"name": req.name.strip(),
|
||||
"role": "admin",
|
||||
"expires_at": expires.isoformat(),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/login")
|
||||
def login(req: LoginRequest):
|
||||
with get_db() as conn:
|
||||
prof = row_to_dict(
|
||||
conn.execute(
|
||||
"SELECT * FROM profiles WHERE email = ?",
|
||||
(req.email.lower().strip(),),
|
||||
).fetchone()
|
||||
)
|
||||
if not prof or not verify_password(req.password, prof["password_hash"]):
|
||||
raise HTTPException(401, "Ungültige Zugangsdaten")
|
||||
if (prof.get("status") or "active") != "active":
|
||||
raise HTTPException(401, "Ungültige Zugangsdaten")
|
||||
token, expires = create_session(prof["id"], prof.get("session_days") or 30)
|
||||
return {
|
||||
"token": token,
|
||||
"profile_id": prof["id"],
|
||||
"name": prof["name"],
|
||||
"role": prof["role"],
|
||||
"expires_at": expires.isoformat(),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/logout")
|
||||
def logout(session: dict = Depends(require_auth)):
|
||||
with get_db() as conn:
|
||||
conn.execute("DELETE FROM sessions WHERE token = ?", (session["token"],))
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
def me(session: dict = Depends(require_auth)):
|
||||
with get_db() as conn:
|
||||
prof = row_to_dict(
|
||||
conn.execute("SELECT id, email, name, role, status, tier_id FROM profiles WHERE id = ?", (session["profile_id"],)).fetchone()
|
||||
)
|
||||
if not prof:
|
||||
raise HTTPException(401, "Profil nicht gefunden")
|
||||
return prof
|
||||
@@ -0,0 +1,215 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from auth import require_auth
|
||||
from context_builder import build_internal_context
|
||||
from continuity import checkpoint_usage_session, close_usage_session
|
||||
from derived_kinds import catalog
|
||||
from dialogue_store import (
|
||||
StoreError,
|
||||
append_message,
|
||||
create_conversation,
|
||||
create_handoff,
|
||||
create_space,
|
||||
create_thread,
|
||||
get_conversation,
|
||||
insert_derived,
|
||||
link_conversation_thread,
|
||||
link_thread_space,
|
||||
list_conversations,
|
||||
list_derived_for_conversation,
|
||||
list_messages,
|
||||
start_usage_session,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/dialogue", tags=["dialogue"])
|
||||
|
||||
|
||||
def _http(exc: StoreError):
|
||||
raise HTTPException(status_code=exc.status_code, detail={"code": exc.code, "message": exc.message}) from exc
|
||||
|
||||
|
||||
class SessionWrite(BaseModel):
|
||||
intent: str = ""
|
||||
|
||||
|
||||
class ConversationWrite(BaseModel):
|
||||
usage_session_id: str | None = None
|
||||
title: str = ""
|
||||
|
||||
|
||||
class MessageWrite(BaseModel):
|
||||
body: str = Field(min_length=1)
|
||||
role: str = "user"
|
||||
id: str | None = None
|
||||
|
||||
|
||||
class ThreadWrite(BaseModel):
|
||||
title: str = ""
|
||||
status: str = "open"
|
||||
visibility: str = "internal"
|
||||
|
||||
|
||||
class SpaceWrite(BaseModel):
|
||||
title: str = ""
|
||||
visibility: str = "internal"
|
||||
|
||||
|
||||
class DerivedWrite(BaseModel):
|
||||
kind: str
|
||||
subject_type: str
|
||||
subject_id: str
|
||||
source_message_ids: list[str]
|
||||
body: str = ""
|
||||
visibility: str = "internal"
|
||||
confidence: float | None = None
|
||||
|
||||
|
||||
class HandoffWrite(BaseModel):
|
||||
target: str
|
||||
source_conversation_id: str | None = None
|
||||
payload: dict = Field(default_factory=dict)
|
||||
|
||||
|
||||
@router.get("/kinds")
|
||||
def list_kinds(session: dict = Depends(require_auth)):
|
||||
return catalog()
|
||||
|
||||
|
||||
@router.post("/sessions")
|
||||
def create_session(req: SessionWrite, session: dict = Depends(require_auth)):
|
||||
return start_usage_session(session["profile_id"], req.intent)
|
||||
|
||||
|
||||
@router.post("/sessions/{usage_session_id}/end")
|
||||
def end_session(usage_session_id: str, session: dict = Depends(require_auth)):
|
||||
try:
|
||||
return close_usage_session(session["profile_id"], usage_session_id)
|
||||
except StoreError as exc:
|
||||
_http(exc)
|
||||
|
||||
|
||||
@router.post("/sessions/{usage_session_id}/checkpoint")
|
||||
def checkpoint_session(usage_session_id: str, session: dict = Depends(require_auth)):
|
||||
try:
|
||||
return checkpoint_usage_session(session["profile_id"], usage_session_id)
|
||||
except StoreError as exc:
|
||||
_http(exc)
|
||||
|
||||
|
||||
@router.post("/conversations")
|
||||
def post_conversation(req: ConversationWrite, session: dict = Depends(require_auth)):
|
||||
try:
|
||||
return create_conversation(session["profile_id"], req.usage_session_id, req.title)
|
||||
except StoreError as exc:
|
||||
_http(exc)
|
||||
|
||||
|
||||
@router.get("/conversations")
|
||||
def get_conversations(session: dict = Depends(require_auth)):
|
||||
return list_conversations(session["profile_id"])
|
||||
|
||||
|
||||
@router.get("/conversations/{conversation_id}")
|
||||
def get_one_conversation(conversation_id: str, session: dict = Depends(require_auth)):
|
||||
try:
|
||||
conv = get_conversation(session["profile_id"], conversation_id)
|
||||
conv["messages"] = list_messages(session["profile_id"], conversation_id)
|
||||
conv["derived"] = list_derived_for_conversation(session["profile_id"], conversation_id)
|
||||
return conv
|
||||
except StoreError as exc:
|
||||
_http(exc)
|
||||
|
||||
|
||||
@router.get("/conversations/{conversation_id}/context")
|
||||
def get_internal_context(conversation_id: str, session: dict = Depends(require_auth)):
|
||||
try:
|
||||
return build_internal_context(session["profile_id"], conversation_id)
|
||||
except StoreError as exc:
|
||||
_http(exc)
|
||||
|
||||
|
||||
@router.post("/conversations/{conversation_id}/messages")
|
||||
def post_message(conversation_id: str, req: MessageWrite, session: dict = Depends(require_auth)):
|
||||
try:
|
||||
return append_message(session["profile_id"], conversation_id, req.body, req.role, req.id)
|
||||
except StoreError as exc:
|
||||
_http(exc)
|
||||
|
||||
|
||||
@router.get("/conversations/{conversation_id}/messages")
|
||||
def get_messages(conversation_id: str, session: dict = Depends(require_auth)):
|
||||
try:
|
||||
return list_messages(session["profile_id"], conversation_id)
|
||||
except StoreError as exc:
|
||||
_http(exc)
|
||||
|
||||
|
||||
@router.post("/threads")
|
||||
def post_thread(req: ThreadWrite, session: dict = Depends(require_auth)):
|
||||
try:
|
||||
return create_thread(session["profile_id"], req.title, req.status, req.visibility)
|
||||
except StoreError as exc:
|
||||
_http(exc)
|
||||
|
||||
|
||||
@router.post("/conversations/{conversation_id}/threads/{thread_id}")
|
||||
def post_conversation_thread(conversation_id: str, thread_id: str, session: dict = Depends(require_auth)):
|
||||
try:
|
||||
return link_conversation_thread(session["profile_id"], conversation_id, thread_id)
|
||||
except StoreError as exc:
|
||||
_http(exc)
|
||||
|
||||
|
||||
@router.post("/spaces")
|
||||
def post_space(req: SpaceWrite, session: dict = Depends(require_auth)):
|
||||
try:
|
||||
return create_space(session["profile_id"], req.title, req.visibility)
|
||||
except StoreError as exc:
|
||||
_http(exc)
|
||||
|
||||
|
||||
@router.post("/threads/{thread_id}/spaces/{space_id}")
|
||||
def post_thread_space(thread_id: str, space_id: str, confidence: float | None = None, session: dict = Depends(require_auth)):
|
||||
try:
|
||||
return link_thread_space(session["profile_id"], thread_id, space_id, confidence)
|
||||
except StoreError as exc:
|
||||
_http(exc)
|
||||
|
||||
|
||||
@router.post("/derived")
|
||||
def post_derived(req: DerivedWrite, session: dict = Depends(require_auth)):
|
||||
try:
|
||||
return insert_derived(
|
||||
session["profile_id"],
|
||||
req.kind,
|
||||
req.subject_type,
|
||||
req.subject_id,
|
||||
req.source_message_ids,
|
||||
req.body,
|
||||
req.visibility,
|
||||
req.confidence,
|
||||
)
|
||||
except StoreError as exc:
|
||||
_http(exc)
|
||||
|
||||
|
||||
@router.get("/derived/latest")
|
||||
def get_latest(subject_type: str, subject_id: str, kind: str, session: dict = Depends(require_auth)):
|
||||
from data_layer import read
|
||||
|
||||
return read(
|
||||
"latest_derived",
|
||||
profile_id=session["profile_id"],
|
||||
context={"subject_type": subject_type, "subject_id": subject_id, "kind": kind},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/handoffs")
|
||||
def post_handoff(req: HandoffWrite, session: dict = Depends(require_auth)):
|
||||
try:
|
||||
return create_handoff(session["profile_id"], req.target, req.source_conversation_id, req.payload)
|
||||
except StoreError as exc:
|
||||
_http(exc)
|
||||
@@ -0,0 +1,19 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from auth import require_auth
|
||||
import placeholder_system # noqa: F401
|
||||
from placeholders import list_placeholders
|
||||
from privacy_placeholders import catalog as privacy_catalog
|
||||
|
||||
router = APIRouter(prefix="/api/placeholders", tags=["placeholders"])
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_all_placeholders(session: dict = Depends(require_auth)):
|
||||
return {
|
||||
"context": list_placeholders(),
|
||||
"privacy": privacy_catalog(),
|
||||
"note": "Templates dürfen nur registrierte {{key}} und [[TOKEN]] enthalten. Fachliche Keys kommen später als Registry-Einträge, nicht als Freitext.",
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from auth import require_admin_dep, require_auth
|
||||
from db import get_db, row_to_dict
|
||||
from engine import EngineError, execute_prompt, preview_prompt
|
||||
|
||||
router = APIRouter(prefix="/api/prompts", tags=["prompts"])
|
||||
|
||||
LIST_FIELDS = """
|
||||
id, slug, name, description, category, prompt_type, template, required_feature,
|
||||
active, is_system_default, sort_order, created, updated
|
||||
"""
|
||||
|
||||
|
||||
class PromptWrite(BaseModel):
|
||||
slug: str = Field(min_length=1, max_length=80)
|
||||
name: str = Field(min_length=1)
|
||||
description: str = ""
|
||||
category: str = "uncategorized"
|
||||
prompt_type: str = "base"
|
||||
template: str = ""
|
||||
required_feature: str = "ai_calls"
|
||||
active: bool = True
|
||||
|
||||
|
||||
class PreviewRequest(BaseModel):
|
||||
slug: str | None = None
|
||||
prompt_id: str | None = None
|
||||
|
||||
|
||||
class ExecuteRequest(BaseModel):
|
||||
slug: str | None = None
|
||||
prompt_id: str | None = None
|
||||
purpose: str = "reflection"
|
||||
data_class: str = Field(default="B")
|
||||
|
||||
|
||||
def _http(exc: EngineError):
|
||||
raise HTTPException(status_code=exc.status_code, detail={"code": exc.code, "message": exc.message}) from exc
|
||||
|
||||
|
||||
def _load(conn, prompt_id: str | None, slug: str | None) -> dict:
|
||||
if prompt_id:
|
||||
row = conn.execute("SELECT * FROM ai_prompts WHERE id = ?", (prompt_id,)).fetchone()
|
||||
elif slug:
|
||||
row = conn.execute("SELECT * FROM ai_prompts WHERE slug = ?", (slug,)).fetchone()
|
||||
else:
|
||||
raise HTTPException(400, "prompt_id oder slug ist erforderlich")
|
||||
prompt = row_to_dict(row)
|
||||
if not prompt:
|
||||
raise HTTPException(404, "Prompt nicht gefunden")
|
||||
return prompt
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_prompts(session: dict = Depends(require_admin_dep)):
|
||||
with get_db() as conn:
|
||||
rows = conn.execute(f"SELECT {LIST_FIELDS} FROM ai_prompts ORDER BY sort_order, name").fetchall()
|
||||
return [row_to_dict(row) for row in rows]
|
||||
|
||||
|
||||
@router.post("")
|
||||
def create_prompt(req: PromptWrite, session: dict = Depends(require_admin_dep)):
|
||||
if req.prompt_type not in {"base", "pipeline", "workflow"}:
|
||||
raise HTTPException(400, "Ungültiger Prompt-Typ")
|
||||
prompt_id = str(uuid.uuid4())
|
||||
if req.prompt_type == "base" and req.template:
|
||||
try:
|
||||
preview_prompt(
|
||||
{
|
||||
"id": prompt_id,
|
||||
"slug": req.slug.strip(),
|
||||
"prompt_type": req.prompt_type,
|
||||
"template": req.template,
|
||||
},
|
||||
{},
|
||||
)
|
||||
except EngineError as exc:
|
||||
_http(exc)
|
||||
try:
|
||||
with get_db() as conn:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO ai_prompts
|
||||
(id, slug, name, description, category, prompt_type, template,
|
||||
required_feature, active, default_template)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
prompt_id,
|
||||
req.slug.strip(),
|
||||
req.name.strip(),
|
||||
req.description,
|
||||
req.category.strip() or "uncategorized",
|
||||
req.prompt_type,
|
||||
req.template,
|
||||
req.required_feature,
|
||||
1 if req.active else 0,
|
||||
req.template,
|
||||
),
|
||||
)
|
||||
return row_to_dict(conn.execute(f"SELECT {LIST_FIELDS} FROM ai_prompts WHERE id = ?", (prompt_id,)).fetchone())
|
||||
except Exception as exc:
|
||||
if "UNIQUE" in str(exc).upper():
|
||||
raise HTTPException(409, "Slug ist bereits vergeben") from exc
|
||||
raise
|
||||
|
||||
|
||||
@router.put("/{prompt_id}")
|
||||
def update_prompt(prompt_id: str, req: PromptWrite, session: dict = Depends(require_admin_dep)):
|
||||
with get_db() as conn:
|
||||
current = row_to_dict(conn.execute("SELECT id FROM ai_prompts WHERE id = ?", (prompt_id,)).fetchone())
|
||||
if not current:
|
||||
raise HTTPException(404, "Prompt nicht gefunden")
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE ai_prompts
|
||||
SET slug = ?, name = ?, description = ?, category = ?, prompt_type = ?,
|
||||
template = ?, required_feature = ?, active = ?, updated = datetime('now')
|
||||
WHERE id = ?
|
||||
""",
|
||||
(
|
||||
req.slug.strip(),
|
||||
req.name.strip(),
|
||||
req.description,
|
||||
req.category.strip() or "uncategorized",
|
||||
req.prompt_type,
|
||||
req.template,
|
||||
req.required_feature,
|
||||
1 if req.active else 0,
|
||||
prompt_id,
|
||||
),
|
||||
)
|
||||
return row_to_dict(conn.execute(f"SELECT {LIST_FIELDS} FROM ai_prompts WHERE id = ?", (prompt_id,)).fetchone())
|
||||
|
||||
|
||||
@router.post("/{prompt_id}/reset")
|
||||
def reset_prompt(prompt_id: str, session: dict = Depends(require_admin_dep)):
|
||||
with get_db() as conn:
|
||||
prompt = row_to_dict(conn.execute("SELECT * FROM ai_prompts WHERE id = ?", (prompt_id,)).fetchone())
|
||||
if not prompt:
|
||||
raise HTTPException(404, "Prompt nicht gefunden")
|
||||
if not prompt["is_system_default"]:
|
||||
raise HTTPException(400, "Nur System-Defaults können zurückgesetzt werden")
|
||||
conn.execute(
|
||||
"UPDATE ai_prompts SET template = default_template, updated = datetime('now') WHERE id = ?",
|
||||
(prompt_id,),
|
||||
)
|
||||
return row_to_dict(conn.execute(f"SELECT {LIST_FIELDS} FROM ai_prompts WHERE id = ?", (prompt_id,)).fetchone())
|
||||
|
||||
|
||||
@router.post("/preview")
|
||||
def preview(req: PreviewRequest, session: dict = Depends(require_admin_dep)):
|
||||
with get_db() as conn:
|
||||
prompt = _load(conn, req.prompt_id, req.slug)
|
||||
try:
|
||||
return preview_prompt(prompt, {"profile_id": session["profile_id"]})
|
||||
except EngineError as exc:
|
||||
_http(exc)
|
||||
|
||||
|
||||
@router.post("/execute")
|
||||
def execute(req: ExecuteRequest, session: dict = Depends(require_auth)):
|
||||
with get_db() as conn:
|
||||
prompt = _load(conn, req.prompt_id, req.slug)
|
||||
if not prompt["active"] and session.get("role") != "admin":
|
||||
raise HTTPException(404, "Prompt nicht gefunden")
|
||||
try:
|
||||
return execute_prompt(
|
||||
prompt,
|
||||
profile_id=session["profile_id"],
|
||||
purpose=req.purpose,
|
||||
data_class=req.data_class,
|
||||
context={"profile_id": session["profile_id"]},
|
||||
)
|
||||
except EngineError as exc:
|
||||
_http(exc)
|
||||
@@ -0,0 +1,29 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
|
||||
from auth import require_admin_dep, require_auth
|
||||
from db import get_db, row_to_dict
|
||||
from entitlements import EntitlementError, check_feature_access, subscription_for
|
||||
|
||||
router = APIRouter(prefix="/api", tags=["subscription"])
|
||||
|
||||
|
||||
@router.get("/subscription")
|
||||
def get_subscription(session: dict = Depends(require_auth)):
|
||||
return subscription_for(session["profile_id"])
|
||||
|
||||
|
||||
@router.get("/features")
|
||||
def list_features(session: dict = Depends(require_admin_dep)):
|
||||
with get_db() as conn:
|
||||
rows = conn.execute("SELECT * FROM features ORDER BY id").fetchall()
|
||||
return [row_to_dict(row) for row in rows]
|
||||
|
||||
|
||||
@router.get("/features/{feature_id}/access")
|
||||
def feature_access(feature_id: str, session: dict = Depends(require_auth)):
|
||||
try:
|
||||
return check_feature_access(session["profile_id"], feature_id)
|
||||
except EntitlementError as exc:
|
||||
raise HTTPException(status_code=exc.status_code, detail={"code": exc.code, "message": exc.message}) from exc
|
||||
@@ -0,0 +1,122 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from auth import hash_password, require_admin_dep, require_auth
|
||||
from db import get_db, row_to_dict
|
||||
|
||||
router = APIRouter(prefix="/api/users", tags=["users"])
|
||||
|
||||
PUBLIC_FIELDS = "id, email, name, role, status, tier_id, created"
|
||||
|
||||
|
||||
class CreateUserRequest(BaseModel):
|
||||
email: str
|
||||
name: str = Field(min_length=1)
|
||||
password: str = Field(min_length=4)
|
||||
role: str = "user"
|
||||
|
||||
|
||||
class PatchUserRequest(BaseModel):
|
||||
name: str | None = None
|
||||
role: str | None = None
|
||||
status: str | None = None
|
||||
password: str | None = None
|
||||
|
||||
|
||||
def _active_admin_count(conn, exclude_id: str | None = None) -> int:
|
||||
if exclude_id:
|
||||
row = conn.execute(
|
||||
"SELECT COUNT(*) AS n FROM profiles WHERE role = 'admin' AND status = 'active' AND id != ?",
|
||||
(exclude_id,),
|
||||
).fetchone()
|
||||
else:
|
||||
row = conn.execute(
|
||||
"SELECT COUNT(*) AS n FROM profiles WHERE role = 'admin' AND status = 'active'"
|
||||
).fetchone()
|
||||
return int(row["n"])
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_users(session: dict = Depends(require_admin_dep)):
|
||||
with get_db() as conn:
|
||||
rows = conn.execute(f"SELECT {PUBLIC_FIELDS} FROM profiles ORDER BY created").fetchall()
|
||||
return [row_to_dict(row) for row in rows]
|
||||
|
||||
|
||||
@router.post("")
|
||||
def create_user(req: CreateUserRequest, session: dict = Depends(require_admin_dep)):
|
||||
if req.role not in {"user", "admin"}:
|
||||
raise HTTPException(400, "Rolle muss user oder admin sein")
|
||||
profile_id = str(uuid.uuid4())
|
||||
try:
|
||||
with get_db() as conn:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO profiles (id, email, name, password_hash, role, status, tier_id)
|
||||
VALUES (?, ?, ?, ?, ?, 'active', 'local')
|
||||
""",
|
||||
(
|
||||
profile_id,
|
||||
req.email.lower().strip(),
|
||||
req.name.strip(),
|
||||
hash_password(req.password),
|
||||
req.role,
|
||||
),
|
||||
)
|
||||
prof = row_to_dict(conn.execute(f"SELECT {PUBLIC_FIELDS} FROM profiles WHERE id = ?", (profile_id,)).fetchone())
|
||||
except Exception as exc:
|
||||
if "UNIQUE" in str(exc).upper():
|
||||
raise HTTPException(409, "E-Mail ist bereits vergeben") from exc
|
||||
raise
|
||||
return prof
|
||||
|
||||
|
||||
@router.patch("/{profile_id}")
|
||||
def patch_user(profile_id: str, req: PatchUserRequest, session: dict = Depends(require_admin_dep)):
|
||||
with get_db() as conn:
|
||||
current = row_to_dict(conn.execute("SELECT * FROM profiles WHERE id = ?", (profile_id,)).fetchone())
|
||||
if not current:
|
||||
raise HTTPException(404, "Nutzer nicht gefunden")
|
||||
name = req.name.strip() if req.name is not None else current["name"]
|
||||
role = req.role if req.role is not None else current["role"]
|
||||
status = req.status if req.status is not None else current["status"]
|
||||
if role not in {"user", "admin"}:
|
||||
raise HTTPException(400, "Rolle muss user oder admin sein")
|
||||
if status not in {"active", "disabled"}:
|
||||
raise HTTPException(400, "Status muss active oder disabled sein")
|
||||
becomes_non_admin = current["role"] == "admin" and (role != "admin" or status == "disabled")
|
||||
if becomes_non_admin and _active_admin_count(conn, exclude_id=profile_id) < 1:
|
||||
raise HTTPException(400, "Der letzte aktive Admin kann nicht entfernt werden")
|
||||
password_hash = current["password_hash"]
|
||||
if req.password:
|
||||
if len(req.password) < 4:
|
||||
raise HTTPException(400, "Passwort muss mind. 4 Zeichen haben")
|
||||
password_hash = hash_password(req.password)
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE profiles SET name = ?, role = ?, status = ?, password_hash = ?
|
||||
WHERE id = ?
|
||||
""",
|
||||
(name, role, status, password_hash, profile_id),
|
||||
)
|
||||
if status == "disabled":
|
||||
conn.execute("DELETE FROM sessions WHERE profile_id = ?", (profile_id,))
|
||||
return row_to_dict(conn.execute(f"SELECT {PUBLIC_FIELDS} FROM profiles WHERE id = ?", (profile_id,)).fetchone())
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
def my_account(session: dict = Depends(require_auth)):
|
||||
with get_db() as conn:
|
||||
prof = row_to_dict(
|
||||
conn.execute(
|
||||
f"SELECT {PUBLIC_FIELDS} FROM profiles WHERE id = ?",
|
||||
(session["profile_id"],),
|
||||
).fetchone()
|
||||
)
|
||||
if not prof:
|
||||
raise HTTPException(401, "Profil nicht gefunden")
|
||||
return prof
|
||||
Reference in new issue
Block a user