import { Prisma } from "@toolctrl/db/prisma-browser"; import { redirect } from "react-router"; import { RowPermissionsDto } from "~/application/dtos/entities/RowPermissionsDto"; import { DefaultAdminRoles } from "~/application/dtos/shared/DefaultAdminRoles"; import { DefaultPermission } from "~/application/dtos/shared/DefaultPermissions"; import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus"; import { RowAccess, RowAccessTypes } from "~/application/enums/entities/RowAccess"; import { RowWithDetails } from "~/utils/db/entities/rows.db.server"; import { getMyGroups } from "~/utils/db/permissions/groups.db.server"; import { getPermissionName } from "~/utils/db/permissions/permissions.db.server"; import { findPermissionByUser, findUserRolesByIds, getUserRoles, getUserRoleInAdmin, userHasPermission } from "~/utils/db/permissions/userRoles.db.server"; import { getTenantMember } from "~/utils/db/tenants.db.server"; import { getEntityPermission } from "~/utils/helpers/PermissionsHelper"; import { getIsSuperAdminByUserId } from "~/utils/loaders.middleware"; import { getUserInfo } from "~/utils/session.server"; import { getAuthUserWithoutPasswordById as getUser } from "@toolctrl/db/auth-boundary.server"; const OPERATOR_ADMIN_BYPASS_DESCRIPTION = "Operator admin tenant permission bypass"; 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 type EntityPermissionOperation = "view" | "read" | "create" | "update" | "delete"; export async function verifyUserHasEntityPermission( request: Request, entity: { name: string }, operation: EntityPermissionOperation, tenantId: string | null = null ) { return verifyUserHasPermission(request, getEntityPermission(entity, operation), tenantId); } 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"); } 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; } export async function getUserRowPermission(row: RowWithDetails, tenantId?: string | null, userId?: string): Promise { const accessLevels: RowAccess[] = ["none"]; let isOwner = false; if (tenantId && userId && (await getIsSuperAdminByUserId(userId))) { isOwner = true; } else if (tenantId === null && userId) { const isSuperAdmin = await getUserRoleInAdmin(userId, DefaultAdminRoles.SuperAdmin); if (isSuperAdmin) { isOwner = true; } } else if (tenantId === undefined && userId === undefined) { accessLevels.push("view"); } else { isOwner = !!userId && userId === row.createdByUserId; if (tenantId) { const existing = row.permissions.find((f) => f.tenantId === tenantId); if (existing) { accessLevels.push(existing.access as RowAccess); } } else if (userId) { if (row.createdByUserId === userId || row.createdByUserId === null) { accessLevels.push("delete"); } const existing = row.permissions.find((f) => f.userId === userId); if (existing) { accessLevels.push(existing.access as RowAccess); } } if (tenantId !== undefined && userId) { const inRoles = row.permissions .filter((f) => f.roleId) .map((f) => f.roleId) .map((f) => f as string); if (inRoles.length > 0) { const userRoles = await findUserRolesByIds(userId, tenantId, inRoles); userRoles.forEach((userRole) => { const existing = row.permissions.find((f) => f.roleId === userRole.roleId); if (existing) { accessLevels.push(existing.access as RowAccess); } }); } const inGroups = row.permissions .filter((f) => f.groupId) .map((f) => f.groupId) .map((f) => f as string); if (inGroups.length > 0) { const userGroups = await getMyGroups(userId, tenantId); userGroups.forEach((userGroup) => { const existing = row.permissions.find((f) => f.groupId === userGroup.id); if (existing) { accessLevels.push(existing.access as RowAccess); } }); } } } let access: RowAccess | undefined = undefined; for (let idx = RowAccessTypes.length - 1; idx >= 0; idx--) { const accessType = RowAccessTypes[idx]; if (accessLevels.includes(accessType)) { access = accessType; break; } } const rowPermissions: RowPermissionsDto = { canRead: isOwner || (access && access !== "none"), canComment: isOwner || access === "comment" || access === "edit" || access === "delete", canUpdate: isOwner || access === "edit" || access === "delete", canDelete: isOwner || access === "delete", isOwner, }; return rowPermissions; } export type RowPermissionsFilter = Prisma.RowWhereInput | {}; export async function getRowPermissionsCondition({ tenantId, userId }: { tenantId?: string | null; userId?: string }) { if (tenantId && userId && (await getIsSuperAdminByUserId(userId))) { return {}; } const OR_CONDITIONS: Prisma.RowWhereInput[] = []; const readableAccess = { not: "none" }; if (tenantId) { OR_CONDITIONS.push(...[{ permissions: { some: { tenantId, access: readableAccess } } }]); if (userId) { OR_CONDITIONS.push(...[{ createdByUserId: userId }, { permissions: { some: { userId, access: readableAccess } } }]); } } else { if (userId) { OR_CONDITIONS.push(...[{ createdByUserId: null }, { createdByUserId: userId }, { permissions: { some: { userId, access: readableAccess } } }]); } } if (tenantId !== undefined && userId) { const userRoles = await getUserRoles(userId, tenantId); userRoles.forEach((userRole) => { OR_CONDITIONS.push(...[{ permissions: { some: { roleId: userRole.roleId, access: readableAccess } } }]); }); const userGroups = await getMyGroups(userId, tenantId); userGroups.forEach((userGroup) => { OR_CONDITIONS.push(...[{ permissions: { some: { groupId: userGroup.id, access: readableAccess } } }]); }); } return { OR: OR_CONDITIONS, }; }