重构大量文件
This commit is contained in:
+15
-5
@@ -1,15 +1,25 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import type { NextRequest } from 'next/server';
|
||||
import { getSessionCookieName, verifySessionToken } from '@/lib/session';
|
||||
|
||||
export default function proxy(request: NextRequest) {
|
||||
const authCookie = request.cookies.get('auth');
|
||||
const PUBLIC_PATHS = new Set(['/login']);
|
||||
const PUBLIC_API_PATHS = new Set(['/api/auth/login', '/api/settings/init']);
|
||||
|
||||
export default async function proxy(request: NextRequest) {
|
||||
const authCookie = request.cookies.get(getSessionCookieName());
|
||||
const isLoginPage = request.nextUrl.pathname === '/login';
|
||||
const isPublicPath = PUBLIC_PATHS.has(request.nextUrl.pathname);
|
||||
const isPublicApiPath = PUBLIC_API_PATHS.has(request.nextUrl.pathname);
|
||||
const isAuthenticated = authCookie ? await verifySessionToken(authCookie.value) : false;
|
||||
|
||||
if (!authCookie && !isLoginPage) {
|
||||
if (!isAuthenticated && !isPublicPath && !isPublicApiPath) {
|
||||
if (request.nextUrl.pathname.startsWith('/api')) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
return NextResponse.redirect(new URL('/login', request.url));
|
||||
}
|
||||
|
||||
if (authCookie && isLoginPage) {
|
||||
if (isAuthenticated && isLoginPage) {
|
||||
return NextResponse.redirect(new URL('/', request.url));
|
||||
}
|
||||
|
||||
@@ -17,5 +27,5 @@ export default function proxy(request: NextRequest) {
|
||||
}
|
||||
|
||||
export const config = {
|
||||
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
|
||||
matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user