'use client' import { useAuth } from '@/contexts/AuthContext' import { useRouter } from 'next/navigation' import { useEffect } from 'react' interface ProtectedRouteProps { children: React.ReactNode redirectTo?: string fallback?: React.ReactNode } export const ProtectedRoute: React.FC = ({ children, redirectTo = '/login', fallback }) => { const { isAuthenticated, isLoading, checkAuth } = useAuth() const router = useRouter() useEffect(() => { const verifyAuth = async () => { if (!isLoading) { if (!isAuthenticated) { router.push(redirectTo) return } // 額外檢查 token 有效性 const isValid = await checkAuth() if (!isValid) { router.push(redirectTo) } } } verifyAuth() }, [isAuthenticated, isLoading, router, redirectTo, checkAuth]) // Loading 狀態 if (isLoading) { return ( fallback || (

驗證中...

) ) } // 未認證 if (!isAuthenticated) { return null // 這時會觸發重定向 } // 已認證,渲染子組件 return <>{children} } // 便利的 HOC 版本 export function withAuth(Component: React.ComponentType, redirectTo = '/login') { const AuthenticatedComponent = (props: T) => ( ) AuthenticatedComponent.displayName = `withAuth(${Component.displayName || Component.name})` return AuthenticatedComponent }