Files
wrong-notebook/src/proxy.ts
2026-11-20 13:20:58 +08:00

106 lines
4.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 { NextResponse } from "next/server";
import { getToken } from "next-auth/jwt";
import type { NextRequest } from "next/server";
import { createLogger } from "@/lib/logger";
import { prisma } from "@/lib/prisma";
const logger = createLogger('proxy');
/** 登录与否都能访问的公开页面:使用协议要在 /initialize 未登录时也能打开 */
const PUBLIC_PATHS = ["/eula"];
function isPublicPath(path: string): boolean {
return PUBLIC_PATHS.some((prefix) => path === prefix || path.startsWith(`${prefix}/`));
}
export async function proxy(req: NextRequest) {
// 页面请求的登录保护(Next.js 16 起由 middleware 更名为 proxy,运行在 Node.js 运行时)
logger.debug({ method: req.method, path: req.nextUrl.pathname }, 'Processing request');
if (isPublicPath(req.nextUrl.pathname)) return NextResponse.next();
try {
const token = await getToken({
req,
secret: process.env.NEXTAUTH_SECRET,
cookieName: "next-auth.session-token", // Explicitly look for the standardized cookie
});
// 页面代理不能只相信 JWT:管理员停用账号后,旧 token 仍可能存在。
// API 层也会再次校验,这里提前阻止旧会话继续访问受保护页面。
const currentUser = token?.id
? await prisma.user.findUnique({ where: { id: token.id }, select: { isActive: true, role: true } })
: null;
const isAuth = !!token?.id && currentUser?.isActive !== false && currentUser !== null;
const currentRole = currentUser?.role;
// /initialize:全新安装时用一次性初始化链接创建管理员,未登录也要能打开
const isAuthPage = ["/login", "/register", "/initialize"].some((prefix) => req.nextUrl.pathname.startsWith(prefix));
const isAdminPage = req.nextUrl.pathname.startsWith("/admin");
logger.debug({
path: req.nextUrl.pathname,
isAuth,
isAuthPage,
hasToken: !!token,
cookies: req.cookies.getAll().map(c => c.name)
}, 'Auth status');
if (isAuthPage) {
if (isAuth) {
logger.debug('Redirecting authenticated user to /');
return NextResponse.redirect(new URL("/", req.url));
}
return null;
}
if (!isAuth) {
let from = req.nextUrl.pathname;
if (req.nextUrl.search) {
from += req.nextUrl.search;
}
logger.debug({ callbackUrl: from }, 'Redirecting unauthenticated user to login');
return NextResponse.redirect(
new URL(`/login?callbackUrl=${encodeURIComponent(from)}`, req.url)
);
}
// 管理员仍使用默认密码时,所有页面都先跳到安装向导改密码
const isSetupPage = req.nextUrl.pathname.startsWith("/setup");
if (token?.mustChangePassword && !isSetupPage) {
logger.info({ userId: token.id, path: req.nextUrl.pathname }, 'Redirecting admin with default password to /setup');
return NextResponse.redirect(new URL("/setup", req.url));
}
// Admin route protection: only allow users with admin role
if (isAdminPage && currentRole !== "admin") {
logger.warn({ userId: token?.id, path: req.nextUrl.pathname }, 'Non-admin user attempting to access admin area');
return NextResponse.redirect(new URL("/", req.url));
}
} catch (e) {
// 无法确认登录状态时按未登录处理(失败即拒绝),否则会绕过强制改密和管理员页面的拦截
logger.error({ error: e }, 'Error processing token');
const path = req.nextUrl.pathname;
if (["/login", "/register", "/initialize"].some((prefix) => path.startsWith(prefix))) {
return NextResponse.next();
}
return NextResponse.redirect(
new URL(`/login?callbackUrl=${encodeURIComponent(path + req.nextUrl.search)}`, req.url)
);
}
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* - icons/、manifest.webmanifest(PWA 图标与清单,登录页也要能加载)
* - sw.js、offline.html(Service Worker 与离线页,未登录时也要能加载)
*/
"/((?!api|_next/static|_next/image|favicon.ico|icons/|manifest.webmanifest|sw.js|offline.html).*)",
],
};