Files
hats-app/lib/get-access-data.tsx
T
Ichsan Kurniawan 279b642a7a Apply RBAC permissions across admin and tasks
Enforce page access and action-level permissions across admin and task views, including exports and record actions. Move user creation to a client component behind server-side permission checks, standardize data fetching, and remove the deprecated user-role route.
2026-11-09 17:32:31 +07:00

100 lines
3.5 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 | string[], action: string = "view") {
const accessData = await getAccessData();
const normalize = (p: string) => (p || '').trim().replace(/^\/+|\/+$/g, '').toLowerCase();
const targetPaths = (Array.isArray(path) ? path : [path]).map(normalize);
// Check whether the current page is registered
const menu = accessData?.role_detail?.find((item: any) => {
const itemPath = normalize(item.menu?.path_url || '');
if (!itemPath) return false;
if (targetPaths.includes(itemPath)) return true;
if (targetPaths.includes('rbac/action-permissions') && itemPath === 'rbac/action-pemission') return true;
if (targetPaths.includes('rbac/action-pemission') && itemPath === 'rbac/action-permissions') return true;
return false;
});
if (!menu?.menu) {
forbidden();
}
// Role-specific assigned actions take precedence; fallback to menu actions if role actions are absent
const permittedActions: string[] = (Array.isArray(menu?.action) && menu.action.length > 0)
? menu.action
: (Array.isArray(menu?.menu?.action) ? menu.menu.action : []);
// Check whether the user has permission
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
}