liufumingren 4f637f1307 feat(web): 微信小程序 code2Session 登录与账号绑定
- POST /api/web/auth/wechat/login:code 换 openid,已绑定直接签发令牌,
  未绑定自动建平台账号(首登标记 firstTime)
- bind / bindings / unbind:登录态下绑定、查询、解绑小程序账号
- wechat_mp_accounts 表 + 迁移;未配置 WX_MP_APPID/SECRET 时本地与单测走 mock
- 新增 cors 中间件(小程序 H5 预览直连后端;鉴权只靠 header 令牌,不依赖 cookie)
- 补充 wechat-mp 接口单测

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-21 00:47:11 +08:00

55 lines
2.0 KiB
JavaScript
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.

'use strict';
/**
* 跨域(CORS)
*
* 为什么需要:小程序 H5 预览(7304)与前端 SPA 一样用浏览器发起请求,
* 但接口现在**统一走后端绝对地址**(不再经 Vite 同源代理),所以后端必须回 CORS 头。
* 小程序真机 / 桌面端 / 扩展走的是原生请求,不受同源策略限制,这段对它们没有影响。
*
* 配置(`config.cors`):
* - `origins`: `'*'`(默认)或逗号分隔白名单(env `CORS_ORIGINS`),白名单外返回不带 CORS 头;
* - `enable: false` 可整体关闭。
*
* 说明:鉴权只用 header 里的令牌(Authorization / X-Subject-Id),**不依赖 cookie**,
* 所以不需要 `Access-Control-Allow-Credentials`。
*/
module.exports = () => {
return async function cors(ctx, next) {
const cfg = ctx.app.config.cors || {};
if (cfg.enable !== false) {
const origin = ctx.get('origin');
const allowed = pickOrigin(origin, cfg.origins);
if (allowed) {
ctx.set('Access-Control-Allow-Origin', allowed);
ctx.set('Vary', 'Origin');
ctx.set('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');
ctx.set(
'Access-Control-Allow-Headers',
'Authorization,Content-Type,X-Subject-Id,X-Access-Token,X-Internal-Token,X-Scanner-Token,X-Pay-Sign',
);
ctx.set('Access-Control-Max-Age', '86400');
ctx.set('Access-Control-Expose-Headers', 'Content-Disposition');
}
}
// 预检请求直接结束(后续路由没有 OPTIONS,否则会 404 让浏览器判成跨域失败)
if (ctx.method === 'OPTIONS') {
ctx.status = 204;
return;
}
await next();
};
};
/** 命中白名单返回要回填的 Origin;`*` 时回显实际 Origin(没有 Origin 就不加头) */
function pickOrigin(origin, origins) {
if (!origin) return '';
const list = Array.isArray(origins) ? origins : [];
if (list.includes('*')) return '*';
return list.includes(origin) ? origin : '';
}