// "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; }