63 lines
2.7 KiB
TypeScript
63 lines
2.7 KiB
TypeScript
import { CatalogError, foundationErrors, requirePermission } from "@hivegrid/foundation";
|
|
import { requireAuth } from "~/utils/loaders.middleware";
|
|
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
|
import { getUserInfo } from "~/utils/session.server";
|
|
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
|
|
import { getPermissionsByUser } from "~/utils/db/permissions/userRoles.db.server";
|
|
import { PROJECTS_MODULE_KEY } from "./projectRoutePaths";
|
|
import { AuftragServiceError } from "./auftragService.server";
|
|
import { ProjectServiceError, type ProjectVisibilityContext } from "./projectService.server";
|
|
|
|
export type ProjectRouteContext = ProjectVisibilityContext & {
|
|
tenantId: string;
|
|
hasModule: boolean;
|
|
};
|
|
|
|
export async function loadProjectContext({
|
|
request,
|
|
params,
|
|
requireModule = false,
|
|
}: {
|
|
request: Request;
|
|
params: Record<string, string | undefined>;
|
|
requireModule?: boolean;
|
|
}): Promise<ProjectRouteContext> {
|
|
await requireAuth({ request, params });
|
|
const [tenantId, userInfo] = await Promise.all([getTenantIdFromUrl(params), getUserInfo(request)]);
|
|
if (!tenantId || !userInfo.userId) {
|
|
throw new CatalogError(foundationErrors.notFound);
|
|
}
|
|
const [hasModule, permissions] = await Promise.all([
|
|
tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: PROJECTS_MODULE_KEY }),
|
|
getPermissionsByUser(userInfo.userId, tenantId),
|
|
]);
|
|
if (requireModule && !hasModule) {
|
|
throw new CatalogError(foundationErrors.notFound, { module: PROJECTS_MODULE_KEY });
|
|
}
|
|
return { tenantId, userId: userInfo.userId, permissions, hasModule };
|
|
}
|
|
|
|
export function requireProjectPermission(ctx: ProjectRouteContext, permission: string): ProjectRouteContext {
|
|
requirePermission({ tenantId: ctx.tenantId, userId: ctx.userId, permissions: ctx.permissions }, permission);
|
|
return ctx;
|
|
}
|
|
|
|
export function requireAnyProjectPermission(ctx: ProjectRouteContext, permissions: readonly string[]): ProjectRouteContext {
|
|
if (permissions.some((permission) => ctx.permissions.includes(permission))) return ctx;
|
|
requirePermission({ tenantId: ctx.tenantId, userId: ctx.userId, permissions: ctx.permissions }, permissions[0] ?? "projects.read_own");
|
|
return ctx;
|
|
}
|
|
|
|
export function projectActionErrorResponse(error: unknown): Response {
|
|
if (error instanceof CatalogError) {
|
|
return Response.json({ error: error.i18nKey, code: error.code }, { status: error.status });
|
|
}
|
|
if (error instanceof ProjectServiceError) {
|
|
return Response.json({ error: error.messageKey }, { status: 400 });
|
|
}
|
|
if (error instanceof AuftragServiceError) {
|
|
return Response.json({ error: error.messageKey }, { status: 400 });
|
|
}
|
|
throw error;
|
|
}
|