Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/utils/helpers/.server/PermissionsService.ts
T

152 lines
6.6 KiB
TypeScript

import { redirect } from "react-router";
import { isAdminPermissionName } from "@hivegrid/db/admin-permissions";
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, userHasPermission } from "~/utils/db/permissions/userRoles.db.server";
import { getTenantMember } from "~/utils/db/tenants.db.server";
import { getUserInfo } from "~/utils/session.server";
import { getTenantBillingReadOnlyState } from "~/utils/services/.server/billingStatusService";
import { getTenantDeletionReadOnlyState } from "~/utils/services/.server/tenantDeletionStatusService";
import { getHostRoutingContextFromRequest } from "~/utils/app/HostRouting.server";
import { requireAdminIdentityPermission } from "~/services/admin/admin-identity.server";
import { NOT_FOUND_ENVELOPE } from "~/utils/errors.server";
const BILLING_READ_ONLY_MUTATION_ENVELOPE = { error: { code: "READ_ONLY", messageKey: "billing:status.readOnly" } };
const DELETION_READ_ONLY_MUTATION_ENVELOPE = { error: { code: "READ_ONLY", messageKey: "settings.privacy.deletion.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);
}
/**
* AK-P21 — during the tenant-deletion grace window the privacy area stays
* writable: admins must be able to withdraw the request and pull a GDPR
* export; users must be able to manage their account deletion.
*/
export function isDeletionReadOnlyBypassPath(requestUrl: string): boolean {
const pathname = new URL(requestUrl).pathname;
return /\/settings\/privacy(\/|$)/.test(pathname);
}
export async function assertTenantWritableForRequest(request: Request, tenantId: string | null) {
if (!tenantId || !isMutatingRequest(request)) {
return;
}
if (!isBillingReadOnlyBypassPath(request.url)) {
const billingState = await getTenantBillingReadOnlyState(tenantId);
if (billingState.readOnly) {
throw Response.json(BILLING_READ_ONLY_MUTATION_ENVELOPE, { status: 423 });
}
}
// AK-P21 deletion_pending read-only: reuse of the AK-P20 frozen mechanism.
if (!isDeletionReadOnlyBypassPath(request.url)) {
const deletionState = await getTenantDeletionReadOnlyState(tenantId);
if (deletionState.readOnly) {
throw Response.json(DELETION_READ_ONLY_MUTATION_ENVELOPE, { status: 423 });
}
}
}
export async function getUserPermission({ userId, permissionName, tenantId }: { userId: string; permissionName: string; tenantId?: string | null }) {
const permission = await getPermissionName(permissionName);
if (!permission) {
return { permission, userPermission: undefined };
}
// 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 (getHostRoutingContextFromRequest(request) === "admin") {
if (!isAdminPermissionName(permissionName)) {
throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
}
await requireAdminIdentityPermission(request, permissionName);
return true;
}
// 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);
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;
}