Files
hats-app/lib/get-access-data.tsx
T
Ichsan Kurniawan 7f8e6637e4 Move auth config and build admin menus
Extract NextAuth configuration into a shared library, load admin sidebar items from role permissions, and update related RBAC types and UI.
2026-11-06 18:25:54 +07:00

56 lines
1.9 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 } from "next-auth";
import { ResponseData } from "@/types/types";
import { redirect } from "next/navigation";
import { authOptions } from "./auth";
export const getAccessData = cache(async () => {
const session = await getServerSession(authOptions)
// 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 reqAccessPagePermission(path: string, action: string = "view", redirectPage: "/forbidden") {
const accessData = await getAccessData();
// Check whether the current page is registered
const menu = accessData?.role_detail?.find((item: any) => item.menu?.path_url === path);
if (!menu) {
redirect(redirectPage);
}
// Check whether the user has permission
if (!menu.action?.includes(action)) {
redirect(redirectPage);
}
return menu;
}