26 lines
1.2 KiB
TypeScript
26 lines
1.2 KiB
TypeScript
import type { Prisma } from "@hivegrid/db/prisma-browser";
|
|
|
|
import { db } from "~/utils/db.server";
|
|
|
|
// R-P2b — App-seitiger RLS-Adoptions-Mechanismus (AD-1). Setzt den Tenant-Kontext
|
|
// TRANSAKTIONS-LOKAL (set_config(..., true) entspricht SET LOCAL und ist damit PgBouncer-
|
|
// Transaction-Pooling-kompatibel: der Wert lebt nur bis COMMIT/ROLLBACK auf genau dieser
|
|
// Verbindung) und fuehrt die Queries innerhalb derselben Transaktion aus, sodass die
|
|
// RLS-Policies (USING/WITH CHECK auf current_setting('app.tenant_id')) greifen.
|
|
//
|
|
// Tenant-bezogene Datenzugriffe eines Moduls laufen ueber diesen Wrapper, sobald die jeweilige
|
|
// Tabelle RLS-aktiviert ist (siehe prisma/rls/tenant-isolation.sql). Ohne gesetzten Kontext
|
|
// liefert eine RLS-Tabelle der App-Rolle KEINE Zeile.
|
|
|
|
export type TenantRlsClient = Prisma.TransactionClient;
|
|
|
|
export async function withTenantRLS<T>(tenantId: string, callback: (tx: TenantRlsClient) => Promise<T>): Promise<T> {
|
|
if (!tenantId) {
|
|
throw new Error("withTenantRLS requires a non-empty tenantId");
|
|
}
|
|
return db.$transaction(async (tx: TenantRlsClient) => {
|
|
await tx.$executeRaw`SELECT set_config('app.tenant_id', ${tenantId}, true)`;
|
|
return callback(tx);
|
|
});
|
|
}
|