Files
ZYZ/web-server/app/middleware/parmsDecode.ts
2026-03-13 01:38:40 +00:00

65 lines
2.5 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.
import { genCode } from '../../../shared/pubUtils/util';
import { MsgEncrypt } from "../../../shared/pubUtils/sysUtil";
import { Context } from 'egg';
module.exports = (options: any) => {
return async function parmsDecode(ctx: Context, next: () => Promise<any>) {
let url = ctx.request.url;
ctx.logcode = genCode(10);
if (url.indexOf("/dev") == 0 || url.indexOf("/web") == 0 || url.indexOf("/cb") == 0) {
ctx.service.utils.log('INFO', `[${ctx.request.url}] [${ctx.logcode}] request: ${JSON.stringify(ctx.request.body)}`);
await next();
ctx.service.utils.log('INFO', `[${ctx.request.url}] [${ctx.logcode}] res: ${JSON.stringify(ctx.body)}`)
return;
}
if (options.threshold && ctx.length < options.threshold) return;
const reqBody = ctx.request.body;
const reqHeader = ctx.request.header;
console.log(ctx.app.config.decodeParm)
if (ctx.app.config.decodeParm == false) {
await next();
return;
}
if (!reqBody.data) return;
const k = typeof reqHeader['k'] === 'string' ? reqHeader['k'] : reqHeader['k'][0];
const v = typeof reqHeader['v'] === 'string' ? reqHeader['v'] : reqHeader['v'][0];
let msgEncrypt = new MsgEncrypt({ encodeK: k, encodeV: v });
console.log(`encode str ${msgEncrypt.encryptMsg(reqBody)}`);
try {
let decryptResult = msgEncrypt.decryptMsg(reqBody.data);
if (!decryptResult) throw new Error('params parse err');
ctx.request.body = decryptResult;
console.log('req body', ctx.request.body);
ctx.service.utils.log('INFO', `[${ctx.request.url}] [${ctx.logcode}] request: ${JSON.stringify(ctx.request.body)}`)
} catch (e) {
console.error('parms parse err');
ctx.service.utils.log('ERROR', `[${ctx.request.url}] [${ctx.logcode}] request: parms parse err`)
}
try {
await next();
} catch (e) {
ctx.service.utils.log('ERROR', `[${ctx.request.url}] [${ctx.logcode}] err: ${(<Error>e).stack}`);
throw e;
}
const resBody = ctx.body;
console.log('return value:', JSON.stringify(resBody));
let resBodyWithEncrypt = msgEncrypt.encryptMsg(resBody);
if (resBodyWithEncrypt) {
ctx.body = { result: resBodyWithEncrypt };
ctx.service.utils.log('INFO', `[${ctx.request.url}] [${ctx.logcode}] res: ${JSON.stringify(resBody)}`)
} else {
ctx.body = { result: msgEncrypt.encryptMsg({ status: 3, data: 'internal err' }) };
ctx.service.utils.log('ERROR', `[${ctx.request.url}] [${ctx.logcode}] res: ${resBody}`)
}
};
};