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:
42
app/components/ProtectedRoute.tsx
Normal file
42
app/components/ProtectedRoute.tsx
Normal 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}</>;
|
||||
}
|
||||
Reference in New Issue
Block a user