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

69
middleware.ts Normal file
View File

@@ -0,0 +1,69 @@
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
// 获取请求的路径
const path = request.nextUrl.pathname;
console.log(`[Middleware] 请求路径: ${path}`);
// 定义不需要验证的路径
const publicPaths = ['/login', '/register', '/auth/callback'];
// API 路由不需要验证
if (path.startsWith('/api/')) {
console.log('[Middleware] API路由跳过验证');
return NextResponse.next();
}
// 静态资源不需要验证
if (path.includes('/_next/') || path.includes('/static/') || path.match(/\.(ico|png|jpg|jpeg|svg|css|js)$/)) {
console.log('[Middleware] 静态资源,跳过验证');
return NextResponse.next();
}
// 检查是否是公开路径
const isPublicPath = publicPaths.some(publicPath => path === publicPath || path.startsWith(publicPath));
console.log(`[Middleware] 是公开路径: ${isPublicPath}`);
// 获取所有 cookie
const allCookies = Object.fromEntries(request.cookies.getAll().map(c => [c.name, c.value]));
console.log('[Middleware] 所有Cookie:', JSON.stringify(allCookies));
// 检查用户是否登录
const supabaseCookie = request.cookies.get('sb-access-token') ||
request.cookies.get('sb-refresh-token') ||
request.cookies.get('sb-provider-token') ||
request.cookies.get('supabase-auth-token');
const isLoggedIn = !!supabaseCookie;
console.log(`[Middleware] 用户是否登录: ${isLoggedIn}`);
// 如果是公开路径但已登录,重定向到首页
if (isPublicPath && isLoggedIn) {
console.log('[Middleware] 已登录用户访问公开路径,重定向到首页');
return NextResponse.redirect(new URL('/', request.url));
}
// 如果不是公开路径且未登录,重定向到登录页
if (!isPublicPath && !isLoggedIn) {
console.log('[Middleware] 未登录用户访问私有路径,重定向到登录页');
const redirectUrl = new URL('/login', request.url);
redirectUrl.searchParams.set('redirect', encodeURIComponent(request.url));
return NextResponse.redirect(redirectUrl);
}
console.log('[Middleware] 通过验证,允许访问');
return NextResponse.next();
}
// 配置中间件匹配的路径
export const config = {
matcher: [
// 匹配所有路径,但排除静态资源
'/((?!_next/static|_next/image|favicon.ico).*)',
// 明确包括重要的路由
'/',
'/analytics',
'/links',
'/create-shorturl',
],
};