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

84 lines
2.7 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';
const { Controller } = require('egg');
/** 路径参数转正整数,非法返回 null */
function toId(value) {
const id = Number(value);
return Number.isInteger(id) && id > 0 ? id : null;
}
/**
* web 用户端:微信小程序登录 / 绑定
*
* - `POST /api/web/auth/wechat/login`(公开):`uni.login()` 的 code 换 openid,
* 未绑定就自动建账号;小程序客户端同样要先同意协议(与账号密码登录一致)
* - `POST /api/web/auth/wechat/bind`(需令牌):把微信绑到当前账号
* - `GET /api/web/auth/wechat/bindings`(需令牌):当前账号的微信绑定
* - `DELETE /api/web/auth/wechat/bindings/:id`(需令牌):解绑
*/
class WebWechatMpController extends Controller {
/**
* POST /api/web/auth/wechat/login
* body: `{ code, userInfo?: { nickname, avatar }, client?, agreements? }`
* → `{ token, tokenType, expiresIn, user, subjects, firstTime, wechat, agreements? }`
*/
async login() {
const { ctx } = this;
const body = ctx.request.body || {};
const client = ctx.service.login.normalizeClient(body.client) || 'mini_program';
let accepted = null;
if (ctx.service.login.shouldEnforceAgreement(client)) {
accepted = await ctx.service.login.requireAgreements(body.agreements);
if (!accepted) return;
}
const result = await ctx.service.wechatMp.login({
code: body.code,
userInfo: body.userInfo,
});
const data = await ctx.service.login.issue(result.user);
data.firstTime = result.firstTime;
data.wechat = result.binding;
if (accepted) {
data.agreements = await ctx.service.login.recordAgreements(result.user, accepted, client);
}
ctx.body = { ok: true, data };
}
/**
* POST /api/web/auth/wechat/bind
* body: `{ code, userInfo? }` → 绑定详情
*/
async bind() {
const { ctx } = this;
const body = ctx.request.body || {};
const data = await ctx.service.wechatMp.bind(ctx.state.user.id, {
code: body.code,
userInfo: body.userInfo,
});
ctx.body = { ok: true, data };
}
/** GET /api/web/auth/wechat/bindings —— 当前账号的微信绑定 */
async bindings() {
const { ctx } = this;
const list = await ctx.service.wechatMp.listByUser(ctx.state.user.id);
ctx.body = { ok: true, data: { list } };
}
/** DELETE /api/web/auth/wechat/bindings/:id —— 解绑 */
async unbind() {
const { ctx } = this;
const id = toId(ctx.params.id);
if (!id) ctx.throw(400, 'id 必须是正整数');
const data = await ctx.service.wechatMp.unbind(ctx.state.user.id, id);
ctx.body = { ok: true, data };
}
}
module.exports = WebWechatMpController;