Files
LunaTV/src/middleware.ts
2025-06-30 22:57:32 +08:00

57 lines
1.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { NextRequest, NextResponse } from 'next/server';
// 全站(含 /api鉴权中间件运行于 Edge Runtime。
export async function middleware(req: NextRequest) {
const { pathname, search } = req.nextUrl;
// 1. 放行无需鉴权的路径
if (
pathname.startsWith('/login') || // 登录页
pathname.startsWith('/api/login') || // 登录接口
pathname.startsWith('/_next') || // Next.js 静态文件
pathname === '/favicon.ico' ||
pathname.startsWith('/icons') ||
pathname === '/manifest.json' ||
pathname === '/logo.png' ||
pathname === '/screenshot.png'
) {
return NextResponse.next();
}
// 内部请求标记,避免递归拦截
if (req.headers.get('x-internal-auth') === 'true') {
return NextResponse.next();
}
// 通过后端接口验证登录状态GET /api/login
const origin = req.nextUrl.origin;
const verifyRes = await fetch(`${origin}/api/login`, {
method: 'GET',
headers: {
Cookie: req.headers.get('cookie') || '',
'x-internal-auth': 'true',
},
});
if (verifyRes.ok) {
return NextResponse.next();
}
// 未通过校验API 返回 401页面跳转登录
if (pathname.startsWith('/api')) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const loginUrl = req.nextUrl.clone();
loginUrl.pathname = '/login';
loginUrl.searchParams.set('redirect', pathname + search);
return NextResponse.redirect(loginUrl);
}
// 2. 指定哪些路径使用 middleware
export const config = {
matcher: [
'/((?!_next/static|_next/image|favicon.ico|manifest.json|icons|logo.png|screenshot.png|api/login).*)',
],
};