42 lines
1.4 KiB
TypeScript
42 lines
1.4 KiB
TypeScript
'use client';
|
|
|
|
import { useEffect } from 'react';
|
|
import { useRouter } from 'next/navigation';
|
|
import { useAuth } from '@/lib/auth';
|
|
|
|
export default function ProtectedRoute({ children }: { children: React.ReactNode }) {
|
|
const router = useRouter();
|
|
const { user, isLoading } = useAuth();
|
|
|
|
useEffect(() => {
|
|
// 如果非加载状态且用户未登录,重定向到登录页
|
|
if (!isLoading && !user) {
|
|
console.log('ProtectedRoute: 未登录,重定向到登录页');
|
|
// 保存当前URL以便登录后可以返回
|
|
const currentUrl = window.location.href;
|
|
router.push(`/login?redirect=${encodeURIComponent(currentUrl)}`);
|
|
}
|
|
}, [isLoading, user, router]);
|
|
|
|
// 如果正在加载,显示加载指示器
|
|
if (isLoading) {
|
|
return (
|
|
<div className="flex items-center justify-center min-h-screen">
|
|
<div className="text-center">
|
|
<div className="animate-spin rounded-full h-16 w-16 border-t-2 border-b-2 border-blue-500 mx-auto"></div>
|
|
<p className="mt-4 text-lg text-gray-700 dark:text-gray-300">加载中...</p>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// 如果用户未登录,不渲染任何内容(等待重定向)
|
|
if (!user) {
|
|
console.log('ProtectedRoute: 用户未登录,等待重定向');
|
|
return null;
|
|
}
|
|
|
|
// 用户已登录,渲染子组件
|
|
console.log('ProtectedRoute: 用户已登录,渲染内容');
|
|
return <>{children}</>;
|
|
}
|