Files
OCS_service/server/middleware/api-auth.ts
T
2026-05-22 23:10:40 +08:00

36 lines
1.3 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.
// server/middleware/api-auth.ts - 统一 API 鉴权层,所有非公开 /api/* 请求都必须通过此处
import { createError, getRequestURL } from "h3";
import { isPublicApiRoute } from "~~/server/utils/api-auth-rules";
import { getAuthSession } from "~~/server/utils/auth";
/**
* 统一 API 鉴权 middleware
*
* 策略:默认所有 /api/* 需要登录,只有 publicApiRoutes 里的路由可以公开访问。
* 鉴权通过后将 session 挂到 event.context.authhandler 直接取用,无需重复查询。
*
* 不影响页面渲染、静态资源或 Nuxt 内部请求。
*/
export default defineEventHandler(async (event) => {
const { pathname } = getRequestURL(event);
const method = event.method;
// 只处理 /api/ 路径
if (!pathname.startsWith("/api/")) return;
// OPTIONS 预检请求不需要鉴权,CORS headers 由 nuxt.config routeRules 统一设置
if (method === "OPTIONS") return;
// 公开路由直接放行
if (isPublicApiRoute(pathname, method)) return;
const session = await getAuthSession(event);
if (!session) {
throw createError({ statusCode: 401, statusMessage: "未登录" });
}
// 挂到 event.context,后续 handler 直接读取,不再重复查询 session
event.context.auth = session;
});