mirror of
https://github.com/ichsankurnia/hats-app.git
synced 2026-12-05 10:46:29 +00:00
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.
This commit is contained in:
@@ -15,12 +15,12 @@ import { CalendarDateRangePicker } from "../components/DaterangePicker"
|
|||||||
import { Button } from "@/components/ui/button"
|
import { Button } from "@/components/ui/button"
|
||||||
// import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
// import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||||
import { authOptions } from "@/pages/api/auth/[...nextauth]"
|
|
||||||
import { titleCase } from "@/lib/helper"
|
import { titleCase } from "@/lib/helper"
|
||||||
import { fetchDataWithPost } from "@/lib/fetchData"
|
import { fetchDataWithPost } from "@/lib/fetchData"
|
||||||
// import { ToggleTheme } from "../admin/components/ToggleTheme"
|
// import { ToggleTheme } from "../admin/components/ToggleTheme"
|
||||||
// import Notification from "../admin/components/Notification"
|
// import Notification from "../admin/components/Notification"
|
||||||
import duration from 'dayjs/plugin/duration'
|
import duration from 'dayjs/plugin/duration'
|
||||||
|
import { authOptions } from "@/lib/auth"
|
||||||
dayjs.extend(duration)
|
dayjs.extend(duration)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ import Link from "next/link"
|
|||||||
import { getServerSession } from "next-auth"
|
import { getServerSession } from "next-auth"
|
||||||
import dayjs from "dayjs"
|
import dayjs from "dayjs"
|
||||||
|
|
||||||
import { authOptions } from "@/pages/api/auth/[...nextauth]"
|
|
||||||
import { generateHourMinutes, titleCase } from "@/lib/helper"
|
import { generateHourMinutes, titleCase } from "@/lib/helper"
|
||||||
import { fetchDataWithPost } from "@/lib/fetchData"
|
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 { Card900, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||||
|
|
||||||
import LazyLoading from "@/components/loader/LazyLoading"
|
import LazyLoading from "@/components/loader/LazyLoading"
|
||||||
|
import { authOptions } from "@/lib/auth"
|
||||||
|
|
||||||
// const LastPresence = lazy(() => import("./components/LastPresence"))
|
// const LastPresence = lazy(() => import("./components/LastPresence"))
|
||||||
const WorkingHours = lazy(() => import("../components/WorkingHours"))
|
const WorkingHours = lazy(() => import("../components/WorkingHours"))
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import { Suspense, lazy } from 'react';
|
import { Suspense, lazy } from 'react';
|
||||||
import { getServerSession } from 'next-auth';
|
import { getServerSession } from 'next-auth';
|
||||||
import dayjs from 'dayjs';
|
import dayjs from 'dayjs';
|
||||||
import { authOptions } from '@/pages/api/auth/[...nextauth]';
|
|
||||||
import { fetchDataWithPost } from '@/lib/fetchData';
|
import { fetchDataWithPost } from '@/lib/fetchData';
|
||||||
import LazyLoading from '@/components/loader/LazyLoading';
|
import LazyLoading from '@/components/loader/LazyLoading';
|
||||||
import { type IHistory } from '../components/type';
|
import { type IHistory } from '../components/type';
|
||||||
|
import { authOptions } from '@/lib/auth';
|
||||||
|
|
||||||
const DataTable = lazy(() => import('./DataTable'));
|
const DataTable = lazy(() => import('./DataTable'));
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import { Suspense, lazy } from 'react';
|
import { Suspense, lazy } from 'react';
|
||||||
import { getServerSession } from 'next-auth';
|
import { getServerSession } from 'next-auth';
|
||||||
import dayjs from 'dayjs';
|
import dayjs from 'dayjs';
|
||||||
import { authOptions } from '@/pages/api/auth/[...nextauth]';
|
|
||||||
import { fetchDataWithPost } from '@/lib/fetchData';
|
import { fetchDataWithPost } from '@/lib/fetchData';
|
||||||
import LazyLoading from '@/components/loader/LazyLoading';
|
import LazyLoading from '@/components/loader/LazyLoading';
|
||||||
import { type ILeaveSickPermit } from '../components/type';
|
import { type ILeaveSickPermit } from '../components/type';
|
||||||
|
import { authOptions } from '@/lib/auth';
|
||||||
|
|
||||||
const DataTable = lazy(() => import('./DataTable'));
|
const DataTable = lazy(() => import('./DataTable'));
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import { Suspense, lazy } from "react";
|
|||||||
import SkeletonTable from "@/components/skeleton/SkeletonTable";
|
import SkeletonTable from "@/components/skeleton/SkeletonTable";
|
||||||
import TabsComponent from "./components/Tabs";
|
import TabsComponent from "./components/Tabs";
|
||||||
import { getServerSession } from "next-auth";
|
import { getServerSession } from "next-auth";
|
||||||
import { authOptions } from "@/pages/api/auth/[...nextauth]";
|
import { authOptions } from "@/lib/auth";
|
||||||
|
|
||||||
const AttendanceHistory = lazy(() => import("./attendance"));
|
const AttendanceHistory = lazy(() => import("./attendance"));
|
||||||
const LeavePermitHistory = lazy(() => import("./leave-permit"));
|
const LeavePermitHistory = lazy(() => import("./leave-permit"));
|
||||||
|
|||||||
@@ -5,8 +5,8 @@ import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
|||||||
import PageLoading from '@/components/loader/PageLoading';
|
import PageLoading from '@/components/loader/PageLoading';
|
||||||
import { fetchDataWithPost } from '@/lib/fetchData';
|
import { fetchDataWithPost } from '@/lib/fetchData';
|
||||||
import { getServerSession } from 'next-auth';
|
import { getServerSession } from 'next-auth';
|
||||||
import { authOptions } from '@/pages/api/auth/[...nextauth]';
|
|
||||||
import { redirect } from 'next/navigation';
|
import { redirect } from 'next/navigation';
|
||||||
|
import { authOptions } from '@/lib/auth';
|
||||||
|
|
||||||
const FormComponent = lazy(() => import('./components/FormComponent'))
|
const FormComponent = lazy(() => import('./components/FormComponent'))
|
||||||
|
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import LazyLoading from '@/components/loader/LazyLoading';
|
|||||||
import { type IProfile } from './components/type';
|
import { type IProfile } from './components/type';
|
||||||
import { type IUser } from '@/app/admin/administration/user/component/type';
|
import { type IUser } from '@/app/admin/administration/user/component/type';
|
||||||
import { getServerSession } from 'next-auth';
|
import { getServerSession } from 'next-auth';
|
||||||
import { authOptions } from '@/pages/api/auth/[...nextauth]';
|
import { authOptions } from '@/lib/auth';
|
||||||
|
|
||||||
const ForgotPassword = lazy(() => import('./components/ForgotPassword'));
|
const ForgotPassword = lazy(() => import('./components/ForgotPassword'));
|
||||||
const ChangeTheme = lazy(() => import("./components/ChangeTheme"))
|
const ChangeTheme = lazy(() => import("./components/ChangeTheme"))
|
||||||
|
|||||||
@@ -3,9 +3,9 @@ import InterceptModal from '@/components/modal/InterceptModal';
|
|||||||
import LazyLoading from '@/components/loader/LazyLoading';
|
import LazyLoading from '@/components/loader/LazyLoading';
|
||||||
import DateRangePicker from '@/app/performance/[id]/components/DateRangePicker';
|
import DateRangePicker from '@/app/performance/[id]/components/DateRangePicker';
|
||||||
import { getServerSession } from 'next-auth';
|
import { getServerSession } from 'next-auth';
|
||||||
import { authOptions } from '@/pages/api/auth/[...nextauth]';
|
|
||||||
import { Metadata } from 'next';
|
import { Metadata } from 'next';
|
||||||
import dayjs from 'dayjs';
|
import dayjs from 'dayjs';
|
||||||
|
import { authOptions } from '@/lib/auth';
|
||||||
|
|
||||||
const PerformanceComponent = lazy(() => import('@/app/performance/[id]/components'));
|
const PerformanceComponent = lazy(() => import('@/app/performance/[id]/components'));
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1,8 +1,8 @@
|
|||||||
"use server"
|
"use server"
|
||||||
|
|
||||||
|
import { authOptions } from "@/lib/auth";
|
||||||
import axios from "@/lib/axios";
|
import axios from "@/lib/axios";
|
||||||
import { serverApiCall } from "@/lib/server-api";
|
import { serverApiCall } from "@/lib/server-api";
|
||||||
import { authOptions } from "@/pages/api/auth/[...nextauth]";
|
|
||||||
import { getServerSession } from "next-auth";
|
import { getServerSession } from "next-auth";
|
||||||
import { revalidatePath } from "next/cache";
|
import { revalidatePath } from "next/cache";
|
||||||
|
|
||||||
|
|||||||
@@ -2,11 +2,11 @@ import { type Metadata } from 'next';
|
|||||||
import { FC, Suspense, lazy } from 'react';
|
import { FC, Suspense, lazy } from 'react';
|
||||||
import { getServerSession } from 'next-auth';
|
import { getServerSession } from 'next-auth';
|
||||||
import { Download } from 'lucide-react'
|
import { Download } from 'lucide-react'
|
||||||
import { authOptions } from '@/pages/api/auth/[...nextauth]';
|
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { type ResponseData } from '@/types/types';
|
import { type ResponseData } from '@/types/types';
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
import LazyLoading from '@/components/loader/LazyLoading';
|
import LazyLoading from '@/components/loader/LazyLoading';
|
||||||
|
import { authOptions } from '@/lib/auth';
|
||||||
|
|
||||||
const ComponentPage = lazy(() => import('./component'));
|
const ComponentPage = lazy(() => import('./component'));
|
||||||
|
|
||||||
|
|||||||
@@ -2,11 +2,11 @@ import { type Metadata } from 'next';
|
|||||||
import { Suspense, lazy } from 'react';
|
import { Suspense, lazy } from 'react';
|
||||||
import { getServerSession } from 'next-auth';
|
import { getServerSession } from 'next-auth';
|
||||||
import { Download } from 'lucide-react'
|
import { Download } from 'lucide-react'
|
||||||
import { authOptions } from '@/pages/api/auth/[...nextauth]';
|
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { type ResponseData } from '@/types/types';
|
import { type ResponseData } from '@/types/types';
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
import LazyLoading from '@/components/loader/LazyLoading';
|
import LazyLoading from '@/components/loader/LazyLoading';
|
||||||
|
import { authOptions } from '@/lib/auth';
|
||||||
|
|
||||||
const ComponentPage = lazy(() => import('./component'));
|
const ComponentPage = lazy(() => import('./component'));
|
||||||
|
|
||||||
|
|||||||
@@ -2,11 +2,11 @@ import { type Metadata } from 'next';
|
|||||||
import { Suspense, lazy } from 'react';
|
import { Suspense, lazy } from 'react';
|
||||||
import { getServerSession } from 'next-auth';
|
import { getServerSession } from 'next-auth';
|
||||||
import { Download } from 'lucide-react'
|
import { Download } from 'lucide-react'
|
||||||
import { authOptions } from '@/pages/api/auth/[...nextauth]';
|
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { type ResponseData } from '@/types/types';
|
import { type ResponseData } from '@/types/types';
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
import LazyLoading from '@/components/loader/LazyLoading';
|
import LazyLoading from '@/components/loader/LazyLoading';
|
||||||
|
import { authOptions } from '@/lib/auth';
|
||||||
|
|
||||||
const ComponentPage = lazy(() => import('./component'));
|
const ComponentPage = lazy(() => import('./component'));
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
import { type Metadata } from 'next';
|
import { type Metadata } from 'next';
|
||||||
import { Suspense, lazy } from 'react';
|
import { Suspense, lazy } from 'react';
|
||||||
import { getServerSession } from 'next-auth';
|
import { getServerSession } from 'next-auth';
|
||||||
import { authOptions } from '@/pages/api/auth/[...nextauth]';
|
|
||||||
import { type ResponseData } from '@/types/types';
|
import { type ResponseData } from '@/types/types';
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
import LazyLoading from '@/components/loader/LazyLoading';
|
import LazyLoading from '@/components/loader/LazyLoading';
|
||||||
import ExportComponent from './component/Export';
|
import ExportComponent from './component/Export';
|
||||||
|
import { authOptions } from '@/lib/auth';
|
||||||
|
|
||||||
const ComponentPage = lazy(() => import('./component'));
|
const ComponentPage = lazy(() => import('./component'));
|
||||||
|
|
||||||
|
|||||||
@@ -2,11 +2,11 @@ import { type Metadata } from 'next';
|
|||||||
import { Suspense, lazy } from 'react';
|
import { Suspense, lazy } from 'react';
|
||||||
import { getServerSession } from 'next-auth';
|
import { getServerSession } from 'next-auth';
|
||||||
import { Download } from 'lucide-react'
|
import { Download } from 'lucide-react'
|
||||||
import { authOptions } from '@/pages/api/auth/[...nextauth]';
|
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { type ResponseData } from '@/types/types';
|
import { type ResponseData } from '@/types/types';
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
import LazyLoading from '@/components/loader/LazyLoading';
|
import LazyLoading from '@/components/loader/LazyLoading';
|
||||||
|
import { authOptions } from '@/lib/auth';
|
||||||
|
|
||||||
const ComponentPage = lazy(() => import('./component'));
|
const ComponentPage = lazy(() => import('./component'));
|
||||||
|
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ export default function AdminBreadcrumb() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center text-xs font-medium text-muted-foreground flex-wrap">
|
<div className="flex items-center text-xs md:text-sm font-medium text-muted-foreground flex-wrap">
|
||||||
<Link href="/admin" className="hover:text-zinc-900 dark:hover:text-zinc-100 transition-colors">
|
<Link href="/admin" className="hover:text-zinc-900 dark:hover:text-zinc-100 transition-colors">
|
||||||
Pages
|
Pages
|
||||||
</Link>
|
</Link>
|
||||||
@@ -63,9 +63,9 @@ export default function AdminBreadcrumb() {
|
|||||||
{formatSegment(seg)}
|
{formatSegment(seg)}
|
||||||
</span>
|
</span>
|
||||||
) : (
|
) : (
|
||||||
<Link href={href} className="hover:text-zinc-900 dark:hover:text-zinc-100 transition-colors">
|
<span className="hover:text-zinc-900 dark:hover:text-zinc-100 transition-colors">
|
||||||
{formatSegment(seg)}
|
{formatSegment(seg)}
|
||||||
</Link>
|
</span>
|
||||||
)}
|
)}
|
||||||
</span>
|
</span>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -19,9 +19,11 @@ const SidebarItem = dynamic(() => import("./SidebarItem"), {
|
|||||||
ssr: false
|
ssr: false
|
||||||
})
|
})
|
||||||
|
|
||||||
type Props = {};
|
type Props = {
|
||||||
|
menuList: ISideMenu[]
|
||||||
|
};
|
||||||
|
|
||||||
const Sidebar: FC<Props> = ({ }) => {
|
const Sidebar: FC<Props> = ({ menuList }) => {
|
||||||
const [expand, setExpand] = useState(true)
|
const [expand, setExpand] = useState(true)
|
||||||
const [sidebarOpen, setSidebarOpen] = useState(false)
|
const [sidebarOpen, setSidebarOpen] = useState(false)
|
||||||
const [search, setSearch] = useState('')
|
const [search, setSearch] = useState('')
|
||||||
@@ -30,7 +32,8 @@ const Sidebar: FC<Props> = ({ }) => {
|
|||||||
const sidebar = useRef<any>(null);
|
const sidebar = useRef<any>(null);
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
|
|
||||||
const menu: ISideMenu[] = SIDEBAR_MENU
|
// const menu: ISideMenu[] = SIDEBAR_MENU
|
||||||
|
const menu: ISideMenu[] = menuList
|
||||||
|
|
||||||
// close on click outside
|
// close on click outside
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { Skeleton } from '@/components/ui/skeleton';
|
||||||
|
import { FC } from 'react';
|
||||||
|
|
||||||
|
type Props = {};
|
||||||
|
|
||||||
|
const SkeletonSidebar: FC<Props> = () => {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div className='hidden lg:block bg-[#FAF8F5] dark:bg-[#1C1814]/95 text-[#4A3F35] dark:text-[#F6F1E8] w-72 h-full rounded-2xl shadow-[4px_0_24px_rgba(74,63,53,0.06)] border border-[#E5DDD1] dark:border-[#3D342C] p-5'>
|
||||||
|
<div className='p-4 border-b border-[#E5DDD1]/70 dark:border-[#3D342C] w-full'>
|
||||||
|
<Skeleton className='w-full h-7 2xl:h-8' />
|
||||||
|
</div>
|
||||||
|
<div className='mt-5 space-y-5 flex flex-col w-full'>
|
||||||
|
<Skeleton className='w-full h-7 2xl:h-8' />
|
||||||
|
<Skeleton className='w-full h-7 2xl:h-8' />
|
||||||
|
<Skeleton className='w-full h-7 2xl:h-8' />
|
||||||
|
<Skeleton className='w-full h-7 2xl:h-8' />
|
||||||
|
<Skeleton className='w-full h-7 2xl:h-8' />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default SkeletonSidebar;
|
||||||
@@ -2,11 +2,11 @@ import { type Metadata } from 'next';
|
|||||||
import { Suspense, lazy } from 'react';
|
import { Suspense, lazy } from 'react';
|
||||||
import { getServerSession } from 'next-auth';
|
import { getServerSession } from 'next-auth';
|
||||||
import { Download } from 'lucide-react'
|
import { Download } from 'lucide-react'
|
||||||
import { authOptions } from '@/pages/api/auth/[...nextauth]';
|
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
import LazyLoading from '@/components/loader/LazyLoading';
|
import LazyLoading from '@/components/loader/LazyLoading';
|
||||||
import { type ResponseData } from '@/types/types';
|
import { type ResponseData } from '@/types/types';
|
||||||
|
import { authOptions } from '@/lib/auth';
|
||||||
|
|
||||||
const ComponentPage = lazy(() => import('./component'));
|
const ComponentPage = lazy(() => import('./component'));
|
||||||
|
|
||||||
|
|||||||
@@ -2,11 +2,11 @@ import { type Metadata } from 'next';
|
|||||||
import { Suspense, lazy } from 'react';
|
import { Suspense, lazy } from 'react';
|
||||||
import { getServerSession } from 'next-auth';
|
import { getServerSession } from 'next-auth';
|
||||||
import { Download } from 'lucide-react'
|
import { Download } from 'lucide-react'
|
||||||
import { authOptions } from '@/pages/api/auth/[...nextauth]';
|
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
import LazyLoading from '@/components/loader/LazyLoading';
|
import LazyLoading from '@/components/loader/LazyLoading';
|
||||||
import { type ResponseData } from '@/types/types';
|
import { type ResponseData } from '@/types/types';
|
||||||
|
import { authOptions } from '@/lib/auth';
|
||||||
|
|
||||||
const ComponentPage = lazy(() => import('./component'));
|
const ComponentPage = lazy(() => import('./component'));
|
||||||
|
|
||||||
|
|||||||
@@ -2,11 +2,11 @@ import { type Metadata } from 'next';
|
|||||||
import { Suspense, lazy } from 'react';
|
import { Suspense, lazy } from 'react';
|
||||||
import { getServerSession } from 'next-auth';
|
import { getServerSession } from 'next-auth';
|
||||||
import { Download } from 'lucide-react'
|
import { Download } from 'lucide-react'
|
||||||
import { authOptions } from '@/pages/api/auth/[...nextauth]';
|
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
import { type ResponseData } from '@/types/types';
|
import { type ResponseData } from '@/types/types';
|
||||||
import LazyLoading from '@/components/loader/LazyLoading';
|
import LazyLoading from '@/components/loader/LazyLoading';
|
||||||
|
import { authOptions } from '@/lib/auth';
|
||||||
|
|
||||||
const ComponentPage = lazy(() => import('./component'));
|
const ComponentPage = lazy(() => import('./component'));
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import { type Metadata } from 'next';
|
import { type Metadata } from 'next';
|
||||||
import { Suspense, lazy } from 'react';
|
import { Suspense, lazy } from 'react';
|
||||||
import { getServerSession } from 'next-auth';
|
import { getServerSession } from 'next-auth';
|
||||||
import { authOptions } from '@/pages/api/auth/[...nextauth]';
|
|
||||||
import { type ResponseData } from '@/types/types';
|
import { type ResponseData } from '@/types/types';
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
import LazyLoading from '@/components/loader/LazyLoading';
|
import LazyLoading from '@/components/loader/LazyLoading';
|
||||||
|
import { authOptions } from '@/lib/auth';
|
||||||
|
|
||||||
const ComponentPage = lazy(() => import('./component'));
|
const ComponentPage = lazy(() => import('./component'));
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import { type Metadata } from 'next';
|
import { type Metadata } from 'next';
|
||||||
import { Suspense, lazy } from 'react';
|
import { Suspense, lazy } from 'react';
|
||||||
import { getServerSession } from 'next-auth';
|
import { getServerSession } from 'next-auth';
|
||||||
import { authOptions } from '@/pages/api/auth/[...nextauth]';
|
|
||||||
import { type ResponseData } from '@/types/types';
|
import { type ResponseData } from '@/types/types';
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
import LazyLoading from '@/components/loader/LazyLoading';
|
import LazyLoading from '@/components/loader/LazyLoading';
|
||||||
|
import { authOptions } from '@/lib/auth';
|
||||||
|
|
||||||
const ComponentPage = lazy(() => import('./component'));
|
const ComponentPage = lazy(() => import('./component'));
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import { type Metadata } from 'next';
|
import { type Metadata } from 'next';
|
||||||
import { Suspense, lazy } from 'react';
|
import { Suspense, lazy } from 'react';
|
||||||
import { getServerSession } from 'next-auth';
|
import { getServerSession } from 'next-auth';
|
||||||
import { authOptions } from '@/pages/api/auth/[...nextauth]';
|
|
||||||
import { type ResponseData } from '@/types/types';
|
import { type ResponseData } from '@/types/types';
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
import LazyLoading from '@/components/loader/LazyLoading';
|
import LazyLoading from '@/components/loader/LazyLoading';
|
||||||
|
import { authOptions } from '@/lib/auth';
|
||||||
|
|
||||||
const ComponentPage = lazy(() => import('./component'));
|
const ComponentPage = lazy(() => import('./component'));
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import { type Metadata } from 'next';
|
import { type Metadata } from 'next';
|
||||||
import { Suspense, lazy } from 'react';
|
import { Suspense, lazy } from 'react';
|
||||||
import { getServerSession } from 'next-auth';
|
import { getServerSession } from 'next-auth';
|
||||||
import { authOptions } from '@/pages/api/auth/[...nextauth]';
|
|
||||||
import { type ResponseData } from '@/types/types';
|
import { type ResponseData } from '@/types/types';
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
import LazyLoading from '@/components/loader/LazyLoading';
|
import LazyLoading from '@/components/loader/LazyLoading';
|
||||||
|
import { authOptions } from '@/lib/auth';
|
||||||
|
|
||||||
const ComponentPage = lazy(() => import('./component'));
|
const ComponentPage = lazy(() => import('./component'));
|
||||||
|
|
||||||
|
|||||||
+74
-7
@@ -2,27 +2,94 @@ import { Metadata } from "next";
|
|||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { ToggleTheme } from "./components/ToggleTheme";
|
import { ToggleTheme } from "./components/ToggleTheme";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import Sidebar from "./components/Sidebar";
|
|
||||||
import Notification from "./components/Notification";
|
import Notification from "./components/Notification";
|
||||||
import { UserNav } from "../(dashboard)/components/UserNav";
|
import { UserNav } from "../(dashboard)/components/UserNav";
|
||||||
import { House } from "lucide-react";
|
import { House } from "lucide-react";
|
||||||
import AdminBreadcrumb from "./components/Breadcrumb";
|
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 = {
|
export const metadata: Metadata = {
|
||||||
title: "Admin Panel",
|
title: "Admin Panel",
|
||||||
description: "H.A.T.s admin panel page",
|
description: "H.A.T.s admin panel page",
|
||||||
}
|
}
|
||||||
|
|
||||||
export default async function AdminLayout({
|
export default async function AdminLayout({ children }: { children: React.ReactNode }) {
|
||||||
children, // will be a page or nested layout
|
const data = await getAccessData()
|
||||||
}: {
|
|
||||||
children: React.ReactNode
|
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<number, IRoleDetail[]>()
|
||||||
|
|
||||||
|
// 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: <i className={`${parent.menu?.icon} text-base`}></i>,
|
||||||
|
submenuId: parent.menu?.id,
|
||||||
|
submenuItems: children.map((child) => ({
|
||||||
|
title: child.menu?.name,
|
||||||
|
path: cleanPath(child.menu?.path_url!),
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
title: parent.menu?.name!,
|
||||||
|
Icon: <i className={`${parent.menu?.icon} text-base`}></i>,
|
||||||
|
path: cleanPath(parent.menu?.path_url!),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<main className="flex flex-col lg:flex-row h-screen overflow-hidden text-sm bg-soft dark:bg-zinc-900">
|
<main className="flex flex-col lg:flex-row h-screen overflow-hidden text-sm bg-soft dark:bg-zinc-900">
|
||||||
<Sidebar />
|
<Suspense fallback={<SkeletonSidebar />}>
|
||||||
|
<Sidebar menuList={buildSidebarMenu(data.role_detail) || []} />
|
||||||
|
</Suspense>
|
||||||
|
|
||||||
{/* CONTENT */}
|
{/* CONTENT */}
|
||||||
<div className="overflow-x-hidden overflow-y-auto h-screen flex flex-col z-0 w-full px-5 pt-5">
|
<div className="overflow-x-hidden overflow-y-auto h-screen flex flex-col z-0 w-full px-5 pt-5">
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import fetchData from '@/lib/fetchData';
|
|||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { type IRole } from '../component/type';
|
import { type IRole } from '../component/type';
|
||||||
import RolePermissionRow from "../component/role-permission-row";
|
import RolePermissionRow from "../component/role-permission-row";
|
||||||
import { PencilLine } from 'lucide-react';
|
import { PencilLine, ShieldCheck } from 'lucide-react';
|
||||||
|
|
||||||
export const dynamic = 'force-dynamic';
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
@@ -179,7 +179,7 @@ const UserRoleDetailPage: FC<Props> = async ({ params }) => {
|
|||||||
<CardHeader className="pb-3 border-b border-zinc-200 dark:border-zinc-800">
|
<CardHeader className="pb-3 border-b border-zinc-200 dark:border-zinc-800">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<i className="ti ti-checklist text-lg text-his" />
|
<ShieldCheck className='text-his' />
|
||||||
<CardTitle className="text-base font-semibold">
|
<CardTitle className="text-base font-semibold">
|
||||||
Authorized Menu Permissions ({orderedDetails.length} Menus Allowed)
|
Authorized Menu Permissions ({orderedDetails.length} Menus Allowed)
|
||||||
</CardTitle>
|
</CardTitle>
|
||||||
|
|||||||
@@ -81,9 +81,7 @@ export const RoleForm: FC<Props> = ({ isUpdate, roleId, initialData }) => {
|
|||||||
|
|
||||||
const rawDetails = Array.isArray(initialData.role_detail)
|
const rawDetails = Array.isArray(initialData.role_detail)
|
||||||
? initialData.role_detail
|
? initialData.role_detail
|
||||||
: Array.isArray(initialData.privilege)
|
: [];
|
||||||
? initialData.privilege
|
|
||||||
: [];
|
|
||||||
|
|
||||||
rawDetails.forEach((item: any) => {
|
rawDetails.forEach((item: any) => {
|
||||||
// Support both new API format (item.menu.id) and legacy format (item.menu_id)
|
// Support both new API format (item.menu.id) and legacy format (item.menu_id)
|
||||||
@@ -421,7 +419,7 @@ export const RoleForm: FC<Props> = ({ isUpdate, roleId, initialData }) => {
|
|||||||
{/* Bottom Action Bar */}
|
{/* Bottom Action Bar */}
|
||||||
<div className="mt-6 flex justify-end items-center gap-3">
|
<div className="mt-6 flex justify-end items-center gap-3">
|
||||||
<Link href="/admin/rbac/user-role">
|
<Link href="/admin/rbac/user-role">
|
||||||
<Button variant="outline" type="button" disabled={isLoading} className='text-zinc-800! dark:text-white'>
|
<Button variant="outline" type="button" disabled={isLoading} >
|
||||||
Cancel
|
Cancel
|
||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</Link>
|
||||||
|
|||||||
@@ -118,9 +118,7 @@ const ComponentRolePage: FC<Props> = ({ data }) => {
|
|||||||
render: (details: any, record: IRole) => {
|
render: (details: any, record: IRole) => {
|
||||||
const count = Array.isArray(details)
|
const count = Array.isArray(details)
|
||||||
? details.length
|
? details.length
|
||||||
: Array.isArray(record.privilege)
|
: 0;
|
||||||
? record.privilege.length
|
|
||||||
: 0;
|
|
||||||
return (
|
return (
|
||||||
<span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-zinc-100 dark:bg-zinc-800 text-zinc-700 dark:text-zinc-300">
|
<span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-zinc-100 dark:bg-zinc-800 text-zinc-700 dark:text-zinc-300">
|
||||||
{count} menus
|
{count} menus
|
||||||
|
|||||||
+1
-1
@@ -5,7 +5,6 @@ import type { Metadata, Viewport } from 'next'
|
|||||||
import { Plus_Jakarta_Sans } from 'next/font/google'
|
import { Plus_Jakarta_Sans } from 'next/font/google'
|
||||||
|
|
||||||
import { getServerSession } from 'next-auth'
|
import { getServerSession } from 'next-auth'
|
||||||
import { authOptions } from '@/pages/api/auth/[...nextauth]'
|
|
||||||
|
|
||||||
import { ThemeProvider } from '@/providers/ThemeProvider'
|
import { ThemeProvider } from '@/providers/ThemeProvider'
|
||||||
import SessionProvider from '@/providers/SessionProvider'
|
import SessionProvider from '@/providers/SessionProvider'
|
||||||
@@ -14,6 +13,7 @@ import AntdConfigProvider from '@/providers/AntdConfigProvider';
|
|||||||
import ProgressBarProviders from '@/providers/ProgressBarProvider';
|
import ProgressBarProviders from '@/providers/ProgressBarProvider';
|
||||||
import { TooltipProvider } from '@/components/ui/tooltip';
|
import { TooltipProvider } from '@/components/ui/tooltip';
|
||||||
import ServiceWorkerRegister from '@/components/pwa/ServiceWorkerRegister';
|
import ServiceWorkerRegister from '@/components/pwa/ServiceWorkerRegister';
|
||||||
|
import { authOptions } from '@/lib/auth';
|
||||||
|
|
||||||
|
|
||||||
const jakarta = Plus_Jakarta_Sans({ subsets: ['latin'] })
|
const jakarta = Plus_Jakarta_Sans({ subsets: ['latin'] })
|
||||||
|
|||||||
@@ -2,12 +2,12 @@ import { FC, Suspense, lazy } from 'react';
|
|||||||
import { redirect } from 'next/navigation';
|
import { redirect } from 'next/navigation';
|
||||||
import { getServerSession } from 'next-auth';
|
import { getServerSession } from 'next-auth';
|
||||||
import dayjs from 'dayjs';
|
import dayjs from 'dayjs';
|
||||||
import { authOptions } from '@/pages/api/auth/[...nextauth]';
|
|
||||||
import { Card, Card900, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
import { Card, Card900, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
import LazyLoading from '@/components/loader/LazyLoading';
|
import LazyLoading from '@/components/loader/LazyLoading';
|
||||||
import fetchData, { fetchDataWithPost } from '@/lib/fetchData';
|
import fetchData, { fetchDataWithPost } from '@/lib/fetchData';
|
||||||
import { generateHourMinutes } from '@/lib/helper';
|
import { generateHourMinutes } from '@/lib/helper';
|
||||||
import ViewAvatar from '@/components/ViewAvatar';
|
import ViewAvatar from '@/components/ViewAvatar';
|
||||||
|
import { authOptions } from '@/lib/auth';
|
||||||
|
|
||||||
const DonutChart = lazy(() => import('./DonutChart'));
|
const DonutChart = lazy(() => import('./DonutChart'));
|
||||||
const AreaChart = lazy(() => import('./AreaChart'))
|
const AreaChart = lazy(() => import('./AreaChart'))
|
||||||
|
|||||||
+197
@@ -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;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import { signOut, useSession } from "next-auth/react";
|
import { signOut, useSession } from "next-auth/react";
|
||||||
import axios from "../axios";
|
import axios from "../axios";
|
||||||
import { EXP_SESSION } from "@/pages/api/auth/[...nextauth]";
|
import { EXP_SESSION } from "../auth";
|
||||||
|
|
||||||
export const useRefreshToken = () => {
|
export const useRefreshToken = () => {
|
||||||
const { data: session, update } = useSession();
|
const { data: session, update } = useSession();
|
||||||
|
|||||||
+1
-1
@@ -1,8 +1,8 @@
|
|||||||
import { getServerSession } from "next-auth"
|
import { getServerSession } from "next-auth"
|
||||||
import { authOptions } from "@/pages/api/auth/[...nextauth]"
|
|
||||||
import { redirect } from "next/navigation"
|
import { redirect } from "next/navigation"
|
||||||
import { ResponseData } from "@/types/types"
|
import { ResponseData } from "@/types/types"
|
||||||
import { logger } from "./logger"
|
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) {
|
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
|
const { BASE_URL_API } = process.env
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
+1
-1
@@ -1,9 +1,9 @@
|
|||||||
"use server"
|
"use server"
|
||||||
|
|
||||||
import { getServerSession } from "next-auth";
|
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 axios from "@/lib/axios"; // Your axios instance
|
||||||
import { writeLog } from "./logger";
|
import { writeLog } from "./logger";
|
||||||
|
import { authOptions } from "./auth";
|
||||||
|
|
||||||
// 1. Define a standard response format for all your actions
|
// 1. Define a standard response format for all your actions
|
||||||
export type ActionResponse<T = any> =
|
export type ActionResponse<T = any> =
|
||||||
|
|||||||
@@ -1,192 +1,5 @@
|
|||||||
import NextAuth, { type NextAuthOptions } from "next-auth"
|
import { authOptions } from "@/lib/auth"
|
||||||
import CredentialsProvider from "next-auth/providers/credentials";
|
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)
|
export default NextAuth(authOptions)
|
||||||
Vendored
+4
-1
@@ -19,18 +19,21 @@ declare module 'next-auth' {
|
|||||||
company?: ICompany
|
company?: ICompany
|
||||||
division?: IDivision
|
division?: IDivision
|
||||||
role: {
|
role: {
|
||||||
|
id: number
|
||||||
code: string
|
code: string
|
||||||
name: string
|
name: string
|
||||||
allow_admin_panel: boolean
|
allow_admin_panel: boolean
|
||||||
role_detail?: {
|
role_detail?: {
|
||||||
|
action: string[]
|
||||||
menu: {
|
menu: {
|
||||||
|
id: number
|
||||||
code: string
|
code: string
|
||||||
name: string
|
name: string
|
||||||
menu_parent_id: number
|
menu_parent_id: number
|
||||||
icon: string
|
icon: string
|
||||||
path_url: string
|
path_url: string
|
||||||
sort: number
|
sort: number
|
||||||
hidden_data: boolean
|
is_admin_menu: boolean
|
||||||
}
|
}
|
||||||
}[]
|
}[]
|
||||||
}
|
}
|
||||||
|
|||||||
+8
-1
@@ -21,13 +21,21 @@ export interface IMenu {
|
|||||||
is_admin_menu: boolean;
|
is_admin_menu: boolean;
|
||||||
menu_parent_id?: number | null;
|
menu_parent_id?: number | null;
|
||||||
action?: string[];
|
action?: string[];
|
||||||
|
status_id?: number
|
||||||
status?: {
|
status?: {
|
||||||
id?: number;
|
id?: number;
|
||||||
code?: string;
|
code?: string;
|
||||||
name?: string;
|
name?: string;
|
||||||
};
|
};
|
||||||
|
sort: number
|
||||||
children?: IMenu[];
|
children?: IMenu[];
|
||||||
menu_level?: number;
|
menu_level?: number;
|
||||||
|
"created_at"?: string
|
||||||
|
"created_by"?: number
|
||||||
|
"updated_at"?: string
|
||||||
|
"updated_by"?: 1
|
||||||
|
"deleted_at"?: string
|
||||||
|
"deleted_by"?: number
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface IRoleDetail {
|
export interface IRoleDetail {
|
||||||
@@ -48,7 +56,6 @@ export interface IRole {
|
|||||||
description?: string;
|
description?: string;
|
||||||
allow_admin_panel?: boolean;
|
allow_admin_panel?: boolean;
|
||||||
role_detail?: IRoleDetail[];
|
role_detail?: IRoleDetail[];
|
||||||
privilege?: any[];
|
|
||||||
status?: {
|
status?: {
|
||||||
id?: number;
|
id?: number;
|
||||||
code?: string;
|
code?: string;
|
||||||
|
|||||||
Reference in New Issue
Block a user