diff --git a/app/(defaults)/layout.tsx b/app/(defaults)/layout.tsx index eb9c3ed..6c27841 100644 --- a/app/(defaults)/layout.tsx +++ b/app/(defaults)/layout.tsx @@ -1,3 +1,5 @@ +"use client"; + import ContentAnimation from '@/components/layouts/content-animation'; import Footer from '@/components/layouts/footer'; import Header from '@/components/layouts/header'; @@ -7,8 +9,11 @@ import ScrollToTop from '@/components/layouts/scroll-to-top'; import Setting from '@/components/layouts/setting'; import Sidebar from '@/components/layouts/sidebar'; import Portals from '@/components/portals'; +import withAuth from '@/hoc/withAuth'; +import { FC } from 'react'; + +const DefaultLayout: FC<{ children: React.ReactNode }> = ({ children }) => { -export default function DefaultLayout({ children }: { children: React.ReactNode }) { return ( <> {/* BEGIN MAIN CONTAINER */} @@ -39,3 +44,5 @@ export default function DefaultLayout({ children }: { children: React.ReactNode ); } + +export default withAuth(DefaultLayout); diff --git a/hoc/withAuth.tsx b/hoc/withAuth.tsx new file mode 100644 index 0000000..4a4ddc9 --- /dev/null +++ b/hoc/withAuth.tsx @@ -0,0 +1,27 @@ +import { useEffect, useState } from "react"; +import { useRouter } from "next/navigation"; + +const withAuth = (WrappedComponent: React.FC) => { + return (props: any) => { + const [isAuthenticated, setIsAuthenticated] = useState(false) + const router = useRouter() + + useEffect(() => { + const token = localStorage.getItem("token") + + if (!token) { + router.replace("/login") // Redirect to login if no token + } else { + setIsAuthenticated(true) + } + }, []) + + if (!isAuthenticated) { + return null // Avoid rendering until auth check is done + } + + return + }; +}; + +export default withAuth