liufumingren b2eea28001 feat(微信网关): 扫码登录 / 绑定微信 / 工作台扫码登入,废弃自建登录码
对接 https://gateway.gztbyc.com:二维码与「扫码确认」由网关提供,本服务只负责
申请临时码 → 验签收通知 → 落地自己的业务。

- 新增 service/wx_gateway.js + controller/gateway/notify.js(POST /api/wechat-gateway/notify,验签 401 / 会话过期 200 ignored)
- 新增 controller/web/wx_gateway.js(登录二维码 / 长轮询 / SVG+GIF / 个人中心绑定与解绑)
- 新表 wechat_gateway_bindings(uk(app_key, openid)):一个微信只绑一个账号,解绑是软删,
  再绑定走 restore 复用(否则会撞唯一键报 Validation error)
- 「这个微信已绑别的账号」策略:原账号正常 → 拒绝并提示对方账号名;原账号禁用/已删 → 直接改绑;
  拿不到原账号 → 运维接口 GET/DELETE /api/internal/wechat-bindings 强制解绑
- 主体成员改为「扫码绑定」:管理员出二维码 → 成员微信扫码 → 已有账号直接继承(自动建的临时账号删掉),
  没有账号则由服务端建号并绑成其登录方式;subject_members.temp_user_id 记录临时账号
- 废弃自建登录码:删除 GET /api/wechat/login(6 位串码)与 workstations.login_code(迁移 20261028121000),
  工作台改扫码登入,成员绑定码与 /wechat?bind= 手机确认页下线
- 前端:登录页/个人中心/主体成员/工作台全部切到网关;桌面端登录窗改网关二维码 + 长轮询
- 测试:wx-gateway.test.js 覆盖登录/绑定/解绑-再绑/禁用账号改绑/运维强制解绑/成员绑定/工作台登入

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-29 17:20:05 +08:00

