File size: 1,250 Bytes
9d4a3b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import { and, eq } from "drizzle-orm";
import { getDb } from "@/db";
import { memberships, organizations, users } from "@/db/schema";
import { ApiError } from "./api";
import { hasPermission, type Permission, type Role } from "./rbac";

export async function getTenantForUser(userId: string, requestedTenantId?: string | null) {
  const rows = await getDb()
    .select({ membership: memberships, organization: organizations })
    .from(memberships)
    .innerJoin(organizations, eq(organizations.id, memberships.organizationId))
    .where(requestedTenantId
      ? and(eq(memberships.userId, userId), eq(memberships.organizationId, requestedTenantId))
      : eq(memberships.userId, userId))
    .limit(1);
  return rows[0] ?? null;
}

export async function requireTenant(user: typeof users.$inferSelect, requestedTenantId?: string | null) {
  const context = await getTenantForUser(user.id, requestedTenantId);
  if (!context) throw new ApiError(403, "Tenant membership is required.", "tenant_required");
  return context;
}

export function requireTenantPermission(role: Role, permission: Permission) {
  if (!hasPermission(role, permission)) throw new ApiError(403, "You do not have permission to perform this action.", "permission_denied");
}