| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- from dataclasses import dataclass
- from fastapi import HTTPException, status
- from sqlalchemy import text
- from sqlalchemy.orm import Session
- @dataclass(frozen=True)
- class Entitlement:
- hauptbetrieb_id: str
- standort_id: str
- abteilung: str | None
- role: str
- priority: int
- @dataclass(frozen=True)
- class Principal:
- username: str
- name: str
- email: str
- role: str
- auth_source: str
- csrf: str
- entitlements: tuple[Entitlement, ...]
- RIGHTS_SQL = text(
- """
- SELECT BR.Hauptbetrieb_ID,
- BR.Standort_ID,
- BR.Abteilung,
- BR.Rolle,
- R.Prioritaet
- FROM dbo.Benutzer_Rechte AS BR
- INNER JOIN dbo.Rollen AS R ON R.Rolle = BR.Rolle AND R.Aktiv = 1
- WHERE LOWER(LTRIM(RTRIM(BR.Benutzer_ID))) = :username
- AND NULLIF(LTRIM(RTRIM(BR.Benutzer_ID)), '') IS NOT NULL
- ORDER BY R.Prioritaet DESC, BR.Rolle ASC
- """
- )
- def load_entitlements(db: Session, username: str) -> tuple[Entitlement, ...]:
- rows = db.execute(RIGHTS_SQL, {"username": username}).mappings().all()
- return tuple(
- Entitlement(
- hauptbetrieb_id=str(row["Hauptbetrieb_ID"]),
- standort_id=str(row["Standort_ID"]),
- abteilung=row["Abteilung"],
- role=row["Rolle"],
- priority=int(row["Prioritaet"]),
- )
- for row in rows
- )
- def highest_role(entitlements: tuple[Entitlement, ...]) -> str:
- if not entitlements:
- raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Keine Berechtigung für diese Anwendung")
- return sorted(entitlements, key=lambda item: (-item.priority, item.role))[0].role
- FORDERUNG_ACCESS_SQL = text(
- """
- SELECT TOP 1 1
- FROM dbo.Forderungen_Kopf AS F
- WHERE F.Client_DB = :client_db
- AND F.Beleg_Nr = :beleg_nr
- AND EXISTS (
- SELECT 1
- FROM dbo.Benutzer_Rechte AS BR
- INNER JOIN dbo.Rollen AS R ON R.Rolle = BR.Rolle AND R.Aktiv = 1
- WHERE LOWER(LTRIM(RTRIM(BR.Benutzer_ID))) = :auth_username
- AND NULLIF(LTRIM(RTRIM(BR.Benutzer_ID)), '') IS NOT NULL
- AND BR.Hauptbetrieb_ID = F.Hauptbetrieb_ID
- AND BR.Standort_ID = F.Standort_ID
- AND (BR.Abteilung IS NULL OR BR.Abteilung = F.Abteilung)
- )
- """
- )
- def ensure_forderung_access(db: Session, principal: Principal, client_db: str, beleg_nr: str) -> None:
- allowed = db.execute(
- FORDERUNG_ACCESS_SQL,
- {"client_db": client_db, "beleg_nr": beleg_nr, "auth_username": principal.username},
- ).first()
- if not allowed:
- raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Forderung nicht gefunden")
- def current_principal(request) -> Principal:
- principal = getattr(request.state, "principal", None)
- if principal is None:
- raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Nicht angemeldet")
- return principal
|