From 2261af9848e87f2032f7a767380f82b58b5aab93 Mon Sep 17 00:00:00 2001 From: sam Date: Wed, 26 Feb 2025 18:00:01 +0800 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20=20private=20route?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/(defaults)/layout.tsx | 9 ++++++++- hoc/withAuth.tsx | 27 +++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 hoc/withAuth.tsx 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