Spaces:
Running
Running
Download core/db/rls.py from Aynkhn/WorkPilot-AI: direct link, hf CLI and curl.
- Browser
- Download file 1.53 kB
-
https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/core/db/rls.py
- Command line
-
hf download hf://spaces/Aynkhn/WorkPilot-AI/core/db/rls.py
-
curl -L -o rls.py https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/core/db/rls.py
1.53 kB
| """Row-level security helpers used by Alembic migrations. | |
| Every tenant table gets ``ENABLE`` + ``FORCE ROW LEVEL SECURITY`` so even the table | |
| owner is filtered (only superusers and BYPASSRLS roles skip RLS; the app role is neither). | |
| """ | |
| from __future__ import annotations | |
| from sqlalchemy import text | |
| from sqlalchemy.engine import Connection | |
| from core.db.base import Base | |
| CURRENT_TENANT = "NULLIF(current_setting('app.tenant_id', true), '')::uuid" | |
| CURRENT_USER_ID = "NULLIF(current_setting('app.user_id', true), '')::uuid" | |
| def tenant_policy_sql(table: str, column: str = "tenant_id") -> list[str]: | |
| return [ | |
| f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY", | |
| f"ALTER TABLE {table} FORCE ROW LEVEL SECURITY", | |
| f"DROP POLICY IF EXISTS tenant_isolation ON {table}", | |
| ( | |
| f"CREATE POLICY tenant_isolation ON {table} " | |
| f"USING ({column} = {CURRENT_TENANT}) " | |
| f"WITH CHECK ({column} = {CURRENT_TENANT})" | |
| ), | |
| ] | |
| def enable_tenant_rls(conn: Connection, table: str, column: str = "tenant_id") -> None: | |
| for stmt in tenant_policy_sql(table, column): | |
| conn.execute(text(stmt)) | |
| def tenant_tables() -> list[str]: | |
| """Names of all mapped tables whose model declares ``__rls__ = True``.""" | |
| names: list[str] = [] | |
| for mapper in Base.registry.mappers: | |
| cls = mapper.class_ | |
| if getattr(cls, "__rls__", False): | |
| names.append(cls.__tablename__) | |
| return sorted(set(names)) | |