Files
hats-app/lib/get-access-data.tsx
T
Ichsan Kurniawan 7d6549f892 Enforce page and action-based permissions
Use RBAC permissions to guard dashboard pages and control approval and export actions. Reuse cached sessions and refine permission badges and available icons.
2026-11-10 16:32:15 +07:00

102 lines
3.2 KiB
TypeScript

// "use server" opens a door from the client to the server, Exports must be async Server Functions. use for Form submissions, mutations, client-triggered server actions
// But import "server-only" locks the client out of a module, cannot call by client components. use for Database, auth, secret API calls
import "server-only";
import { cache } from "react";
import { getServerSession, type Session } from "next-auth";
import { ResponseData } from "@/types/types";
import { forbidden, redirect } from "next/navigation";
import { authOptions } from "./auth";
export const getCacheServerSession = cache(async (): Promise<Session | null> => {
return getServerSession(authOptions)
})
export const getAccessData = cache(async () => {
const session = await getCacheServerSession()
// Validate session first
if (!session?.user?.detail?.role?.id) {
redirect("/auth?error=Session%20error%20or%20has%20expired");
}
const res = await fetch(`${process.env.BASE_URL_API}/role/${session?.user.detail.role.id}`,
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${session?.user.access_token}`,
},
cache: "no-store",
}
);
if (!res.ok) {
if (res.status === 401 || res.status === 403) return redirect(`/auth?error=Session error or has expired !`)
// This will activate the closest `error.js` Error Boundar`)
throw new Error(`Failed to retrieve access data (${res.status}) ${res.statusText}`);
}
const data: ResponseData = await res.json()
return data.data
});
export async function getAccessPagePermission(path: string, action: string = "VIEW", isAdminMenu: boolean = true) {
const accessData = await getAccessData();
const normalizePath = (value?: string) => (value ?? "").trim().replace(/\/+/g, "/").replace(/\/$/, "").replace(/^$/, "/").toLowerCase();
const targetPath = normalizePath(path);
const menu = accessData?.role_detail?.find((item: any) => {
const menuPath = normalizePath(item.menu?.path_url);
return (
menuPath === targetPath &&
item.menu?.is_admin_menu === isAdminMenu
);
});
if (!menu?.menu) {
forbidden();
}
const permittedActions: string[] =
Array.isArray(menu.action) && menu.action.length > 0
? menu.action
: Array.isArray(menu.menu.action)
? menu.menu.action
: [];
const hasPermission = permittedActions.some((act: string) => act.toUpperCase() === action.toUpperCase());
if (!hasPermission) {
forbidden();
}
return permittedActions;
}
export async function getNonAdminAccessPagePermission(path: string, action: string = "view") {
const session = await getCacheServerSession()
if (!session?.user?.detail?.role?.role_detail) {
redirect("/auth?error=Session%20error%20or%20has%20expired");
}
const menu = session.user.detail?.role?.role_detail?.find(item => item.menu.path_url === path)
if (!menu) {
forbidden()
}
if (!menu.action?.includes(action.toUpperCase())) {
forbidden()
}
return menu.action
}