Enhance authentication flow by implementing ProtectedRoute component across various pages, ensuring users are redirected based on their authentication status. Update login page to support Google sign-in and handle redirect URLs after login. Modify analytics and links pages to include loading indicators and protected access. Update next.config.ts to enable middleware for edge functions.

This commit is contained in:
2025-04-23 17:36:54 +08:00
parent c56410b4de
commit 1b4e0bafc7
15 changed files with 597 additions and 85 deletions

View File

@@ -0,0 +1,42 @@
'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}</>;
}