feat: 添加checkAppId函数以验证上下文中的App ID,并在auth中间件中使用
This commit is contained in:
@@ -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`);
|
||||
|
||||
35
src/route.ts
35
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');
|
||||
|
||||
Reference in New Issue
Block a user