205 lines
6.6 KiB
JavaScript
Raw Permalink 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 用户端:微信登录网关(扫码登录 / 绑定微信)
*
* 取代了旧的「自建 6 位登录码」:二维码内容由网关下发(`pageUrl`),
* 用户扫码确认后网关回调本服务,本服务把结果放回会话,浏览器长轮询取走。
*
* - `POST /api/web/auth/wechat-gateway/qrcode`(公开)申请登录二维码 → `{ state, qrUrl, pageUrl, expiresIn }`
* - `GET /api/web/auth/wechat-gateway/login`(公开)长轮询:`?state=&wait=` → `{ status, token?, user? }`
* - `GET /api/wechat-gateway/qrcode.svg|gif`(公开)把会话里的网关地址画成二维码(本地生成,零外链)
* - `POST /api/web/me/wechat/qrcode`(需令牌)申请「绑定微信」二维码
* - `GET /api/web/me/wechat/status`(需令牌)长轮询绑定结果
* - `GET /api/web/me/wechat/bindings`(需令牌)当前账号已绑定的微信
* - `DELETE /api/web/me/wechat/bindings/:id`(需令牌)解绑
*/
class WebWxGatewayController extends Controller {
/**
* 没配网关时返回 503 + 明确提示
*
* ⚠️ 5xx 的 `ctx.throw` 会被统一错误处理遮成「服务器内部错误」,前端就拿不到原因了,
* 所以这里直接写 body。
*/
ensureEnabled() {
if (this.ctx.service.wxGateway.enabled) return true;
this.ctx.status = 503;
this.ctx.body = { ok: false, message: '未开通微信扫码登录(服务端未配置微信登录网关)' };
return false;
}
/**
* POST /api/web/auth/wechat-gateway/qrcode —— 申请登录二维码
*
* 没配网关时返回 503(前端据此提示「未开通微信扫码登录」)。
*/
async createLoginQr() {
const { ctx } = this;
if (!this.ensureEnabled()) return;
const session = await ctx.service.wxGateway.openSession({
purpose: 'login',
scene: 'login',
});
ctx.body = {
ok: true,
data: {
state: session.state,
pageUrl: session.pageUrl,
qrUrl: `/api/wechat-gateway/qrcode.svg?state=${encodeURIComponent(session.state)}`,
expiresIn: session.expiresIn,
},
};
}
/**
* GET /api/web/auth/wechat-gateway/login?state=&wait= —— 长轮询登录结果
*
* 确认后当场签发用户 JWT(令牌不落 Redis,只经过这一次响应):
* `{ status:'confirmed', token, tokenType, expiresIn, user }`
*/
async loginStatus() {
const { ctx } = this;
const result = await ctx.service.wxGateway.awaitSession(String(ctx.query.state || ''), {
wait: ctx.query.wait,
});
if (result.status === 'aborted') {
// 客户端已经断开(切回账号密码登录 / 关页签):不用写响应
ctx.respond = false;
return;
}
if (result.status !== 'confirmed') {
ctx.body = { ok: true, data: result };
return;
}
const user = await ctx.service.user.findById(Number(result.userId));
if (!user) {
ctx.body = { ok: true, data: { status: 'failed', message: '绑定的平台账号不存在,请联系管理员' } };
return;
}
ctx.logger.info('[wx-gateway] %s 扫码登录成功(API)', user.username);
ctx.body = {
ok: true,
data: {
status: 'confirmed',
token: ctx.service.jwt.signUser(user),
tokenType: 'Bearer',
expiresIn: ctx.app.config.jwt.userExpiresIn,
user: {
id: user.id,
username: user.username,
nickname: user.nickname || null,
email: user.email || null,
phone: user.phone || null,
avatar: user.avatar || null,
},
},
};
}
/** GET /api/wechat-gateway/qrcode.svg?state= —— 二维码 SVG(本地画,不引用任何外链) */
async qrSvg() {
const { ctx } = this;
const content = await this.contentOfState(String(ctx.query.state || ''));
if (!content) ctx.throw(404, '二维码已失效,请刷新');
ctx.set('Cache-Control', 'no-store');
ctx.type = 'image/svg+xml; charset=utf-8';
ctx.body = ctx.service.wechatLogin.qrSvg(content);
}
/** GET /api/wechat-gateway/qrcode.gif?state= —— 同一张二维码的 GIF(桌面端 WPF 不能渲染 SVG) */
async qrGif() {
const { ctx } = this;
const content = await this.contentOfState(String(ctx.query.state || ''));
if (!content) ctx.throw(404, '二维码已失效,请刷新');
ctx.set('Cache-Control', 'no-store');
ctx.type = 'image/gif';
ctx.body = ctx.service.wechatLogin.qrGif(content);
}
/** POST /api/web/me/wechat/qrcode —— 申请「绑定微信」二维码(绑定到当前账号) */
async createBindQr() {
const { ctx } = this;
if (!this.ensureEnabled()) return;
const session = await ctx.service.wxGateway.openSession({
purpose: 'bind',
scene: 'bind',
payload: { userId: Number(ctx.state.user.id) },
});
ctx.body = {
ok: true,
data: {
state: session.state,
pageUrl: session.pageUrl,
qrUrl: `/api/wechat-gateway/qrcode.svg?state=${encodeURIComponent(session.state)}`,
expiresIn: session.expiresIn,
},
};
}
/** GET /api/web/me/wechat/status?state=&wait= —— 长轮询绑定结果 */
async bindStatus() {
const { ctx } = this;
const result = await ctx.service.wxGateway.awaitSession(String(ctx.query.state || ''), {
wait: ctx.query.wait,
});
if (result.status === 'aborted') {
ctx.respond = false;
return;
}
ctx.body = { ok: true, data: result };
}
/** GET /api/web/me/wechat/bindings —— 当前账号已绑定的微信 */
async bindings() {
const { ctx } = this;
const list = await ctx.service.wxGateway.listBindings(ctx.state.user.id);
ctx.body = {
ok: true,
data: {
list,
// 没配网关时前端把「绑定微信」整块灰掉(而不是点了才报错)
enabled: ctx.service.wxGateway.enabled,
},
};
}
/** DELETE /api/web/me/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.wxGateway.unbind(ctx.state.user.id, id);
ctx.body = { ok: true, data };
}
/** 会话里的二维码内容(网关授权页地址);会话没了返回空串 */
async contentOfState(state) {
if (!state) return '';
return this.ctx.service.wxGateway.pageUrlOf(state);
}
}
module.exports = WebWxGatewayController;