From efb30708eb51f4445c1c8575340a72ae7666fa47 Mon Sep 17 00:00:00 2001 From: abearxiong Date: Mon, 9 Mar 2026 19:23:51 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0checkAppId=E5=87=BD?= =?UTF-8?q?=E6=95=B0=E4=BB=A5=E9=AA=8C=E8=AF=81=E4=B8=8A=E4=B8=8B=E6=96=87?= =?UTF-8?q?=E4=B8=AD=E7=9A=84App=20ID=EF=BC=8C=E5=B9=B6=E5=9C=A8auth?= =?UTF-8?q?=E4=B8=AD=E9=97=B4=E4=BB=B6=E4=B8=AD=E4=BD=BF=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/modules/n5/index.ts | 2 +- src/route.ts | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/src/modules/n5/index.ts b/src/modules/n5/index.ts index 3d7b0a8..66623d1 100644 --- a/src/modules/n5/index.ts +++ b/src/modules/n5/index.ts @@ -5,7 +5,7 @@ import { IncomingMessage, ServerResponse } from 'http'; type ProxyOptions = { createNotFoundPage: (msg?: string) => any; }; -// /n5/:slug +// /n5/:slug/ export const N5Proxy = async (req: IncomingMessage, res: ServerResponse, opts?: ProxyOptions) => { const { url } = req; const _url = new URL(url || '', `http://localhost`); diff --git a/src/route.ts b/src/route.ts index 197655e..a842386 100644 --- a/src/route.ts +++ b/src/route.ts @@ -6,6 +6,23 @@ import { User } from './models/user.ts'; import { createCookie, getSomeInfoFromReq } from './routes/user/me.ts'; import { toJSONSchema } from '@kevisual/router'; import { pick } from 'es-toolkit'; +/** + * 验证上下文中的 App ID 是否与指定的 App ID 匹配 + * @param {any} ctx - 上下文对象,可能包含 appId 属性 + * @param {string} appId - 需要验证的目标 App ID + * @returns {boolean} 如果 ctx 中包含 appId 且匹配则返回 true,否则返回 false + * @throws {Error} 如果 ctx 中包含 appId 但不匹配,则抛出 403 错误 + */ +const checkAppId = (ctx: any, appId: string) => { + const _appId = ctx?.app?.appId; + if (_appId) { + if (_appId !== appId) { + ctx.throw(403, 'Invalid App ID'); + } + return true; + } + return false; +} /** * 添加auth中间件, 用于验证token @@ -23,6 +40,12 @@ export const addAuth = (app: App) => { }) .define(async (ctx) => { const token = ctx.query.token; + if (checkAppId(ctx, app.appId)) { + ctx.state.tokenUser = { + username: 'default', + } + return; + } // 已经有用户信息则直接返回,不需要重复验证 if (ctx.state.tokenUser) { return; @@ -52,6 +75,12 @@ export const addAuth = (app: App) => { description: '验证token,可以不成功,错误不返回401,正确赋值到ctx.state.tokenUser,失败赋值null', }) .define(async (ctx) => { + if (checkAppId(ctx, app.appId)) { + ctx.state.tokenUser = { + username: 'default', + } + return; + } // 已经有用户信息则直接返回,不需要重复验证 if (ctx.state.tokenUser) { return; @@ -84,6 +113,12 @@ app description: '验证token,必须是admin用户, 错误返回403,正确赋值到ctx.state.tokenAdmin', }) .define(async (ctx) => { + if (checkAppId(ctx, app.appId)) { + ctx.state.tokenUser = { + username: 'default', + } + return; + } const tokenUser = ctx.state.tokenUser; if (!tokenUser) { ctx.throw(401, 'No User For authorized');