import { redirect } from "react-router"; import { DefaultAdminRoles } from "~/application/dtos/shared/DefaultAdminRoles"; import { DefaultPermission } from "~/application/dtos/shared/DefaultPermissions"; import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus"; import { getPermissionName } from "~/utils/db/permissions/permissions.db.server"; import { findPermissionByUser, getUserRoleInAdmin, userHasPermission } from "~/utils/db/permissions/userRoles.db.server"; import { getTenantMember } from "~/utils/db/tenants.db.server"; import { getIsSuperAdminByUserId } from "~/utils/loaders.middleware"; import { getUserInfo } from "~/utils/session.server"; import { getAuthUserWithoutPasswordById as getUser } from "@hivegrid/db/auth-boundary.server"; import { getTenantBillingReadOnlyState } from "~/utils/services/.server/billingStatusService"; const OPERATOR_ADMIN_BYPASS_DESCRIPTION = "Operator admin tenant permission bypass"; const BILLING_READ_ONLY_MUTATION_ENVELOPE = { error: { code: "READ_ONLY", messageKey: "billing:status.readOnly" } }; function isMutatingRequest(request: Request): boolean { return !["GET", "HEAD", "OPTIONS"].includes(request.method.toUpperCase()); } export function isBillingReadOnlyBypassPath(requestUrl: string): boolean { const pathname = new URL(requestUrl).pathname; return /\/settings\/subscription\/?$/.test(pathname); } export async function assertTenantWritableForRequest(request: Request, tenantId: string | null) { if (!tenantId || !isMutatingRequest(request) || isBillingReadOnlyBypassPath(request.url)) { return; } const billingState = await getTenantBillingReadOnlyState(tenantId); if (billingState.readOnly) { throw Response.json(BILLING_READ_ONLY_MUTATION_ENVELOPE, { status: 423 }); } } export async function getUserPermission({ userId, permissionName, tenantId }: { userId: string; permissionName: string; tenantId?: string | null }) { if (tenantId) { const user = await getUser(userId); const isOperatorAdmin = !!user?.admin || (await getIsSuperAdminByUserId(userId)) || !!(await getUserRoleInAdmin(userId, DefaultAdminRoles.SuperAdmin)); if (isOperatorAdmin) { return { permission: { id: "operator-admin-bypass", name: permissionName, description: OPERATOR_ADMIN_BYPASS_DESCRIPTION }, userPermission: permissionName, }; } } const permission = await getPermissionName(permissionName); if (!permission) { return { permission, userPermission: undefined }; } if (tenantId && (await getIsSuperAdminByUserId(userId))) { return { permission, userPermission: permission.name }; } // const userRoles = await getUserRoles(userId ?? undefined, tenantId ?? null); // let userPermission: Permission | undefined = undefined; // userRoles.forEach((userRole) => { // userRole.role.permissions.forEach((rolePermission) => { // if (rolePermission.permission.name === permissionName) { // userPermission = rolePermission.permission; // } // }); // }); const userPermission = await findPermissionByUser(permissionName, userId, tenantId); return { permission, userPermission }; } export type PermissionCheckDeniedReason = "unauthenticated" | "permission-denied"; export type PermissionCheckResult = | { allowed: true; permissionName: DefaultPermission; tenantId: string | null; reason?: undefined } | { allowed: false; permissionName: DefaultPermission; tenantId: string | null; reason: PermissionCheckDeniedReason }; export function buildPermissionDeniedUrl({ permissionName, tenantId, requestUrl, }: { permissionName: DefaultPermission; tenantId: string | null; requestUrl: string; }) { const requestPathname = new URL(requestUrl).pathname; const searchParams = new URLSearchParams([["redirect", requestPathname]]); const tenantSegment = tenantId ? `/${encodeURIComponent(tenantId)}` : ""; return `/unauthorized/${permissionName}${tenantSegment}?${searchParams}`; } export function shapePermissionCheckResult({ allowed, permissionName, tenantId, reason, }: { allowed: boolean; permissionName: DefaultPermission; tenantId: string | null; reason?: PermissionCheckDeniedReason; }): PermissionCheckResult { if (allowed) { return { allowed: true, permissionName, tenantId }; } return { allowed: false, permissionName, tenantId, reason: reason ?? "permission-denied" }; } export async function verifyUserHasPermission(request: Request, permissionName: DefaultPermission, tenantId: string | null = null) { // if (permissionName.startsWith("entity.")) { // return true; // } // console.log("verifyUserHasPermission", permissionName); const userInfo = await getUserInfo(request); if (!userInfo.userId) { shapePermissionCheckResult({ allowed: false, permissionName, tenantId, reason: "unauthenticated" }); throw Error("Unauthorized"); } await assertTenantWritableForRequest(request, tenantId); if (tenantId) { const user = await getUser(userInfo.userId); const isOperatorAdmin = !!user?.admin || (await getIsSuperAdminByUserId(userInfo.userId)) || !!(await getUserRoleInAdmin(userInfo.userId, DefaultAdminRoles.SuperAdmin)); if (isOperatorAdmin) { shapePermissionCheckResult({ allowed: true, permissionName, tenantId }); return true; } } const permission = await getPermissionName(permissionName); if (!permission) { shapePermissionCheckResult({ allowed: false, permissionName, tenantId, reason: "permission-denied" }); throw Error(`Unknown permission: ${permissionName}`); } if (tenantId) { const tenantMember = await getTenantMember(userInfo.userId, tenantId); if (!tenantMember || tenantMember.status !== TenantUserStatus.ACTIVE) { const decision = shapePermissionCheckResult({ allowed: false, permissionName, tenantId, reason: "permission-denied" }); throw redirect(buildPermissionDeniedUrl({ permissionName: decision.permissionName, tenantId: decision.tenantId, requestUrl: request.url })); } } const userPermission = await userHasPermission(userInfo.userId, tenantId, permissionName); if (!userPermission) { const decision = shapePermissionCheckResult({ allowed: false, permissionName, tenantId, reason: "permission-denied" }); throw redirect(buildPermissionDeniedUrl({ permissionName: decision.permissionName, tenantId: decision.tenantId, requestUrl: request.url })); } shapePermissionCheckResult({ allowed: true, permissionName, tenantId }); return true; }