fiddy/apps/web/lib/server/group-access.ts
2026-02-11 23:45:15 -08:00

38 lines
1.4 KiB
TypeScript

if (process.env.NODE_ENV !== "test")
require("server-only");
import getPool from "@/lib/server/db";
import { apiError } from "@/lib/server/errors";
export type GroupRole = "MEMBER" | "GROUP_ADMIN" | "GROUP_OWNER";
export async function getGroupRole(userId: number, groupId: number): Promise<GroupRole | null> {
const pool = getPool();
const { rows } = await pool.query(
"select role from group_members where user_id=$1 and group_id=$2",
[userId, groupId]
);
return (rows[0]?.role as GroupRole | undefined) ?? null;
}
export function isAdminRole(role: GroupRole | null | undefined) {
return role === "GROUP_ADMIN" || role === "GROUP_OWNER";
}
export async function requireGroupMember(userId: number, groupId: number): Promise<GroupRole> {
const role = await getGroupRole(userId, groupId);
if (!role) apiError("FORBIDDEN", { userId, groupId });
return role;
}
export async function requireGroupAdmin(userId: number, groupId: number): Promise<GroupRole> {
const role = await getGroupRole(userId, groupId);
if (!isAdminRole(role)) apiError("FORBIDDEN", { userId, groupId });
return role!;
}
export async function requireGroupOwner(userId: number, groupId: number): Promise<GroupRole> {
const role = await getGroupRole(userId, groupId);
if (role !== "GROUP_OWNER") apiError("FORBIDDEN", { userId, groupId });
return role;
}