feat: 添加checkAppId函数以验证上下文中的App ID,并在auth中间件中使用

This commit is contained in:
2026-03-09 19:23:51 +08:00
parent e68b77f871
commit efb30708eb
2 changed files with 36 additions and 1 deletions

View File

@@ -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`);

View File

@@ -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');