refactor(api): share owned resource read access
This commit is contained in:
@@ -1,48 +1,20 @@
|
||||
import { PreviewResolvedHolidaysSchema } from "@capakraken/shared";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { z } from "zod";
|
||||
import { findUniqueOrThrow } from "../db/helpers.js";
|
||||
import { asHolidayResolverDb, getResolvedCalendarHolidays } from "../lib/holiday-availability.js";
|
||||
import { protectedProcedure } from "../trpc.js";
|
||||
import { type HolidayReadContext } from "./holiday-calendar-shared.js";
|
||||
|
||||
function canManageHolidayResourceReads(ctx: HolidayReadContext): boolean {
|
||||
const role = ctx.dbUser?.systemRole;
|
||||
return role === "ADMIN" || role === "MANAGER";
|
||||
}
|
||||
|
||||
async function findOwnedHolidayResourceId(ctx: HolidayReadContext): Promise<string | null> {
|
||||
if (!ctx.dbUser?.id) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!ctx.db.resource || typeof ctx.db.resource.findFirst !== "function") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const resource = await ctx.db.resource.findFirst({
|
||||
where: { userId: ctx.dbUser.id },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
return resource?.id ?? null;
|
||||
}
|
||||
import { assertCanReadOwnedResource } from "./resource-owned-read-access.js";
|
||||
|
||||
async function assertCanReadHolidayResource(
|
||||
ctx: HolidayReadContext,
|
||||
resourceId: string,
|
||||
): Promise<void> {
|
||||
if (canManageHolidayResourceReads(ctx)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const ownedResourceId = await findOwnedHolidayResourceId(ctx);
|
||||
if (!ownedResourceId || ownedResourceId !== resourceId) {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "You can only view holiday data for your own resource",
|
||||
});
|
||||
}
|
||||
await assertCanReadOwnedResource(
|
||||
ctx,
|
||||
resourceId,
|
||||
"You can only view holiday data for your own resource",
|
||||
);
|
||||
}
|
||||
|
||||
function formatResolvedHolidayDetail(holiday: {
|
||||
|
||||
Reference in New Issue
Block a user