80 lines
3.0 KiB
TypeScript
80 lines
3.0 KiB
TypeScript
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));
|
||
|
||
// 检查各个认证cookie
|
||
const accessToken = request.cookies.get('sb-access-token');
|
||
const refreshToken = request.cookies.get('sb-refresh-token');
|
||
const providerToken = request.cookies.get('sb-provider-token');
|
||
const authToken = request.cookies.get('supabase-auth-token');
|
||
const customAuthToken = request.cookies.get('sb-auth-token');
|
||
|
||
console.log('[Middleware] 认证Cookie详情:', {
|
||
'sb-access-token': accessToken ? '存在' : '不存在',
|
||
'sb-refresh-token': refreshToken ? '存在' : '不存在',
|
||
'sb-provider-token': providerToken ? '存在' : '不存在',
|
||
'supabase-auth-token': authToken ? '存在' : '不存在',
|
||
'sb-auth-token': customAuthToken ? '存在' : '不存在'
|
||
});
|
||
|
||
// 检查用户是否登录
|
||
const isLoggedIn = !!(accessToken || refreshToken || providerToken || authToken || customAuthToken);
|
||
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',
|
||
],
|
||
};
|