34 lines
1.1 KiB
TypeScript
34 lines
1.1 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import type { NextRequest } from 'next/server';
|
|
|
|
// 需要登录才能访问的路径
|
|
const protectedPaths = ['/', '/publish', '/admin'];
|
|
|
|
// 公开路径 (无需登录)
|
|
const publicPaths = ['/login', '/register'];
|
|
|
|
export function proxy(request: NextRequest) {
|
|
const { pathname } = request.nextUrl;
|
|
|
|
// 检查是否有 access_token cookie
|
|
const token = request.cookies.get('access_token');
|
|
|
|
// 访问受保护页面但未登录 → 重定向到登录页
|
|
if (protectedPaths.some(path => pathname === path || pathname.startsWith(path + '/')) && !token) {
|
|
const loginUrl = new URL('/login', request.url);
|
|
loginUrl.searchParams.set('from', pathname);
|
|
return NextResponse.redirect(loginUrl);
|
|
}
|
|
|
|
// 已登录用户访问登录/注册页 → 重定向到首页
|
|
if (publicPaths.includes(pathname) && token) {
|
|
return NextResponse.redirect(new URL('/', request.url));
|
|
}
|
|
|
|
return NextResponse.next();
|
|
}
|
|
|
|
export const config = {
|
|
matcher: ['/', '/publish/:path*', '/admin/:path*', '/login', '/register']
|
|
};
|