2026-01-18 05:13:53 +08:00
|
|
|
import { convexAuthNextjsMiddleware, createRouteMatcher, nextjsMiddlewareRedirect } from "@convex-dev/auth/nextjs/server";
|
|
|
|
|
|
|
|
|
|
// 说明:
|
|
|
|
|
// - 这里启用 Convex Auth 的 Next.js 中间件,负责:
|
|
|
|
|
// 1) 代理 /api/auth 到 Convex(用于 signIn / signOut 等动作)
|
|
|
|
|
// 2) 刷新/同步 auth cookies
|
|
|
|
|
// 3) 对需要登录的页面做统一拦截
|
|
|
|
|
// - 默认将未登录用户重定向到 /auth(Convex Auth 登录页)。
|
|
|
|
|
|
|
|
|
|
const isPublicRoute = createRouteMatcher([
|
|
|
|
|
"/auth",
|
|
|
|
|
"/login",
|
|
|
|
|
"/api/auth(.*)",
|
2026-01-20 07:24:12 +08:00
|
|
|
// 说明:ONLYOFFICE 文档服务器(容器/远端)拉取文件与回调保存不携带用户态,必须放行。
|
|
|
|
|
"/api/onlyoffice/proxy(.*)",
|
|
|
|
|
"/api/onlyoffice/callback(.*)",
|
2026-01-18 05:13:53 +08:00
|
|
|
"/api/health(.*)",
|
|
|
|
|
"/_next(.*)",
|
|
|
|
|
"/favicon.ico",
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
export default convexAuthNextjsMiddleware(async (request, ctx) => {
|
|
|
|
|
// 公共路由不做拦截(但 middleware 仍会处理 token 刷新/代理等)。
|
|
|
|
|
if (isPublicRoute(request)) return;
|
|
|
|
|
|
|
|
|
|
// 只在启用 Convex 模式时做鉴权拦截;否则走 Supabase 逻辑(页面内部自行处理)。
|
|
|
|
|
// 注意:middleware 运行在 Edge/Node 环境中,读取到的是运行期环境变量。
|
|
|
|
|
if (process.env.NEXT_PUBLIC_USE_CONVEX !== "1") return;
|
|
|
|
|
|
|
|
|
|
const authed = await ctx.convexAuth.isAuthenticated();
|
|
|
|
|
if (!authed) {
|
|
|
|
|
return nextjsMiddlewareRedirect(request, "/auth");
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
export const config = {
|
|
|
|
|
// 说明:排除静态资源,避免无意义的中间件开销。
|
|
|
|
|
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
|
|
|
|
|
};
|