From 7f8e6637e4e39246b9a71d168621ff2da99efdd1 Mon Sep 17 00:00:00 2001 From: Ichsan Kurniawan <43689091+ichsankurnia@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:25:54 +0700 Subject: [PATCH] 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. --- app/(dashboard)/(main)/page-backup.tsx | 2 +- app/(dashboard)/(main)/page.tsx | 2 +- app/(dashboard)/history/attendance/index.tsx | 2 +- .../history/leave-permit/index.tsx | 2 +- app/(dashboard)/history/page.tsx | 2 +- app/(dashboard)/iam-here/page.tsx | 2 +- app/(dashboard)/profile/page.tsx | 2 +- app/@modal/(.)performance/[id]/page.tsx | 2 +- app/actions/user.ts | 2 +- app/admin/administration/area/page.tsx | 2 +- app/admin/administration/company/page.tsx | 2 +- app/admin/administration/division/page.tsx | 2 +- app/admin/administration/user/page.tsx | 2 +- app/admin/audit-trail/page.tsx | 2 +- app/admin/components/Breadcrumb.tsx | 6 +- app/admin/components/Sidebar.tsx | 9 +- app/admin/components/SkeletonSidebar.tsx | 25 +++ app/admin/device/device-type/page.tsx | 2 +- app/admin/device/device/page.tsx | 2 +- app/admin/global-parameter/page.tsx | 2 +- app/admin/information/employee-type/page.tsx | 2 +- app/admin/information/master-status/page.tsx | 2 +- app/admin/information/position/page.tsx | 2 +- app/admin/information/working-status/page.tsx | 2 +- app/admin/layout.tsx | 81 ++++++- app/admin/rbac/user-role/[id]/page.tsx | 4 +- .../rbac/user-role/component/RoleForm.tsx | 6 +- app/admin/rbac/user-role/component/index.tsx | 4 +- app/layout.tsx | 2 +- app/performance/[id]/components/index.tsx | 2 +- lib/auth.ts | 197 ++++++++++++++++++ lib/axios/useRefreshToken.ts | 2 +- lib/fetchData.ts | 2 +- lib/get-access-data.tsx | 56 +++++ lib/server-api.ts | 2 +- pages/api/auth/[...nextauth].ts | 191 +---------------- types/next-auth.d.ts | 5 +- types/rbac.ts | 9 +- 38 files changed, 406 insertions(+), 239 deletions(-) create mode 100644 app/admin/components/SkeletonSidebar.tsx create mode 100644 lib/auth.ts create mode 100644 lib/get-access-data.tsx diff --git a/app/(dashboard)/(main)/page-backup.tsx b/app/(dashboard)/(main)/page-backup.tsx index 6c85d83..11115eb 100644 --- a/app/(dashboard)/(main)/page-backup.tsx +++ b/app/(dashboard)/(main)/page-backup.tsx @@ -15,12 +15,12 @@ import { CalendarDateRangePicker } from "../components/DaterangePicker" import { Button } from "@/components/ui/button" // import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs" import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" -import { authOptions } from "@/pages/api/auth/[...nextauth]" import { titleCase } from "@/lib/helper" import { fetchDataWithPost } from "@/lib/fetchData" // import { ToggleTheme } from "../admin/components/ToggleTheme" // import Notification from "../admin/components/Notification" import duration from 'dayjs/plugin/duration' +import { authOptions } from "@/lib/auth" dayjs.extend(duration) diff --git a/app/(dashboard)/(main)/page.tsx b/app/(dashboard)/(main)/page.tsx index 0660a71..6844a15 100644 --- a/app/(dashboard)/(main)/page.tsx +++ b/app/(dashboard)/(main)/page.tsx @@ -3,7 +3,6 @@ import Link from "next/link" import { getServerSession } from "next-auth" import dayjs from "dayjs" -import { authOptions } from "@/pages/api/auth/[...nextauth]" import { generateHourMinutes, titleCase } from "@/lib/helper" import { fetchDataWithPost } from "@/lib/fetchData" @@ -12,6 +11,7 @@ import { Button } from "@/components/ui/button" import { Card900, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" import LazyLoading from "@/components/loader/LazyLoading" +import { authOptions } from "@/lib/auth" // const LastPresence = lazy(() => import("./components/LastPresence")) const WorkingHours = lazy(() => import("../components/WorkingHours")) diff --git a/app/(dashboard)/history/attendance/index.tsx b/app/(dashboard)/history/attendance/index.tsx index 3f5dce4..ac9852b 100644 --- a/app/(dashboard)/history/attendance/index.tsx +++ b/app/(dashboard)/history/attendance/index.tsx @@ -1,10 +1,10 @@ import { Suspense, lazy } from 'react'; import { getServerSession } from 'next-auth'; import dayjs from 'dayjs'; -import { authOptions } from '@/pages/api/auth/[...nextauth]'; import { fetchDataWithPost } from '@/lib/fetchData'; import LazyLoading from '@/components/loader/LazyLoading'; import { type IHistory } from '../components/type'; +import { authOptions } from '@/lib/auth'; const DataTable = lazy(() => import('./DataTable')); diff --git a/app/(dashboard)/history/leave-permit/index.tsx b/app/(dashboard)/history/leave-permit/index.tsx index 9415072..6e3ae6c 100644 --- a/app/(dashboard)/history/leave-permit/index.tsx +++ b/app/(dashboard)/history/leave-permit/index.tsx @@ -1,10 +1,10 @@ import { Suspense, lazy } from 'react'; import { getServerSession } from 'next-auth'; import dayjs from 'dayjs'; -import { authOptions } from '@/pages/api/auth/[...nextauth]'; import { fetchDataWithPost } from '@/lib/fetchData'; import LazyLoading from '@/components/loader/LazyLoading'; import { type ILeaveSickPermit } from '../components/type'; +import { authOptions } from '@/lib/auth'; const DataTable = lazy(() => import('./DataTable')); diff --git a/app/(dashboard)/history/page.tsx b/app/(dashboard)/history/page.tsx index 549d9d6..d544950 100644 --- a/app/(dashboard)/history/page.tsx +++ b/app/(dashboard)/history/page.tsx @@ -6,7 +6,7 @@ import { Suspense, lazy } from "react"; import SkeletonTable from "@/components/skeleton/SkeletonTable"; import TabsComponent from "./components/Tabs"; import { getServerSession } from "next-auth"; -import { authOptions } from "@/pages/api/auth/[...nextauth]"; +import { authOptions } from "@/lib/auth"; const AttendanceHistory = lazy(() => import("./attendance")); const LeavePermitHistory = lazy(() => import("./leave-permit")); diff --git a/app/(dashboard)/iam-here/page.tsx b/app/(dashboard)/iam-here/page.tsx index 88bff1d..456afc9 100644 --- a/app/(dashboard)/iam-here/page.tsx +++ b/app/(dashboard)/iam-here/page.tsx @@ -5,8 +5,8 @@ import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import PageLoading from '@/components/loader/PageLoading'; import { fetchDataWithPost } from '@/lib/fetchData'; import { getServerSession } from 'next-auth'; -import { authOptions } from '@/pages/api/auth/[...nextauth]'; import { redirect } from 'next/navigation'; +import { authOptions } from '@/lib/auth'; const FormComponent = lazy(() => import('./components/FormComponent')) diff --git a/app/(dashboard)/profile/page.tsx b/app/(dashboard)/profile/page.tsx index 98041d0..c4ac0bf 100644 --- a/app/(dashboard)/profile/page.tsx +++ b/app/(dashboard)/profile/page.tsx @@ -10,7 +10,7 @@ import LazyLoading from '@/components/loader/LazyLoading'; import { type IProfile } from './components/type'; import { type IUser } from '@/app/admin/administration/user/component/type'; import { getServerSession } from 'next-auth'; -import { authOptions } from '@/pages/api/auth/[...nextauth]'; +import { authOptions } from '@/lib/auth'; const ForgotPassword = lazy(() => import('./components/ForgotPassword')); const ChangeTheme = lazy(() => import("./components/ChangeTheme")) diff --git a/app/@modal/(.)performance/[id]/page.tsx b/app/@modal/(.)performance/[id]/page.tsx index 1d7d134..1ff3215 100644 --- a/app/@modal/(.)performance/[id]/page.tsx +++ b/app/@modal/(.)performance/[id]/page.tsx @@ -3,9 +3,9 @@ import InterceptModal from '@/components/modal/InterceptModal'; import LazyLoading from '@/components/loader/LazyLoading'; import DateRangePicker from '@/app/performance/[id]/components/DateRangePicker'; import { getServerSession } from 'next-auth'; -import { authOptions } from '@/pages/api/auth/[...nextauth]'; import { Metadata } from 'next'; import dayjs from 'dayjs'; +import { authOptions } from '@/lib/auth'; const PerformanceComponent = lazy(() => import('@/app/performance/[id]/components')); diff --git a/app/actions/user.ts b/app/actions/user.ts index c9a6ad7..56b9573 100644 --- a/app/actions/user.ts +++ b/app/actions/user.ts @@ -1,8 +1,8 @@ "use server" +import { authOptions } from "@/lib/auth"; import axios from "@/lib/axios"; import { serverApiCall } from "@/lib/server-api"; -import { authOptions } from "@/pages/api/auth/[...nextauth]"; import { getServerSession } from "next-auth"; import { revalidatePath } from "next/cache"; diff --git a/app/admin/administration/area/page.tsx b/app/admin/administration/area/page.tsx index 9b0c9e1..b36c24a 100644 --- a/app/admin/administration/area/page.tsx +++ b/app/admin/administration/area/page.tsx @@ -2,11 +2,11 @@ import { type Metadata } from 'next'; import { FC, Suspense, lazy } from 'react'; import { getServerSession } from 'next-auth'; import { Download } from 'lucide-react' -import { authOptions } from '@/pages/api/auth/[...nextauth]'; import { Button } from '@/components/ui/button'; import { type ResponseData } from '@/types/types'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import LazyLoading from '@/components/loader/LazyLoading'; +import { authOptions } from '@/lib/auth'; const ComponentPage = lazy(() => import('./component')); diff --git a/app/admin/administration/company/page.tsx b/app/admin/administration/company/page.tsx index b0f7249..b00492b 100644 --- a/app/admin/administration/company/page.tsx +++ b/app/admin/administration/company/page.tsx @@ -2,11 +2,11 @@ import { type Metadata } from 'next'; import { Suspense, lazy } from 'react'; import { getServerSession } from 'next-auth'; import { Download } from 'lucide-react' -import { authOptions } from '@/pages/api/auth/[...nextauth]'; import { Button } from '@/components/ui/button'; import { type ResponseData } from '@/types/types'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import LazyLoading from '@/components/loader/LazyLoading'; +import { authOptions } from '@/lib/auth'; const ComponentPage = lazy(() => import('./component')); diff --git a/app/admin/administration/division/page.tsx b/app/admin/administration/division/page.tsx index bf5966b..ba60578 100644 --- a/app/admin/administration/division/page.tsx +++ b/app/admin/administration/division/page.tsx @@ -2,11 +2,11 @@ import { type Metadata } from 'next'; import { Suspense, lazy } from 'react'; import { getServerSession } from 'next-auth'; import { Download } from 'lucide-react' -import { authOptions } from '@/pages/api/auth/[...nextauth]'; import { Button } from '@/components/ui/button'; import { type ResponseData } from '@/types/types'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import LazyLoading from '@/components/loader/LazyLoading'; +import { authOptions } from '@/lib/auth'; const ComponentPage = lazy(() => import('./component')); diff --git a/app/admin/administration/user/page.tsx b/app/admin/administration/user/page.tsx index 3863226..27557c6 100644 --- a/app/admin/administration/user/page.tsx +++ b/app/admin/administration/user/page.tsx @@ -1,11 +1,11 @@ import { type Metadata } from 'next'; import { Suspense, lazy } from 'react'; import { getServerSession } from 'next-auth'; -import { authOptions } from '@/pages/api/auth/[...nextauth]'; import { type ResponseData } from '@/types/types'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import LazyLoading from '@/components/loader/LazyLoading'; import ExportComponent from './component/Export'; +import { authOptions } from '@/lib/auth'; const ComponentPage = lazy(() => import('./component')); diff --git a/app/admin/audit-trail/page.tsx b/app/admin/audit-trail/page.tsx index 5826973..0aeaa9e 100644 --- a/app/admin/audit-trail/page.tsx +++ b/app/admin/audit-trail/page.tsx @@ -2,11 +2,11 @@ import { type Metadata } from 'next'; import { Suspense, lazy } from 'react'; import { getServerSession } from 'next-auth'; import { Download } from 'lucide-react' -import { authOptions } from '@/pages/api/auth/[...nextauth]'; import { Button } from '@/components/ui/button'; import { type ResponseData } from '@/types/types'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import LazyLoading from '@/components/loader/LazyLoading'; +import { authOptions } from '@/lib/auth'; const ComponentPage = lazy(() => import('./component')); diff --git a/app/admin/components/Breadcrumb.tsx b/app/admin/components/Breadcrumb.tsx index 3abdc7d..f05f43a 100644 --- a/app/admin/components/Breadcrumb.tsx +++ b/app/admin/components/Breadcrumb.tsx @@ -47,7 +47,7 @@ export default function AdminBreadcrumb() { } return ( -
+
Pages @@ -63,9 +63,9 @@ export default function AdminBreadcrumb() { {formatSegment(seg)} ) : ( - + {formatSegment(seg)} - + )} ); diff --git a/app/admin/components/Sidebar.tsx b/app/admin/components/Sidebar.tsx index b04e8cc..7fd886b 100644 --- a/app/admin/components/Sidebar.tsx +++ b/app/admin/components/Sidebar.tsx @@ -19,9 +19,11 @@ const SidebarItem = dynamic(() => import("./SidebarItem"), { ssr: false }) -type Props = {}; +type Props = { + menuList: ISideMenu[] +}; -const Sidebar: FC = ({ }) => { +const Sidebar: FC = ({ menuList }) => { const [expand, setExpand] = useState(true) const [sidebarOpen, setSidebarOpen] = useState(false) const [search, setSearch] = useState('') @@ -30,7 +32,8 @@ const Sidebar: FC = ({ }) => { const sidebar = useRef(null); const router = useRouter() - const menu: ISideMenu[] = SIDEBAR_MENU + // const menu: ISideMenu[] = SIDEBAR_MENU + const menu: ISideMenu[] = menuList // close on click outside useEffect(() => { diff --git a/app/admin/components/SkeletonSidebar.tsx b/app/admin/components/SkeletonSidebar.tsx new file mode 100644 index 0000000..cb7fbc2 --- /dev/null +++ b/app/admin/components/SkeletonSidebar.tsx @@ -0,0 +1,25 @@ +import { Skeleton } from '@/components/ui/skeleton'; +import { FC } from 'react'; + +type Props = {}; + +const SkeletonSidebar: FC = () => { + return ( + <> +
+
+ +
+
+ + + + + +
+
+ + ); +} + +export default SkeletonSidebar; \ No newline at end of file diff --git a/app/admin/device/device-type/page.tsx b/app/admin/device/device-type/page.tsx index 3829bf4..451d704 100644 --- a/app/admin/device/device-type/page.tsx +++ b/app/admin/device/device-type/page.tsx @@ -2,11 +2,11 @@ import { type Metadata } from 'next'; import { Suspense, lazy } from 'react'; import { getServerSession } from 'next-auth'; import { Download } from 'lucide-react' -import { authOptions } from '@/pages/api/auth/[...nextauth]'; import { Button } from '@/components/ui/button'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import LazyLoading from '@/components/loader/LazyLoading'; import { type ResponseData } from '@/types/types'; +import { authOptions } from '@/lib/auth'; const ComponentPage = lazy(() => import('./component')); diff --git a/app/admin/device/device/page.tsx b/app/admin/device/device/page.tsx index d41b8e9..28be8b9 100644 --- a/app/admin/device/device/page.tsx +++ b/app/admin/device/device/page.tsx @@ -2,11 +2,11 @@ import { type Metadata } from 'next'; import { Suspense, lazy } from 'react'; import { getServerSession } from 'next-auth'; import { Download } from 'lucide-react' -import { authOptions } from '@/pages/api/auth/[...nextauth]'; import { Button } from '@/components/ui/button'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import LazyLoading from '@/components/loader/LazyLoading'; import { type ResponseData } from '@/types/types'; +import { authOptions } from '@/lib/auth'; const ComponentPage = lazy(() => import('./component')); diff --git a/app/admin/global-parameter/page.tsx b/app/admin/global-parameter/page.tsx index 466a626..9286549 100644 --- a/app/admin/global-parameter/page.tsx +++ b/app/admin/global-parameter/page.tsx @@ -2,11 +2,11 @@ import { type Metadata } from 'next'; import { Suspense, lazy } from 'react'; import { getServerSession } from 'next-auth'; import { Download } from 'lucide-react' -import { authOptions } from '@/pages/api/auth/[...nextauth]'; import { Button } from '@/components/ui/button'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { type ResponseData } from '@/types/types'; import LazyLoading from '@/components/loader/LazyLoading'; +import { authOptions } from '@/lib/auth'; const ComponentPage = lazy(() => import('./component')); diff --git a/app/admin/information/employee-type/page.tsx b/app/admin/information/employee-type/page.tsx index 270bdac..56e4cad 100644 --- a/app/admin/information/employee-type/page.tsx +++ b/app/admin/information/employee-type/page.tsx @@ -1,10 +1,10 @@ import { type Metadata } from 'next'; import { Suspense, lazy } from 'react'; import { getServerSession } from 'next-auth'; -import { authOptions } from '@/pages/api/auth/[...nextauth]'; import { type ResponseData } from '@/types/types'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import LazyLoading from '@/components/loader/LazyLoading'; +import { authOptions } from '@/lib/auth'; const ComponentPage = lazy(() => import('./component')); diff --git a/app/admin/information/master-status/page.tsx b/app/admin/information/master-status/page.tsx index 727a688..57e5670 100644 --- a/app/admin/information/master-status/page.tsx +++ b/app/admin/information/master-status/page.tsx @@ -1,10 +1,10 @@ import { type Metadata } from 'next'; import { Suspense, lazy } from 'react'; import { getServerSession } from 'next-auth'; -import { authOptions } from '@/pages/api/auth/[...nextauth]'; import { type ResponseData } from '@/types/types'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import LazyLoading from '@/components/loader/LazyLoading'; +import { authOptions } from '@/lib/auth'; const ComponentPage = lazy(() => import('./component')); diff --git a/app/admin/information/position/page.tsx b/app/admin/information/position/page.tsx index ba913f0..2797cab 100644 --- a/app/admin/information/position/page.tsx +++ b/app/admin/information/position/page.tsx @@ -1,10 +1,10 @@ import { type Metadata } from 'next'; import { Suspense, lazy } from 'react'; import { getServerSession } from 'next-auth'; -import { authOptions } from '@/pages/api/auth/[...nextauth]'; import { type ResponseData } from '@/types/types'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import LazyLoading from '@/components/loader/LazyLoading'; +import { authOptions } from '@/lib/auth'; const ComponentPage = lazy(() => import('./component')); diff --git a/app/admin/information/working-status/page.tsx b/app/admin/information/working-status/page.tsx index 771063a..60f77ed 100644 --- a/app/admin/information/working-status/page.tsx +++ b/app/admin/information/working-status/page.tsx @@ -1,10 +1,10 @@ import { type Metadata } from 'next'; import { Suspense, lazy } from 'react'; import { getServerSession } from 'next-auth'; -import { authOptions } from '@/pages/api/auth/[...nextauth]'; import { type ResponseData } from '@/types/types'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import LazyLoading from '@/components/loader/LazyLoading'; +import { authOptions } from '@/lib/auth'; const ComponentPage = lazy(() => import('./component')); diff --git a/app/admin/layout.tsx b/app/admin/layout.tsx index 8f87dce..6d22ba6 100644 --- a/app/admin/layout.tsx +++ b/app/admin/layout.tsx @@ -2,27 +2,94 @@ import { Metadata } from "next"; import Link from "next/link"; import { ToggleTheme } from "./components/ToggleTheme"; import { Button } from "@/components/ui/button"; -import Sidebar from "./components/Sidebar"; import Notification from "./components/Notification"; import { UserNav } from "../(dashboard)/components/UserNav"; import { House } from "lucide-react"; import AdminBreadcrumb from "./components/Breadcrumb"; +import { getAccessData } from "@/lib/get-access-data"; +import { IRoleDetail } from "@/types/rbac"; +import { ISideMenu } from "./components/SidebarItem"; +import { lazy, Suspense } from "react"; +import SkeletonSidebar from "./components/SkeletonSidebar"; + +const Sidebar = lazy(() => import("./components/Sidebar")); export const metadata: Metadata = { title: "Admin Panel", description: "H.A.T.s admin panel page", } -export default async function AdminLayout({ - children, // will be a page or nested layout -}: { - children: React.ReactNode -}) { +export default async function AdminLayout({ children }: { children: React.ReactNode }) { + const data = await getAccessData() + + const cleanPath = (path: string): string => { + if (!path || path === '/') return '' + const sanitized = path.replace(/\/+/g, '/') + return sanitized.startsWith('/') ? sanitized : `/${sanitized}` + } + + const buildSidebarMenu = (items: IRoleDetail[]): ISideMenu[] => { + // 1. Filter out deleted, inactive, or hidden items + const adminMenus = items.filter(item => item.menu?.is_admin_menu === true) + const activeItems = adminMenus.filter((item) => item.menu && !item.menu.deleted_at && item.menu.status_id === 1) + + const parents: IRoleDetail[] = [] + const childrenMap = new Map() + + // 2. Group into parent items and children + for (const item of activeItems) { + const parentId = item.menu?.menu_parent_id + if (parentId === null) { + parents.push(item) + } else { + const children = childrenMap.get(parentId!) || [] + children.push(item) + childrenMap.set(parentId!, children) + } + } + + // 3. Sorting helper (sort ascending, null values last, fallback to id) + const sortByOrder = (a: IRoleDetail, b: IRoleDetail) => { + const sortA = a.menu?.sort ?? Number.MAX_SAFE_INTEGER + const sortB = b.menu?.sort ?? Number.MAX_SAFE_INTEGER + if (sortA !== sortB) return sortA - sortB + return a.menu?.id! - b.menu?.id! + } + + parents.sort(sortByOrder) + + // 4. Map to target structure + // @ts-ignore + return parents.map((parent) => { + const children = childrenMap.get(parent.menu?.id!) || [] + + if (children.length > 0) { + children.sort(sortByOrder) + return { + title: parent.menu?.name!, + Icon: , + submenuId: parent.menu?.id, + submenuItems: children.map((child) => ({ + title: child.menu?.name, + path: cleanPath(child.menu?.path_url!), + })), + } + } + + return { + title: parent.menu?.name!, + Icon: , + path: cleanPath(parent.menu?.path_url!), + } + }) + } return ( <>
- + }> + + {/* CONTENT */}
diff --git a/app/admin/rbac/user-role/[id]/page.tsx b/app/admin/rbac/user-role/[id]/page.tsx index f55d994..1a6c6c3 100644 --- a/app/admin/rbac/user-role/[id]/page.tsx +++ b/app/admin/rbac/user-role/[id]/page.tsx @@ -6,7 +6,7 @@ import fetchData from '@/lib/fetchData'; import { Button } from '@/components/ui/button'; import { type IRole } from '../component/type'; import RolePermissionRow from "../component/role-permission-row"; -import { PencilLine } from 'lucide-react'; +import { PencilLine, ShieldCheck } from 'lucide-react'; export const dynamic = 'force-dynamic'; @@ -179,7 +179,7 @@ const UserRoleDetailPage: FC = async ({ params }) => {
- + Authorized Menu Permissions ({orderedDetails.length} Menus Allowed) diff --git a/app/admin/rbac/user-role/component/RoleForm.tsx b/app/admin/rbac/user-role/component/RoleForm.tsx index c6a20a5..d2609a8 100644 --- a/app/admin/rbac/user-role/component/RoleForm.tsx +++ b/app/admin/rbac/user-role/component/RoleForm.tsx @@ -81,9 +81,7 @@ export const RoleForm: FC = ({ isUpdate, roleId, initialData }) => { const rawDetails = Array.isArray(initialData.role_detail) ? initialData.role_detail - : Array.isArray(initialData.privilege) - ? initialData.privilege - : []; + : []; rawDetails.forEach((item: any) => { // Support both new API format (item.menu.id) and legacy format (item.menu_id) @@ -421,7 +419,7 @@ export const RoleForm: FC = ({ isUpdate, roleId, initialData }) => { {/* Bottom Action Bar */}
- diff --git a/app/admin/rbac/user-role/component/index.tsx b/app/admin/rbac/user-role/component/index.tsx index 8a61f2f..948983b 100644 --- a/app/admin/rbac/user-role/component/index.tsx +++ b/app/admin/rbac/user-role/component/index.tsx @@ -118,9 +118,7 @@ const ComponentRolePage: FC = ({ data }) => { render: (details: any, record: IRole) => { const count = Array.isArray(details) ? details.length - : Array.isArray(record.privilege) - ? record.privilege.length - : 0; + : 0; return ( {count} menus diff --git a/app/layout.tsx b/app/layout.tsx index e47a10a..445c1b4 100644 --- a/app/layout.tsx +++ b/app/layout.tsx @@ -5,7 +5,6 @@ import type { Metadata, Viewport } from 'next' import { Plus_Jakarta_Sans } from 'next/font/google' import { getServerSession } from 'next-auth' -import { authOptions } from '@/pages/api/auth/[...nextauth]' import { ThemeProvider } from '@/providers/ThemeProvider' import SessionProvider from '@/providers/SessionProvider' @@ -14,6 +13,7 @@ import AntdConfigProvider from '@/providers/AntdConfigProvider'; import ProgressBarProviders from '@/providers/ProgressBarProvider'; import { TooltipProvider } from '@/components/ui/tooltip'; import ServiceWorkerRegister from '@/components/pwa/ServiceWorkerRegister'; +import { authOptions } from '@/lib/auth'; const jakarta = Plus_Jakarta_Sans({ subsets: ['latin'] }) diff --git a/app/performance/[id]/components/index.tsx b/app/performance/[id]/components/index.tsx index 9c0831b..97710eb 100644 --- a/app/performance/[id]/components/index.tsx +++ b/app/performance/[id]/components/index.tsx @@ -2,12 +2,12 @@ import { FC, Suspense, lazy } from 'react'; import { redirect } from 'next/navigation'; import { getServerSession } from 'next-auth'; import dayjs from 'dayjs'; -import { authOptions } from '@/pages/api/auth/[...nextauth]'; import { Card, Card900, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import LazyLoading from '@/components/loader/LazyLoading'; import fetchData, { fetchDataWithPost } from '@/lib/fetchData'; import { generateHourMinutes } from '@/lib/helper'; import ViewAvatar from '@/components/ViewAvatar'; +import { authOptions } from '@/lib/auth'; const DonutChart = lazy(() => import('./DonutChart')); const AreaChart = lazy(() => import('./AreaChart')) diff --git a/lib/auth.ts b/lib/auth.ts new file mode 100644 index 0000000..f2c2504 --- /dev/null +++ b/lib/auth.ts @@ -0,0 +1,197 @@ +import { type NextAuthOptions } from "next-auth" +import CredentialsProvider from "next-auth/providers/credentials"; + +const { BASE_URL_API, DEVICE_CODE } = process.env + +/** + * CUSTOM NEXTAUTH EXP + * THIS VALUE SHOULD BE LESS THAN ACCESS TOKEN EXP (EX: 1 days) + * */ +export const EXP_SESSION = 12 * 60 * 60 // 12 hours +// const EXP_SESSION = 24 * 60 * 60 // 1 days +// const EXP_SESSION = 10 // 10 seconds + +// Determine if we are using HTTPS +async function refreshAccessToken(token: any) { + // If the access token has expired, try to refresh it + try { + // FOR INSECURE SSL (ex: Self Signed Certificates) + // process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0' + + // 1. Race Condition Check: + // If we refreshed recently (within 10s), return the current token + // to prevent parallel requests from spamming the API. + if (token.last_refreshed && Date.now() - token.last_refreshed < 10000) { + return token; + } + console.log(`[REFRESH] Attempting refresh for token ending in... ${token.access_token?.slice(-5)}`) + + const response = await fetch(BASE_URL_API + "/auth/refresh-token", { + method: "POST", + headers: { + "Content-Type": "application/json", + "Refresh-Token": token?.refresh_token, + "Device-Code": DEVICE_CODE || "40001", + }, + body: JSON.stringify({ + email: token?.detail.email + }), + }) + + const data = await response.json() + console.log(data) + + if (!response.ok) throw token + + console.log("[REFRESH] Success. New Access Token received.") + return { + ...token, // Keep the previous token properties + access_token: data.data.access_token, + refresh_token: data.data.refresh_token, + expired_at: Math.floor(Date.now() + EXP_SESSION * 1000), + last_refreshed: Date.now(), // Mark this refresh + error: null, // Clear errors + } + } catch (error) { + console.log("[REFRESH] Error refreshing access token", error) + + return { + ...token, + error: "RefreshAccessTokenError", + }; + } +} + +export const authOptions: NextAuthOptions = { + // FORCE COOKIE SETTINGS (To fix localhost rejection) + providers: [ + CredentialsProvider({ + name: "Credentials", + credentials: { + email: {}, + password: {} + }, + async authorize(credentials, req) { + // FOR INSECURE SSL (ex: Self Signed Certificates) + // process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0' + + const { email, password } = credentials as any; + + const res = await fetch(`${BASE_URL_API}/auth/login`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ email, password, }), + }); + + const data: any = await res.json(); + + if (res.ok) { + if (data) { + const rawDetail = data.data.detail; + + const keepNonAdminMenu = rawDetail?.role?.role_detail?.filter((item: any) => item?.menu?.is_admin_menu === false).map((item: any) => ({ + action: item.action, + menu: { + name: item.menu.name, + icon: item.menu.icon, + path_url: item.menu.path_url, + } + })) + + const cleanDetail = { + id: rawDetail.id, + email: rawDetail.email, + nik: rawDetail.nik, + fullname: rawDetail.fullname, + nickname: rawDetail.nickname, + avatar: rawDetail.avatar, + phone_number: rawDetail.phone_number, + role: { + id: rawDetail.role?.id, + code: rawDetail.role?.code, + name: rawDetail.role?.name, + allow_admin_panel: rawDetail.role?.allow_admin_panel, + role_detail: keepNonAdminMenu + } + }; + + // console.log(cleanDetail.role) + + return { + access_token: data.data.access_token, + refresh_token: data.data.refresh_token, + detail: cleanDetail, // <--- Using the Pruned Object + expired_at: Math.floor(Date.now() + (EXP_SESSION * 1000)), + last_refreshed: Date.now() + } as any; + } else { + throw new Error(`Invalid email or password`) + } + } else { + throw new Error(data.message) + } + } + }) + ], + session: { + strategy: "jwt", + + /* SET MAX_AGE IF NOT USING REFRESH TOKEN */ + // maxAge: 30 * 24 * 60 * 60, // 30 days + // maxAge: 24 * 60 * 60, // 1 days + // maxAge: 10, // 10 seconds + // updateAge: 10, // 1 days + }, + pages: { + signIn: "/auth", + // newUser: "/complete-account" // where to redirect if user is new + // signOut: "/login" + }, + callbacks: { + async jwt({ token, user, account, profile, trigger, session }: any) { + + // 1. Handle Update Trigger (Client side update) + if (trigger === "update" && session?.access_token) { + // Note, that `session` can be any arbitrary object, remember to validate it! + console.log("====================================== MASUK KE JWT ========================================") + console.log("============================ SESSION UPDATED FROM THE CLIENT ===================================") + + // const newSession = { + // ...session, // Keep the previous token properties + // expired_at: Math.floor(Date.now() + EXP_SESSION * 1000) // UPDATE NEXTAUTH SESSION EXP + // } + // console.log({ session: newSession }) + // return newSession + return session + } + + // 2. Initial Sign In + if (user) { + return { ...token, ...user } + } + + // 3. Safety Check: If we somehow lost the access token, return what we have (or error) + if (!token?.access_token) { + console.log("JWT callback: token already null, skipping refresh."); + return token; + } + + // 4. Check Validity + // If expired_at is missing, we assume we need to refresh (safety) + // Refresh 15 seconds *before* it actually dies to prevent timing issues + const isValid = token.expired_at && (Date.now() < (token.expired_at - 15000)); + + if (isValid) return token; + + // 5. Token Expired (or missing expiry), Refresh it + console.log(`[JWT] Token Expired (or invalid timestamp). Refreshing... Current: ${Date.now()}, ExpiredAt: ${token.expired_at}`) + return await refreshAccessToken(token) + }, + async session({ session, token, user }) { + // Send properties to the client, like an access_token from a provider. + session.user = token as any; + + return session; + }, + }, +} \ No newline at end of file diff --git a/lib/axios/useRefreshToken.ts b/lib/axios/useRefreshToken.ts index 3cf902e..02d3340 100644 --- a/lib/axios/useRefreshToken.ts +++ b/lib/axios/useRefreshToken.ts @@ -2,7 +2,7 @@ import { signOut, useSession } from "next-auth/react"; import axios from "../axios"; -import { EXP_SESSION } from "@/pages/api/auth/[...nextauth]"; +import { EXP_SESSION } from "../auth"; export const useRefreshToken = () => { const { data: session, update } = useSession(); diff --git a/lib/fetchData.ts b/lib/fetchData.ts index 181274a..3e4d963 100644 --- a/lib/fetchData.ts +++ b/lib/fetchData.ts @@ -1,8 +1,8 @@ import { getServerSession } from "next-auth" -import { authOptions } from "@/pages/api/auth/[...nextauth]" import { redirect } from "next/navigation" import { ResponseData } from "@/types/types" import { logger } from "./logger" +import { authOptions } from "./auth" export default async function fetchData(url: string = '/', cache: "default" | "force-cache" | "no-cache" | "no-store" | "only-if-cached" | "reload" = 'default', next?: NextFetchRequestConfig) { const { BASE_URL_API } = process.env diff --git a/lib/get-access-data.tsx b/lib/get-access-data.tsx new file mode 100644 index 0000000..7bc8f8d --- /dev/null +++ b/lib/get-access-data.tsx @@ -0,0 +1,56 @@ +// "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; +} \ No newline at end of file diff --git a/lib/server-api.ts b/lib/server-api.ts index 36b975c..bbf9a66 100644 --- a/lib/server-api.ts +++ b/lib/server-api.ts @@ -1,9 +1,9 @@ "use server" import { getServerSession } from "next-auth"; -import { authOptions } from "@/pages/api/auth/[...nextauth]"; // Adjust path as needed import axios from "@/lib/axios"; // Your axios instance import { writeLog } from "./logger"; +import { authOptions } from "./auth"; // 1. Define a standard response format for all your actions export type ActionResponse = diff --git a/pages/api/auth/[...nextauth].ts b/pages/api/auth/[...nextauth].ts index b9c5c4f..88a756c 100644 --- a/pages/api/auth/[...nextauth].ts +++ b/pages/api/auth/[...nextauth].ts @@ -1,192 +1,5 @@ -import NextAuth, { type NextAuthOptions } from "next-auth" -import CredentialsProvider from "next-auth/providers/credentials"; +import { authOptions } from "@/lib/auth" +import NextAuth from "next-auth" -const { BASE_URL_API, DEVICE_CODE } = process.env -/** - * CUSTOM NEXTAUTH EXP - * THIS VALUE SHOULD BE LESS THAN ACCESS TOKEN EXP (EX: 1 days) - * */ -export const EXP_SESSION = 12 * 60 * 60 // 12 hours -// const EXP_SESSION = 24 * 60 * 60 // 1 days -// const EXP_SESSION = 10 // 10 seconds - -// Determine if we are using HTTPS -const useSecureCookies = process.env.NEXTAUTH_URL?.startsWith('https://'); - -async function refreshAccessToken(token: any) { - // If the access token has expired, try to refresh it - try { - // FOR INSECURE SSL (ex: Self Signed Certificates) - // process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0' - - // 1. Race Condition Check: - // If we refreshed recently (within 10s), return the current token - // to prevent parallel requests from spamming the API. - if (token.last_refreshed && Date.now() - token.last_refreshed < 10000) { - return token; - } - console.log(`[REFRESH] Attempting refresh for token ending in... ${token.access_token?.slice(-5)}`) - - const response = await fetch(BASE_URL_API + "/auth/refresh-token", { - method: "POST", - headers: { - "Content-Type": "application/json", - "Refresh-Token": token?.refresh_token, - "Device-Code": DEVICE_CODE || "40001", - }, - body: JSON.stringify({ - email: token?.detail.email - }), - }) - - const data = await response.json() - console.log(data) - - if (!response.ok) throw token - - console.log("[REFRESH] Success. New Access Token received.") - return { - ...token, // Keep the previous token properties - access_token: data.data.access_token, - refresh_token: data.data.refresh_token, - expired_at: Math.floor(Date.now() + EXP_SESSION * 1000), - last_refreshed: Date.now(), // Mark this refresh - error: null, // Clear errors - } - } catch (error) { - console.log("[REFRESH] Error refreshing access token", error) - - return { - ...token, - error: "RefreshAccessTokenError", - }; - } -} - -export const authOptions: NextAuthOptions = { - // FORCE COOKIE SETTINGS (To fix localhost rejection) - providers: [ - CredentialsProvider({ - name: "Credentials", - credentials: { - email: {}, - password: {} - }, - async authorize(credentials, req) { - // FOR INSECURE SSL (ex: Self Signed Certificates) - // process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0' - - const { email, password } = credentials as any; - - const res = await fetch(`${BASE_URL_API}/auth/login`, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ email, password, }), - }); - - const data: any = await res.json(); - console.log("LOGIN :", data) - - if (res.ok) { - if (data) { - // data.data.expired_at = Math.floor(Date.now() + (EXP_SESSION * 1000)) // SET NEXTAUTH SESSION EXP - // data.data.last_refreshed = Date.now() // SET LAST REFRESHED - // return data.data; - - const rawDetail = data.data.detail; - - const cleanDetail = { - id: rawDetail.id, - email: rawDetail.email, - nik: rawDetail.nik, - fullname: rawDetail.fullname, - nickname: rawDetail.nickname, - avatar: rawDetail.avatar, - phone_number: rawDetail.phone_number, - role: { - code: rawDetail.role?.code, - name: rawDetail.role?.name, - allow_admin_panel: rawDetail.role?.allow_admin_panel - } - }; - - return { - access_token: data.data.access_token, - refresh_token: data.data.refresh_token, - detail: cleanDetail, // <--- Using the Pruned Object - expired_at: Math.floor(Date.now() + (EXP_SESSION * 1000)), - last_refreshed: Date.now() - } as any; - } else { - throw new Error(`Invalid email or password`) - } - } else { - throw new Error(data.message) - } - } - }) - ], - session: { - strategy: "jwt", - - /* SET MAX_AGE IF NOT USING REFRESH TOKEN */ - // maxAge: 30 * 24 * 60 * 60, // 30 days - // maxAge: 24 * 60 * 60, // 1 days - // maxAge: 10, // 10 seconds - // updateAge: 10, // 1 days - }, - pages: { - signIn: "/auth", - // newUser: "/complete-account" // where to redirect if user is new - // signOut: "/login" - }, - callbacks: { - async jwt({ token, user, account, profile, trigger, session }: any) { - - // 1. Handle Update Trigger (Client side update) - if (trigger === "update" && session?.access_token) { - // Note, that `session` can be any arbitrary object, remember to validate it! - console.log("====================================== MASUK KE JWT ========================================") - console.log("============================ SESSION UPDATED FROM THE CLIENT ===================================") - - // const newSession = { - // ...session, // Keep the previous token properties - // expired_at: Math.floor(Date.now() + EXP_SESSION * 1000) // UPDATE NEXTAUTH SESSION EXP - // } - // console.log({ session: newSession }) - // return newSession - return session - } - - // 2. Initial Sign In - if (user) { - return { ...token, ...user } - } - - // 3. Safety Check: If we somehow lost the access token, return what we have (or error) - if (!token?.access_token) { - console.log("JWT callback: token already null, skipping refresh."); - return token; - } - - // 4. Check Validity - // If expired_at is missing, we assume we need to refresh (safety) - // Refresh 15 seconds *before* it actually dies to prevent timing issues - const isValid = token.expired_at && (Date.now() < (token.expired_at - 15000)); - - if (isValid) return token; - - // 5. Token Expired (or missing expiry), Refresh it - console.log(`[JWT] Token Expired (or invalid timestamp). Refreshing... Current: ${Date.now()}, ExpiredAt: ${token.expired_at}`) - return await refreshAccessToken(token) - }, - async session({ session, token, user }) { - // Send properties to the client, like an access_token from a provider. - session.user = token as any; - - return session; - }, - }, -} export default NextAuth(authOptions) \ No newline at end of file diff --git a/types/next-auth.d.ts b/types/next-auth.d.ts index 0f94c8d..97fe491 100644 --- a/types/next-auth.d.ts +++ b/types/next-auth.d.ts @@ -19,18 +19,21 @@ declare module 'next-auth' { company?: ICompany division?: IDivision role: { + id: number code: string name: string allow_admin_panel: boolean role_detail?: { + action: string[] menu: { + id: number code: string name: string menu_parent_id: number icon: string path_url: string sort: number - hidden_data: boolean + is_admin_menu: boolean } }[] } diff --git a/types/rbac.ts b/types/rbac.ts index 08d332e..0015049 100644 --- a/types/rbac.ts +++ b/types/rbac.ts @@ -21,13 +21,21 @@ export interface IMenu { is_admin_menu: boolean; menu_parent_id?: number | null; action?: string[]; + status_id?: number status?: { id?: number; code?: string; name?: string; }; + sort: number children?: IMenu[]; menu_level?: number; + "created_at"?: string + "created_by"?: number + "updated_at"?: string + "updated_by"?: 1 + "deleted_at"?: string + "deleted_by"?: number } export interface IRoleDetail { @@ -48,7 +56,6 @@ export interface IRole { description?: string; allow_admin_panel?: boolean; role_detail?: IRoleDetail[]; - privilege?: any[]; status?: { id?: number; code?: string;