Implement Club Feature Access Probing and Inventory Count
Deploy Development / deploy (push) Successful in 41s
Test Suite / pytest-backend (push) Successful in 40s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 1m42s
Deploy Development / deploy (push) Successful in 41s
Test Suite / pytest-backend (push) Successful in 40s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 1m42s
- Introduced `probe_club_feature_access` to check club feature limits and log access attempts without blocking by default. - Added `_live_inventory_count` function to retrieve current counts for specific features, enhancing feature limit management. - Updated various endpoints to utilize the new probing functionality, ensuring compliance with club feature access rules. - Incremented version to 1.1.0 in version.py to reflect these enhancements in club feature management.
This commit is contained in:
1 parent
c294c27de8
commit
7cfbca40bb
6 files changed
+344
-4
No files matched your search
+145
-2
@@ -2,17 +2,29 @@
|
||||
Vereinsbezogene Feature-Limits (Mitai-v9c-Pattern, Subjekt club_id).
|
||||
|
||||
Spez: .claude/docs/technical/CLUB_MEMBERSHIP_AND_FEATURES.v1.md
|
||||
Enforcement in Routern folgt in M2+ (Phase 2–4); M1 liefert Schema + Prüf-Helfer.
|
||||
Phase 2 (M2): probe_club_feature_access — JSON-Log, kein HTTP-Block.
|
||||
Phase 4 (M5+): CLUB_FEATURE_ENFORCE=1 — HTTP 403 + increment.
|
||||
|
||||
Legacy profil-zentriert: auth.check_feature_access (001 / Mitai-Überbleibsel) — nicht für Shinkan-Limits nutzen.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Dict, Optional
|
||||
from typing import Any, Dict, Optional, TYPE_CHECKING
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from db import get_db, get_cursor
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from tenant_context import TenantContext
|
||||
|
||||
# Bestands-Features: Verbrauch = Live-Zählung in DB (nicht club_feature_usage)
|
||||
_INVENTORY_FEATURES = frozenset(
|
||||
{"exercises", "training_groups", "active_members", "training_programs"}
|
||||
)
|
||||
|
||||
|
||||
def _calculate_next_reset(reset_period: str, *, now: Optional[datetime] = None) -> Optional[datetime]:
|
||||
"""Nächster Reset-Zeitpunkt; None bei 'never'."""
|
||||
@@ -113,6 +125,61 @@ def _resolve_club_limit(cur, club_id: int, feature_id: str, feature_row: dict) -
|
||||
return _normalize_limit(feature_row.get("default_limit"))
|
||||
|
||||
|
||||
def _live_inventory_count(cur, club_id: int, feature_id: str) -> Optional[int]:
|
||||
"""Aktueller Bestand für reset_period=never Features."""
|
||||
if feature_id == "exercises":
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COUNT(*)::int AS c
|
||||
FROM exercises
|
||||
WHERE club_id = %s AND status != 'archived'
|
||||
""",
|
||||
(club_id,),
|
||||
)
|
||||
elif feature_id == "training_groups":
|
||||
cur.execute(
|
||||
"SELECT COUNT(*)::int AS c FROM training_groups WHERE club_id = %s",
|
||||
(club_id,),
|
||||
)
|
||||
elif feature_id == "active_members":
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COUNT(*)::int AS c
|
||||
FROM club_members
|
||||
WHERE club_id = %s AND status = 'active'
|
||||
""",
|
||||
(club_id,),
|
||||
)
|
||||
elif feature_id == "training_programs":
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COUNT(*)::int AS c FROM (
|
||||
SELECT id FROM training_framework_programs WHERE club_id = %s
|
||||
UNION ALL
|
||||
SELECT id FROM training_modules WHERE club_id = %s
|
||||
) t
|
||||
""",
|
||||
(club_id, club_id),
|
||||
)
|
||||
else:
|
||||
return None
|
||||
|
||||
row = cur.fetchone()
|
||||
return int(row["c"] or 0) if row else 0
|
||||
|
||||
|
||||
def resolve_club_id_for_probe(
|
||||
tenant: "TenantContext",
|
||||
*,
|
||||
object_club_id: Optional[int] = None,
|
||||
) -> Optional[int]:
|
||||
"""Verein für Feature-Probe: explizites Objekt > effective_club_id."""
|
||||
if object_club_id is not None:
|
||||
return int(object_club_id)
|
||||
eff = getattr(tenant, "effective_club_id", None)
|
||||
return int(eff) if eff is not None else None
|
||||
|
||||
|
||||
def _maybe_reset_usage(cur, conn, club_id: int, feature_id: str, feature_row: dict, usage_row: Optional[dict]) -> int:
|
||||
"""Setzt Zähler zurück wenn reset_at überschritten; gibt aktuellen used zurück."""
|
||||
used = int(usage_row.get("usage_count") or 0) if usage_row else 0
|
||||
@@ -210,6 +277,12 @@ def _check_club_impl(club_id: int, feature_id: str, conn) -> Dict[str, Any]:
|
||||
usage = cur.fetchone()
|
||||
used = _maybe_reset_usage(cur, conn, club_id, feature_id, feature, usage)
|
||||
|
||||
period = (feature.get("reset_period") or "never").strip().lower()
|
||||
if period == "never" and feature_id in _INVENTORY_FEATURES:
|
||||
inv = _live_inventory_count(cur, club_id, feature_id)
|
||||
if inv is not None:
|
||||
used = inv
|
||||
|
||||
if limit is None:
|
||||
return {
|
||||
"allowed": True,
|
||||
@@ -244,6 +317,76 @@ def _check_club_impl(club_id: int, feature_id: str, conn) -> Dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def club_feature_enforcement_enabled() -> bool:
|
||||
"""Phase 4: Hard-Block aktiv (Env CLUB_FEATURE_ENFORCE=1)."""
|
||||
return os.getenv("CLUB_FEATURE_ENFORCE", "0").strip() == "1"
|
||||
|
||||
|
||||
def probe_club_feature_access(
|
||||
*,
|
||||
feature_id: str,
|
||||
action: str,
|
||||
club_id: Optional[int] = None,
|
||||
profile_id: Optional[int] = None,
|
||||
endpoint: Optional[str] = None,
|
||||
conn=None,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Phase 2: Prüft Vereins-Kontingent, schreibt JSON-Log, blockiert standardmäßig nicht.
|
||||
|
||||
Bei CLUB_FEATURE_ENFORCE=1: HTTP 403 wenn nicht allowed.
|
||||
"""
|
||||
from club_feature_logger import log_club_feature_usage
|
||||
|
||||
if club_id is None:
|
||||
access = {
|
||||
"allowed": True,
|
||||
"limit": None,
|
||||
"used": 0,
|
||||
"remaining": None,
|
||||
"reason": "no_club_context",
|
||||
"plan_id": None,
|
||||
}
|
||||
log_club_feature_usage(
|
||||
club_id=None,
|
||||
profile_id=profile_id,
|
||||
feature_id=feature_id,
|
||||
action=action,
|
||||
access=access,
|
||||
endpoint=endpoint,
|
||||
phase="probe",
|
||||
)
|
||||
return access
|
||||
|
||||
if conn is not None:
|
||||
access = check_club_feature_access(club_id, feature_id, conn=conn)
|
||||
else:
|
||||
with get_db() as c:
|
||||
access = check_club_feature_access(club_id, feature_id, conn=c)
|
||||
|
||||
log_club_feature_usage(
|
||||
club_id=club_id,
|
||||
profile_id=profile_id,
|
||||
feature_id=feature_id,
|
||||
action=action,
|
||||
access=access,
|
||||
endpoint=endpoint,
|
||||
phase="enforce" if club_feature_enforcement_enabled() else "probe",
|
||||
)
|
||||
|
||||
if club_feature_enforcement_enabled() and not access.get("allowed"):
|
||||
limit = access.get("limit")
|
||||
used = access.get("used", 0)
|
||||
detail = (
|
||||
f"Kontingent überschritten für {feature_id} "
|
||||
f"({used}/{limit if limit is not None else '∞'}). "
|
||||
f"Grund: {access.get('reason', 'limit_exceeded')}."
|
||||
)
|
||||
raise HTTPException(status_code=403, detail=detail)
|
||||
|
||||
return access
|
||||
|
||||
|
||||
def increment_club_feature_usage(
|
||||
club_id: int,
|
||||
feature_id: str,
|
||||
|
||||
Reference in new issue
Block a user