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>
This commit is contained in:
parent
f8aa4c4899
commit
b2eea28001
@ -1,66 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
|
||||
/**
|
||||
* 成员绑定(手机扫码侧)
|
||||
*
|
||||
* 流程与扫码登录一个套路:
|
||||
* 1. 电脑端 `POST /api/web/subjects/:id/members/:memberId/bind-code` 生成 6 位码 → 画二维码
|
||||
* 2. 手机扫码打开前端 `/wechat?bind=<码>`
|
||||
* 3. 手机侧轮询 `GET /api/subject/member-bind?code=`(公开)拿状态
|
||||
* 4. 已登录的账号点「确认绑定」→ `POST /api/subject/member-bind/confirm`(要 user JWT)
|
||||
* → 该账号被写进 `subject_members.user_id`,从此可以进入这个主体
|
||||
*/
|
||||
class MemberBindController extends Controller {
|
||||
/** GET /api/subject/member-bind?code=ABC123 —— 绑定码状态(公开) */
|
||||
async status() {
|
||||
const { ctx } = this;
|
||||
const code = String(ctx.query.code || '').trim();
|
||||
|
||||
if (!code) {
|
||||
ctx.status = 422;
|
||||
ctx.body = { ok: false, status: 'bad_format', message: '缺少绑定码' };
|
||||
return;
|
||||
}
|
||||
if (!/^[0-9A-Z]{4,12}$/i.test(code)) {
|
||||
ctx.status = 422;
|
||||
ctx.body = { ok: false, status: 'bad_format', message: '绑定码格式不对' };
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await ctx.service.subject.bindStatus(code);
|
||||
ctx.status = result.status === 'expired' ? 410 : 200;
|
||||
ctx.body = { ok: true, data: result };
|
||||
}
|
||||
|
||||
/** POST /api/subject/member-bind/confirm —— body { code },把当前登录账号绑到该成员 */
|
||||
async confirm() {
|
||||
const { ctx } = this;
|
||||
const body = ctx.request.body || {};
|
||||
const code = String(body.code || ctx.query.code || '').trim();
|
||||
|
||||
if (!code) ctx.throw(422, '缺少绑定码');
|
||||
|
||||
const user = ctx.state.user;
|
||||
const result = await ctx.service.subject.confirmBind(code, user.id);
|
||||
if (!result.ok) {
|
||||
const mapping = {
|
||||
bad_param: 422,
|
||||
expired: 410,
|
||||
used: 410,
|
||||
bound: 409,
|
||||
joined: 409,
|
||||
};
|
||||
ctx.status = mapping[result.reason] || 400;
|
||||
ctx.body = { ok: false, status: result.reason, message: result.message };
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.logger.info('[subject] %s 扫码确认成为主体 %s 的成员「%s」',
|
||||
user.username || user.id, result.subjectId, result.memberName);
|
||||
ctx.body = { ok: true, data: result };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = MemberBindController;
|
||||
@ -5,155 +5,29 @@ const { Controller } = require('egg');
|
||||
/**
|
||||
* 扫码登录的**公开**接口(发码 / 查码)—— 谁来调都行,不需要令牌
|
||||
*
|
||||
* 面向:登录页(浏览器内联脚本)、Win 客户端、任何想自己画二维码显示的前端。
|
||||
* 面向:Win 客户端、设备端、任何想自己画二维码显示的前端。
|
||||
* 确认环节在 `app/controller/client/wechat.js`(需要 user JWT);设备端扫码登录在 `app/controller/device/auth.js`。
|
||||
*
|
||||
* ⚠️ 登录页扫码登录、主体成员绑定、个人中心绑定微信都已改走微信登录网关(`/api/wechat-gateway/*`),
|
||||
* 这里只剩「设备扫码登录」在用(手机页 `/wechat?spm=…` 点确认)。
|
||||
*/
|
||||
class WechatAuthController extends Controller {
|
||||
/**
|
||||
* GET /api/wechat/qrcode.svg?code=xxxxxx —— 登录码的二维码(SVG,**本地生成**,零外链)
|
||||
*
|
||||
* - 默认:内容是本站在址 `/wechat?spm=1.0.<码>.1`(扫码登录)
|
||||
* - `?mode=member`:内容是 `/wechat?bind=<码>`(主体成员绑定码,同一个扫码页、不同处理逻辑)
|
||||
* 内容是本站地址 `/wechat?spm=1.0.<码>.1`(设备扫码登录的手机页)。
|
||||
*/
|
||||
async qrcode() {
|
||||
const { ctx } = this;
|
||||
const code = String(ctx.query.code || '');
|
||||
const origin = ctx.app.config.email.siteUrl || ctx.origin;
|
||||
const content = String(ctx.query.mode || '') === 'member'
|
||||
? `${String(origin).replace(/\/+$/, '')}/wechat?bind=${encodeURIComponent(code)}`
|
||||
: ctx.service.wechatLogin.qrContent({ code, origin });
|
||||
const content = ctx.service.wechatLogin.qrContent({ code, origin });
|
||||
|
||||
ctx.set('Cache-Control', 'no-store');
|
||||
ctx.type = 'image/svg+xml; charset=utf-8';
|
||||
ctx.body = ctx.service.wechatLogin.qrSvg(content);
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/wechat/qrcode.gif?code=xxxxxx&mode=member —— 二维码的 **GIF** 版
|
||||
*
|
||||
* 桌面端(WPF)没法渲染 SVG,只能直接拉位图;内容和 `qrcode.svg` 完全一致。
|
||||
*/
|
||||
async qrcodeGif() {
|
||||
const { ctx } = this;
|
||||
const code = String(ctx.query.code || '');
|
||||
const origin = ctx.app.config.email.siteUrl || ctx.origin;
|
||||
const content = String(ctx.query.mode || '') === 'member'
|
||||
? `${String(origin).replace(/\/+$/, '')}/wechat?bind=${encodeURIComponent(code)}`
|
||||
: ctx.service.wechatLogin.qrContent({ code, origin });
|
||||
|
||||
ctx.set('Cache-Control', 'no-store');
|
||||
ctx.type = 'image/gif';
|
||||
ctx.body = ctx.service.wechatLogin.qrGif(content);
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/wechat/login —— 扫码登录接口(前端 JS/SPA 用,不依赖页面渲染)
|
||||
* - **不带参数**:生成一个 6 位串码(数字+字母,存 Redis)并返回二维码地址,前端拿去画二维码;
|
||||
* - **带 `?code=`**:轮询状态;手机确认后:**写入登录会话 + 返回用户 JWT**,前端存下 JWT 即完成登录。
|
||||
*/
|
||||
async login() {
|
||||
const { ctx } = this;
|
||||
const svc = ctx.service.wechatLogin;
|
||||
const raw = String(ctx.query.code || '').trim();
|
||||
|
||||
if (!raw) {
|
||||
const code = await svc.newCode();
|
||||
ctx.body = {
|
||||
ok: true,
|
||||
data: {
|
||||
code,
|
||||
spm: svc.spm(code),
|
||||
qrUrl: `/api/wechat/qrcode.svg?code=${encodeURIComponent(code)}`,
|
||||
expiresIn: svc.stateTtl,
|
||||
},
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
const code = raw.toUpperCase();
|
||||
const expect = Number(ctx.app.config.wechat.codeLength || 6);
|
||||
if (!new RegExp(`^[0-9A-Z]{${expect}}$`).test(code)) {
|
||||
ctx.status = 422;
|
||||
ctx.body = { ok: false, message: `code 格式不对(${expect} 位数字 + 字母)` };
|
||||
return;
|
||||
}
|
||||
|
||||
// ?wait=25 走长轮询(最多挂起到 config.wechat.pollWait):有人登录立即返回,
|
||||
// 到时间还没动静就直接给一张新码(status=refreshed),前端换二维码后继续请求
|
||||
const result = await svc.awaitLogin(code, { wait: ctx.query.wait });
|
||||
|
||||
if (result.status === 'aborted') {
|
||||
// 客户端已经断开(切回账号密码登录 / 关页签 / 前端 abort):没什么可回的,也不用写响应
|
||||
ctx.respond = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.status === 'refreshed') {
|
||||
ctx.body = {
|
||||
ok: true,
|
||||
data: {
|
||||
status: 'refreshed',
|
||||
code: result.code,
|
||||
spm: svc.spm(result.code),
|
||||
qrUrl: `/api/wechat/qrcode.svg?code=${encodeURIComponent(result.code)}`,
|
||||
expiresIn: svc.stateTtl,
|
||||
waited: result.waited || 0,
|
||||
},
|
||||
};
|
||||
return;
|
||||
}
|
||||
if (result.status !== 'confirmed') {
|
||||
ctx.body = { ok: true, data: { status: result.status } };
|
||||
return;
|
||||
}
|
||||
|
||||
// 手机已确认:后端只下发 JWT(前端存本地),**不写 cookie/session**
|
||||
const user = result.user;
|
||||
ctx.logger.info('[wechat] %s 扫码登录成功(API)', user.username);
|
||||
|
||||
ctx.body = {
|
||||
ok: true,
|
||||
data: {
|
||||
status: 'confirmed',
|
||||
token: result.token,
|
||||
tokenType: result.tokenType,
|
||||
expiresIn: result.expiresIn,
|
||||
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/callback?code=&state= —— 微信公众号网页授权回调
|
||||
*
|
||||
* 微信把**手机浏览器**重定向到这里(回调地址可在微信平台配 `WECHAT_REDIRECT_URI`,
|
||||
* 不配就用 `<origin>/api/wechat/callback`)。这里不登录扫码设备,只把「已确认的用户 id」
|
||||
* 写进 Redis,等电脑上的登录页长轮询取走;处理完把浏览器转回**前端**的 `/wechat` 路由,
|
||||
* 由前端给出“已确认/失败”的文案。
|
||||
*/
|
||||
async callback() {
|
||||
const { ctx } = this;
|
||||
const state = String(ctx.query.state || '');
|
||||
const result = await ctx.service.wechatLogin.login(String(ctx.query.code || ''), state);
|
||||
|
||||
if (!result.ok) ctx.logger.warn('[wechat] 扫码失败: %s', result.message);
|
||||
|
||||
const spm = ctx.service.wechatLogin.parseSpm(state) ? ctx.service.wechatLogin.spm(state) : '';
|
||||
const base = String(ctx.app.config.email.siteUrl || ctx.origin || '').replace(/\/+$/, '');
|
||||
const query = new URLSearchParams({ ok: result.ok ? '1' : '0' });
|
||||
if (spm) query.set('spm', spm);
|
||||
if (!result.ok) query.set('message', result.message || '扫码失败,请重新扫码');
|
||||
|
||||
ctx.redirect(`${base}/wechat?${query.toString()}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/wechat/status —— 查串码状态(**无需登录**,小程序/网页先问一下再决定怎么提示)
|
||||
*
|
||||
|
||||
@ -92,13 +92,13 @@ class DeviceController extends Controller {
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/device/login —— 设备专用「扫码登录 + 注册/绑定」(参考 `GET /api/wechat/login`,区别是下发**长期** JWT)
|
||||
* GET /api/device/login —— 设备专用「扫码登录 + 注册/绑定」(扫码确认,区别是下发**长期** JWT)
|
||||
*
|
||||
* 设备信息(`?sn=` 设备序列号、`name` / `vendor` / `model` / `firmware`)**都是可选的**:
|
||||
* **发码时带上最省事**(服务端会暂存,确认/换码时沿用),轮询时再带上(补齐/覆盖)也行;
|
||||
* 不带 SN 时服务端在注册那一步生成一个(`DEV-…`)并返回给设备保存。
|
||||
*
|
||||
* 三种用法(**不需要任何凭据**,与 `GET /api/wechat/login` 一样是公开接口):
|
||||
* 三种用法(**不需要任何凭据**,公开接口):
|
||||
* 1. **不带 `code`**:发一张新登录码(登记为 pending)→ `{ status:'pending', expiresIn, code, spm,
|
||||
* origin, qrContent, qrImageUrl, qrUrl, device:{ sn, name } }`;**此时还没有注册任何东西**;
|
||||
* 2. **带 `code=&wait=N`**:**长轮询**(挂起最多 `WECHAT_POLL_WAIT` 秒,默认 60)——
|
||||
|
||||
42
backend/app/controller/gateway/notify.js
Normal file
42
backend/app/controller/gateway/notify.js
Normal file
@ -0,0 +1,42 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
|
||||
/**
|
||||
* 微信登录网关回调(**公开接口**,靠签名鉴权)
|
||||
*
|
||||
* 网关在用户微信里确认后 `POST` 到这里(地址在网关管理台配成「服务端通知地址」,
|
||||
* 对应 `config.wxGateway.notifyPath`)。请求体带 `sign` / `timestamp` / `nonce`,
|
||||
* 用 `sha256(appSecret)` 当密钥做 HMAC-SHA256,见 `service/wx_gateway.js#verifyNotify`。
|
||||
*
|
||||
* ⚠️ 网关只看 HTTP 状态码:**2xx 视为成功**,失败会重试 1 次。
|
||||
* 真正给浏览器/设备看的结果,通过本地会话(Redis)交给正在长轮询的那个请求。
|
||||
*/
|
||||
class GatewayNotifyController extends Controller {
|
||||
/** POST /api/wechat-gateway/notify */
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const svc = ctx.service.wxGateway;
|
||||
|
||||
if (!svc.enabled) {
|
||||
ctx.status = 503;
|
||||
ctx.body = { ok: false, message: '未配置微信登录网关' };
|
||||
return;
|
||||
}
|
||||
|
||||
const body = ctx.request.body || {};
|
||||
const checked = svc.verifyNotify(body);
|
||||
if (!checked.ok) {
|
||||
ctx.logger.warn('[wx-gateway] 通知验签失败:%s(event=%s state=%s)', checked.message, body.event, body.state);
|
||||
ctx.status = 401;
|
||||
ctx.body = { ok: false, message: checked.message };
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await svc.handleNotify(body);
|
||||
ctx.logger.info('[wx-gateway] 通知已处理:event=%s state=%s → %j', body.event, body.state, data);
|
||||
ctx.body = { ok: true, data };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = GatewayNotifyController;
|
||||
@ -3,58 +3,43 @@
|
||||
const { Controller } = require('egg');
|
||||
|
||||
/**
|
||||
* 运维/内部:微信授权(绑定关系)的读写
|
||||
* 运维/内部:微信绑定关系(微信登录网关)的查询与强制解绑
|
||||
*
|
||||
* 挂在 `middleware.internalAuth()` 后面(见 app/middleware/internal_auth.js)。
|
||||
*
|
||||
* 用户侧的扫码确认在 `app/controller/client/wechat.js`,公开的发码/查码在 `app/controller/auth/wechat.js`。
|
||||
* 用户侧的绑定/解绑在 `app/controller/web/wx_gateway.js`;
|
||||
* 网关回调在 `app/controller/gateway/notify.js`。
|
||||
*/
|
||||
class InternalWechatController extends Controller {
|
||||
/** GET /api/users/:id/wechats —— 某用户的全部微信授权 */
|
||||
async indexByUser() {
|
||||
/**
|
||||
* GET /api/internal/wechat-bindings?openid=&userId= —— 微信登录网关的绑定关系(**含已解绑的**)
|
||||
*
|
||||
* 排查「这个微信绑在谁身上 / 为什么绑不了」用;返回里带账号状态(禁用、已删除)。
|
||||
*/
|
||||
async bindings() {
|
||||
const { ctx } = this;
|
||||
const userId = Number(ctx.params.id);
|
||||
if (!Number.isInteger(userId) || userId <= 0) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { ok: false, message: 'id 必须是正整数' };
|
||||
const openid = String(ctx.query.openid || '').trim();
|
||||
const userId = Number(ctx.query.userId || 0);
|
||||
|
||||
if (!openid && !userId) {
|
||||
ctx.status = 422;
|
||||
ctx.body = { ok: false, message: 'openid 或 userId 至少要有一个' };
|
||||
return;
|
||||
}
|
||||
|
||||
const list = await ctx.service.wechat.listByUser(userId);
|
||||
const list = await ctx.service.wxGateway.listBindingsForOps({
|
||||
openid: openid || undefined,
|
||||
userId: userId || undefined,
|
||||
});
|
||||
ctx.body = { ok: true, data: { list, total: list.length } };
|
||||
}
|
||||
|
||||
/** GET /api/wechat/:appid/:openid —— 按 appid + openid 反查授权与用户 */
|
||||
async show() {
|
||||
const { ctx } = this;
|
||||
const { appid, openid } = ctx.params;
|
||||
const data = await ctx.service.wechat.findByOpenid(appid, openid);
|
||||
if (!data) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { ok: false, message: '授权记录不存在' };
|
||||
return;
|
||||
}
|
||||
ctx.body = { ok: true, data };
|
||||
}
|
||||
|
||||
/** POST /api/wechat/bind —— 绑定(已存在则更新) */
|
||||
async bind() {
|
||||
const { ctx } = this;
|
||||
const { userId, appid, openid } = ctx.request.body || {};
|
||||
|
||||
if (!userId || !appid || !openid) {
|
||||
ctx.status = 422;
|
||||
ctx.body = { ok: false, message: 'userId、appid、openid 均为必填' };
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await ctx.service.wechat.bind(ctx.request.body);
|
||||
ctx.status = 201;
|
||||
ctx.body = { ok: true, data };
|
||||
}
|
||||
|
||||
/** PUT /api/wechat/:id/tokens —— 更新 session_key / 令牌 */
|
||||
async updateTokens() {
|
||||
/**
|
||||
* DELETE /api/internal/wechat-bindings/:id —— **强制解绑**(不校验归属)
|
||||
*
|
||||
* 给「微信绑在前员工/已停用账号上,本人又拿不到那个账号」兜底;解绑后该微信可以重新绑给别人。
|
||||
*/
|
||||
async unbindBinding() {
|
||||
const { ctx } = this;
|
||||
const id = Number(ctx.params.id);
|
||||
if (!Number.isInteger(id) || id <= 0) {
|
||||
@ -63,32 +48,7 @@ class InternalWechatController extends Controller {
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await ctx.service.wechat.updateTokens(id, ctx.request.body || {});
|
||||
if (!data) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { ok: false, message: '授权记录不存在' };
|
||||
return;
|
||||
}
|
||||
ctx.body = { ok: true, data };
|
||||
}
|
||||
|
||||
/** DELETE /api/wechat/:id —— 解绑 */
|
||||
async unbind() {
|
||||
const { ctx } = this;
|
||||
const id = Number(ctx.params.id);
|
||||
if (!Number.isInteger(id) || id <= 0) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { ok: false, message: 'id 必须是正整数' };
|
||||
return;
|
||||
}
|
||||
|
||||
const removed = await ctx.service.wechat.unbind(id);
|
||||
if (!removed) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { ok: false, message: '授权记录不存在' };
|
||||
return;
|
||||
}
|
||||
ctx.body = { ok: true, data: { id } };
|
||||
ctx.body = { ok: true, data: await ctx.service.wxGateway.forceUnbind(id) };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -17,8 +17,8 @@ function toId(value) {
|
||||
* 关键规则:
|
||||
* - 创建主体:管理员 = 创建人,使用期限默认赠送 7 天(`config.subject.trialDays`)
|
||||
* - 主体列表:只返回「我是成员」的主体(含角色、成员数、是否过期)
|
||||
* - 成员:可按姓名快速创建(尚未绑定账号),再用「绑定码」扫码绑定
|
||||
* - **成员管理(增 / 删 / 发绑定码 / 改角色)只有主体管理员能做**,普通成员只能看列表;
|
||||
* - 成员:可按姓名快速创建(尚未绑定账号),再用「扫码绑定」绑微信/账号
|
||||
* - **成员管理(增 / 删 / 扫码绑定 / 改角色)只有主体管理员能做**,普通成员只能看列表;
|
||||
* 一个主体可以有多个管理员(`subject_members.role=1`),创建者恒为管理员且不能降级
|
||||
*/
|
||||
class WebSubjectController extends Controller {
|
||||
@ -136,14 +136,73 @@ class WebSubjectController extends Controller {
|
||||
ctx.body = { ok: true, data };
|
||||
}
|
||||
|
||||
/** POST /api/web/subjects/:id/members/:memberId/bind-code —— 生成成员绑定码 */
|
||||
async memberBindCode() {
|
||||
/**
|
||||
* POST /api/web/subjects/:id/members/:memberId/bind-qr —— 生成「扫码绑定」二维码(微信登录网关)
|
||||
*
|
||||
* 返回 `{ memberId, memberName, state, pageUrl, qrUrl, expiresIn }`:前端把 `qrUrl` 当图片显示,
|
||||
* 再拿 `state` 去 `GET .../bind-qr/status` 长轮询结果。
|
||||
*/
|
||||
async memberBindQr() {
|
||||
const { ctx } = this;
|
||||
const id = toId(ctx.params.id);
|
||||
const memberId = toId(ctx.params.memberId);
|
||||
if (!id || !memberId) ctx.throw(400, 'id 必须是正整数');
|
||||
|
||||
const data = await ctx.service.subject.createBindCode({
|
||||
// 5xx 的 ctx.throw 会被统一错误处理遮成「服务器内部错误」,这里直接给明确提示
|
||||
if (!ctx.service.wxGateway.enabled) {
|
||||
ctx.status = 503;
|
||||
ctx.body = { ok: false, message: '未开通微信扫码绑定(服务端未配置微信登录网关)' };
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await ctx.service.subject.createBindQr({
|
||||
subjectId: id,
|
||||
memberId,
|
||||
operatorUserId: ctx.state.user.id,
|
||||
});
|
||||
ctx.body = { ok: true, data };
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/web/subjects/:id/members/:memberId/bind-qr/status?state=&wait= —— 长轮询绑定结果
|
||||
*
|
||||
* `data.status`:pending / confirmed(附 `memberName`、`boundName`、`autoCreated`)/ failed(附原因)/ expired
|
||||
*/
|
||||
async memberBindQrStatus() {
|
||||
const { ctx } = this;
|
||||
const id = toId(ctx.params.id);
|
||||
const memberId = toId(ctx.params.memberId);
|
||||
if (!id || !memberId) ctx.throw(400, 'id 必须是正整数');
|
||||
|
||||
// 仍然校验管理员身份:二维码能扫,但不是谁都能来看结果
|
||||
await ctx.service.subject.ensureAdmin(id, ctx.state.user.id);
|
||||
|
||||
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 };
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/web/subjects/:id/members/:memberId/unbind —— 解除成员的账号绑定(**仅管理员**)
|
||||
*
|
||||
* 绑错了 / 手机换人时用:解绑后成员回到「未绑定」,可以重新出二维码绑别人;
|
||||
* 自动建给成员的临时账号会一并删掉。
|
||||
*/
|
||||
async unbindMember() {
|
||||
const { ctx } = this;
|
||||
const id = toId(ctx.params.id);
|
||||
const memberId = toId(ctx.params.memberId);
|
||||
if (!id || !memberId) ctx.throw(400, 'id 必须是正整数');
|
||||
|
||||
const data = await ctx.service.subject.unbindMember({
|
||||
subjectId: id,
|
||||
memberId,
|
||||
operatorUserId: ctx.state.user.id,
|
||||
|
||||
204
backend/app/controller/web/wx_gateway.js
Normal file
204
backend/app/controller/web/wx_gateway.js
Normal file
@ -0,0 +1,204 @@
|
||||
'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;
|
||||
@ -6,7 +6,8 @@
|
||||
* 用法:`router.post('/api/xxx', middleware.apiAuth(), controller.xxx.yyy)`
|
||||
*
|
||||
* - 令牌:`Authorization: Bearer <user JWT>`(也认 `X-Access-Token`,方便不爱用 Authorization 的客户端)
|
||||
* JWT 由这些地方下发:扫码登录 `GET /api/wechat/login` 的 `data.token`、页面里现场签发的同款令牌;
|
||||
* JWT 由这些地方下发:账号密码登录 `/api/web/auth/login`、微信网关扫码登录
|
||||
* `/api/web/auth/wechat-gateway/login` 的 `data.token`、页面里现场签发的同款令牌;
|
||||
* - 不加 cookie、也不写 session:小程序 / App / SPA 这类没有浏览器 cookie 的客户端直接用它;
|
||||
* - 未带或验不过 → 401 `{ ok:false, status:'unauthorized', message }`;
|
||||
* 用户不存在/被禁用 → 403 `{ ok:false, status:'forbidden', message }`;
|
||||
|
||||
@ -5,7 +5,8 @@
|
||||
*
|
||||
* 一行 = 某主体下的一个成员:
|
||||
* - `name`:姓名(必填,创建成员时先只填姓名也行)
|
||||
* - `userId`:绑定的账号(可为空 —— 先建成员、之后用绑定码扫码绑定)
|
||||
* - `userId`:绑定的账号(可为空 —— 先建成员,之后用「扫码绑定」绑微信/账号)
|
||||
* - `tempUserId`:扫码绑定时**自动建给成员的账号**(被已有账号继承时删除)
|
||||
* - `role`:1 管理员 / 2 成员
|
||||
* - `wechatOpenid` / `boundAt`:扫码绑定微信后记录
|
||||
*
|
||||
@ -18,6 +19,7 @@ module.exports = (app) => {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
subjectId: { type: BIGINT.UNSIGNED, allowNull: false, comment: '主体 subjects.id' },
|
||||
userId: { type: BIGINT.UNSIGNED, comment: '绑定账号 users.id(未绑定为空)' },
|
||||
tempUserId: { type: BIGINT.UNSIGNED, comment: '自动建给成员的临时账号 users.id(被已有账号继承时删除)' },
|
||||
name: { type: STRING(32), allowNull: false, comment: '成员姓名' },
|
||||
role: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 2, comment: '角色:1管理员 2成员' },
|
||||
wechatOpenid: { type: STRING(64), comment: '绑定的微信 openid' },
|
||||
|
||||
35
backend/app/model/wechat_gateway_binding.js
Normal file
35
backend/app/model/wechat_gateway_binding.js
Normal file
@ -0,0 +1,35 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 微信登录网关绑定表(wechat_gateway_bindings)
|
||||
*
|
||||
* 一行 = 「某个网关应用下的一个 openid」 ↔ 「平台账号」的绑定关系。
|
||||
* 登录页扫码登录、工作台扫码登入都靠它把微信身份换成平台账号;
|
||||
* 解绑直接删行(历史登录记录在 `workstation_login_records` 里,不依赖这张表)。
|
||||
*
|
||||
* ⚠️ 一个 openid 只能绑一个平台账号(`uk_app_openid`),
|
||||
* 一个平台账号在同一应用下也只留一个微信(绑新的要先解绑,见 `service/wx_gateway.js`)。
|
||||
*/
|
||||
module.exports = (app) => {
|
||||
const { BIGINT, STRING, DATE } = app.Sequelize;
|
||||
|
||||
const WechatGatewayBinding = app.model.define('wechatGatewayBinding', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
userId: { type: BIGINT.UNSIGNED, allowNull: false, comment: '绑定的平台账号 users.id' },
|
||||
appKey: { type: STRING(64), allowNull: false, comment: '网关应用标识 appKey' },
|
||||
openid: { type: STRING(64), allowNull: false, comment: '网关返回的 openid' },
|
||||
unionid: { type: STRING(64), comment: '开放平台 unionid(网关没给就为空)' },
|
||||
bindScene: { type: STRING(16), allowNull: false, defaultValue: 'bind', comment: '绑定时用的场景:bind / login' },
|
||||
lastLoginAt: { type: DATE, comment: '最近一次用这个微信登录的时间' },
|
||||
}, {
|
||||
tableName: 'wechat_gateway_bindings',
|
||||
paranoid: true,
|
||||
comment: '微信登录网关绑定表',
|
||||
});
|
||||
|
||||
WechatGatewayBinding.associate = function() {
|
||||
app.model.WechatGatewayBinding.belongsTo(app.model.User, { foreignKey: 'user_id', as: 'user' });
|
||||
};
|
||||
|
||||
return WechatGatewayBinding;
|
||||
};
|
||||
@ -4,23 +4,9 @@ const { Service } = require('egg');
|
||||
const crypto = require('crypto');
|
||||
const { Op } = require('sequelize');
|
||||
|
||||
/** 绑定码字符集(去掉容易看错的 0/O/1/I) */
|
||||
const CODE_ALPHABET = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
|
||||
|
||||
/** 新建主体默认赠送天数(可通过 config.subject.trialDays 覆盖) */
|
||||
const DEFAULT_TRIAL_DAYS = 7;
|
||||
|
||||
/** 成员绑定码默认有效期(秒) */
|
||||
const BIND_TTL = 600;
|
||||
|
||||
function randomCode(length = 6) {
|
||||
let out = '';
|
||||
for (let i = 0; i < length; i++) {
|
||||
out += CODE_ALPHABET[crypto.randomInt(CODE_ALPHABET.length)];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const USER_ATTRIBUTES = [ 'id', 'username', 'nickname', 'avatar' ];
|
||||
|
||||
/**
|
||||
@ -29,7 +15,7 @@ const USER_ATTRIBUTES = [ 'id', 'username', 'nickname', 'avatar' ];
|
||||
* 职责:
|
||||
* - 主体列表 / 创建(默认赠送 N 天)/ 修改(管理员)
|
||||
* - 成员管理:列表、按姓名快速添加、删除
|
||||
* - 成员微信绑定码:发码 → 手机扫码 → 登录用户确认 → 绑定该成员
|
||||
* - 成员微信绑定:出网关二维码 → 手机微信扫码 → 绑到已有账号 / 自动建号
|
||||
* - 供中间件用的「当前用户是否属于该主体 / 主体是否过期」判断
|
||||
*/
|
||||
class SubjectService extends Service {
|
||||
@ -50,10 +36,6 @@ class SubjectService extends Service {
|
||||
return (this.app.config.cache && this.app.config.cache.prefix) || 'packs:';
|
||||
}
|
||||
|
||||
bindKey(code) {
|
||||
return `${this.prefix}member:bind:${code}`;
|
||||
}
|
||||
|
||||
/** 是否已过期(含稍后到期判断,统一用服务器时间) */
|
||||
isExpired(subject) {
|
||||
if (!subject || !subject.expireAt) return false;
|
||||
@ -69,7 +51,7 @@ class SubjectService extends Service {
|
||||
expireAt: subject.expireAt,
|
||||
status: Number(subject.status),
|
||||
remark: subject.remark || null,
|
||||
createdAt: subject.createdAt,
|
||||
createdAt: subject.createdAt || subject.created_at,
|
||||
expired: this.isExpired(subject),
|
||||
}, extra);
|
||||
}
|
||||
@ -268,7 +250,7 @@ class SubjectService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 按姓名快速添加成员(先只建成员,账号/微信稍后用绑定码绑定)
|
||||
* 按姓名快速添加成员(先只建成员,账号/微信稍后用「扫码绑定」绑定)
|
||||
*
|
||||
* **仅管理员**可操作(普通成员只能看成员列表)。
|
||||
* @param {object} params { subjectId, userId 操作人, name, role? }
|
||||
@ -314,7 +296,7 @@ class SubjectService extends Service {
|
||||
* 一个主体可以有多名管理员(`role=1`),`subjects.admin_user_id` 只是创建者,同样恒为管理员:
|
||||
* - 创建者不能降级(否则「创建者」与 `role` 两套判断会打架);
|
||||
* - 不能改自己的角色(避免管理员把自己降成成员后没人能管);
|
||||
* - 允许给**还没绑定账号**的成员设为管理员:等他用绑定码绑定后直接就是管理员。
|
||||
* - 允许给**还没绑定账号**的成员设为管理员:等他扫码绑定账号后直接就是管理员。
|
||||
*
|
||||
* @param {object} params { subjectId, operatorUserId, memberId, role }
|
||||
*/
|
||||
@ -386,148 +368,229 @@ class SubjectService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 给「未绑定账号/微信」的成员生成绑定码(**仅管理员**)
|
||||
* 给「未绑定账号/微信」的成员出一张扫码绑定二维码(**仅管理员**)
|
||||
*
|
||||
* 手机扫码后打开前端 `/wechat?bind=<码>`,已登录的账号点确认即可完成绑定。
|
||||
* @return {Promise<object>} { code, bindUrl, qrUrl, expiresIn }
|
||||
* 走微信登录网关(`scene=bind`):成员用手机微信扫码 → 网关回调后按两种情形落地:
|
||||
* - 这个微信**已经是某个平台账号**的登录方式 → 成员直接绑到那个账号(之前自动建的临时账号删掉);
|
||||
* - 这个微信**还没有平台账号** → 自动给这名成员建一个账号,并把微信绑成它的登录方式。
|
||||
*
|
||||
* @param {object} params { subjectId, memberId, operatorUserId }
|
||||
* @return {Promise<object>} { memberId, memberName, state, pageUrl, qrUrl, expiresIn }
|
||||
*/
|
||||
async createBindCode({ subjectId, memberId, operatorUserId } = {}) {
|
||||
const { subject } = await this.ensureAdmin(subjectId, operatorUserId);
|
||||
async createBindQr({ subjectId, memberId, operatorUserId } = {}) {
|
||||
await this.ensureAdmin(subjectId, operatorUserId);
|
||||
|
||||
const member = await this.Member.findOne({
|
||||
where: { id: Number(memberId), subjectId: Number(subjectId) },
|
||||
});
|
||||
if (!member) this.ctx.throw(404, '成员不存在');
|
||||
if (member.userId) this.ctx.throw(409, '该成员已绑定账号,如需换绑请先解绑');
|
||||
|
||||
const code = randomCode(6);
|
||||
const payload = JSON.stringify({
|
||||
status: 'pending',
|
||||
subjectId: Number(subjectId),
|
||||
subjectName: subject.name,
|
||||
memberId: Number(memberId),
|
||||
name: member.name,
|
||||
});
|
||||
await this.app.redis.setex(this.bindKey(code), BIND_TTL, payload);
|
||||
|
||||
const origin = this.app.config.email.siteUrl || this.ctx.origin;
|
||||
const bindUrl = `${String(origin).replace(/\/+$/, '')}/wechat?bind=${encodeURIComponent(code)}`;
|
||||
|
||||
return {
|
||||
code,
|
||||
memberId: Number(memberId),
|
||||
memberName: member.name,
|
||||
bindUrl,
|
||||
qrUrl: `/api/wechat/qrcode.svg?code=${encodeURIComponent(code)}&mode=member`,
|
||||
expiresIn: BIND_TTL,
|
||||
};
|
||||
}
|
||||
|
||||
/** 绑定码状态(扫码页轮询) */
|
||||
async bindStatus(code) {
|
||||
const normalized = String(code || '').trim().toUpperCase();
|
||||
if (!normalized) return { status: 'bad_format' };
|
||||
|
||||
const raw = await this.app.redis.get(this.bindKey(normalized));
|
||||
if (!raw) return { status: 'expired' };
|
||||
|
||||
let data = null;
|
||||
try {
|
||||
data = JSON.parse(raw);
|
||||
} catch (err) {
|
||||
return { status: 'expired' };
|
||||
// 已绑到「真实账号」就不能再扫码换绑;只挂着自动建的临时账号的,允许重新扫码
|
||||
if (member.userId && Number(member.userId) !== Number(member.tempUserId)) {
|
||||
this.ctx.throw(409, '该成员已绑定账号,如需换绑请先「解除绑定」');
|
||||
}
|
||||
|
||||
const session = await this.ctx.service.wxGateway.openSession({
|
||||
purpose: 'member',
|
||||
scene: 'bind',
|
||||
payload: { subjectId: Number(subjectId), memberId: Number(member.id) },
|
||||
});
|
||||
|
||||
return {
|
||||
status: data.status || 'pending',
|
||||
code: normalized,
|
||||
subjectId: data.subjectId,
|
||||
memberId: data.memberId,
|
||||
memberName: data.name,
|
||||
subjectName: data.subjectName,
|
||||
boundName: data.boundName,
|
||||
memberId: Number(member.id),
|
||||
memberName: member.name,
|
||||
state: session.state,
|
||||
pageUrl: session.pageUrl,
|
||||
qrUrl: `/api/wechat-gateway/qrcode.svg?state=${encodeURIComponent(session.state)}`,
|
||||
expiresIn: session.expiresIn,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 手机侧确认绑定:把当前登录账号绑到该成员上
|
||||
* 网关确认后:把「扫码的微信」落到这名成员上(`service/wx_gateway.js#handleMemberBind` 调)
|
||||
*
|
||||
* @param {string} code 绑定码
|
||||
* @param {number} userId 当前登录用户(手机端已登录)
|
||||
* @param {object} params
|
||||
* @param {number} params.subjectId
|
||||
* @param {number} params.memberId
|
||||
* @param {string} params.openid 扫码的微信
|
||||
* @param {string} [params.unionid]
|
||||
* @param {number|null} [params.boundUserId] 这个微信已经属于哪个平台账号(没有就 null)
|
||||
* @return {Promise<object>} { subjectId, subjectName, memberId, memberName, userId, boundName, autoCreated }
|
||||
*/
|
||||
async confirmBind(code, userId) {
|
||||
const normalized = String(code || '').trim().toUpperCase();
|
||||
if (!normalized || !userId) {
|
||||
return { ok: false, reason: 'bad_param', message: '参数不完整' };
|
||||
}
|
||||
async bindMemberWithWechat({ subjectId, memberId, openid, unionid = null, boundUserId = null } = {}) {
|
||||
const subject = await this.Subject.findByPk(Number(subjectId));
|
||||
if (!subject) this.ctx.throw(404, '主体已不存在');
|
||||
|
||||
const raw = await this.app.redis.get(this.bindKey(normalized));
|
||||
if (!raw) return { ok: false, reason: 'expired', message: '绑定码已失效,请让管理员重新生成' };
|
||||
const member = await this.Member.findOne({
|
||||
where: { id: Number(memberId), subjectId: Number(subjectId) },
|
||||
});
|
||||
if (!member) this.ctx.throw(404, '成员已不存在');
|
||||
|
||||
let data = null;
|
||||
try {
|
||||
data = JSON.parse(raw);
|
||||
} catch (err) {
|
||||
return { ok: false, reason: 'expired', message: '绑定码已失效,请让管理员重新生成' };
|
||||
}
|
||||
if (data.status === 'confirmed') return { ok: false, reason: 'used', message: '该绑定码已被使用' };
|
||||
const currentUserId = member.userId ? Number(member.userId) : null;
|
||||
const tempUserId = member.tempUserId ? Number(member.tempUserId) : null;
|
||||
const now = new Date();
|
||||
|
||||
const subject = await this.Subject.findByPk(Number(data.subjectId));
|
||||
if (!subject) return { ok: false, reason: 'expired', message: '主体已不存在' };
|
||||
// ① 这个微信已经属于某个平台账号:成员直接绑到它
|
||||
if (boundUserId) {
|
||||
const userId = Number(boundUserId);
|
||||
if (currentUserId && currentUserId !== userId && currentUserId !== tempUserId) {
|
||||
this.ctx.throw(409, '该成员已绑定其他账号,如需换绑请先「解除绑定」');
|
||||
}
|
||||
|
||||
const member = await this.Member.findByPk(Number(data.memberId));
|
||||
if (!member) return { ok: false, reason: 'expired', message: '成员已不存在' };
|
||||
if (member.userId && Number(member.userId) !== Number(userId)) {
|
||||
return { ok: false, reason: 'bound', message: '该成员已绑定其他账号' };
|
||||
}
|
||||
// 同一主体下,一个账号只能有一条成员记录
|
||||
const mine = await this.memberOf(subject.id, userId);
|
||||
if (mine && Number(mine.id) !== Number(member.id)) {
|
||||
this.ctx.throw(409, '你已经是该主体的成员了');
|
||||
}
|
||||
|
||||
// 同一主体下,一个账号只能有一条成员记录
|
||||
const mine = await this.memberOf(subject.id, userId);
|
||||
if (mine && Number(mine.id) !== Number(member.id)) {
|
||||
return { ok: false, reason: 'joined', message: '你已经是该主体的成员了' };
|
||||
}
|
||||
|
||||
let openid = null;
|
||||
try {
|
||||
const wechat = await this.app.model.WechatOauth.findOne({
|
||||
where: { userId: Number(userId) },
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
attributes: [ 'openid' ],
|
||||
await member.update({
|
||||
userId,
|
||||
tempUserId: null,
|
||||
wechatOpenid: String(openid),
|
||||
boundAt: now,
|
||||
status: 1,
|
||||
});
|
||||
openid = wechat ? wechat.openid : null;
|
||||
} catch (err) {
|
||||
openid = null;
|
||||
|
||||
// 自动建的临时账号用不上了,删掉(顺带清掉它上面的微信绑定)
|
||||
if (tempUserId && tempUserId !== userId) await this.dropTempUser(tempUserId);
|
||||
|
||||
const user = await this.app.model.User.findByPk(userId, { attributes: USER_ATTRIBUTES });
|
||||
const boundName = (user && (user.nickname || user.username)) || `用户${userId}`;
|
||||
this.ctx.logger.info('[subject] 主体 %s 成员「%s」绑定到已有账号 %s(%s)', subject.id, member.name, userId, boundName);
|
||||
return this.presentBind({ subject, member, userId, boundName, autoCreated: false });
|
||||
}
|
||||
|
||||
// ② 这个微信还没有平台账号:自动给这名成员建一个,微信就是它的登录方式
|
||||
if (currentUserId && currentUserId !== tempUserId) {
|
||||
this.ctx.throw(409, '该成员已绑定其他账号,如需换绑请先「解除绑定」');
|
||||
}
|
||||
|
||||
const existingTemp = tempUserId ? await this.ctx.service.user.findById(tempUserId) : null;
|
||||
const tempUser = existingTemp || await this.createTempUserForMember(member);
|
||||
|
||||
await this.ctx.service.wxGateway.upsertBinding({
|
||||
userId: Number(tempUser.id),
|
||||
openid,
|
||||
unionid,
|
||||
bindScene: 'member',
|
||||
});
|
||||
|
||||
await member.update({
|
||||
userId: Number(userId),
|
||||
wechatOpenid: openid,
|
||||
boundAt: new Date(),
|
||||
userId: Number(tempUser.id),
|
||||
tempUserId: Number(tempUser.id),
|
||||
wechatOpenid: String(openid),
|
||||
boundAt: now,
|
||||
status: 1,
|
||||
});
|
||||
|
||||
const user = await this.app.model.User.findByPk(Number(userId), { attributes: USER_ATTRIBUTES });
|
||||
const boundName = (user && (user.nickname || user.username)) || `用户${userId}`;
|
||||
|
||||
await this.app.redis.setex(this.bindKey(normalized), BIND_TTL, JSON.stringify({
|
||||
status: 'confirmed',
|
||||
subjectId: Number(subject.id),
|
||||
memberId: Number(member.id),
|
||||
name: member.name,
|
||||
subjectName: subject.name,
|
||||
boundName,
|
||||
}));
|
||||
|
||||
this.ctx.logger.info('[subject] 主体 %s 成员「%s」绑定到用户 %s(%s)',
|
||||
subject.id, member.name, userId, boundName);
|
||||
this.ctx.logger.info('[subject] 主体 %s 成员「%s」自动建号 %s 并绑定微信', subject.id, member.name, tempUser.id);
|
||||
return this.presentBind({
|
||||
subject,
|
||||
member,
|
||||
userId: Number(tempUser.id),
|
||||
boundName: tempUser.nickname || tempUser.username || `用户${tempUser.id}`,
|
||||
autoCreated: true,
|
||||
});
|
||||
}
|
||||
|
||||
presentBind({ subject, member, userId, boundName, autoCreated }) {
|
||||
return {
|
||||
ok: true,
|
||||
status: 'confirmed',
|
||||
subjectId: Number(subject.id),
|
||||
subjectName: subject.name,
|
||||
memberId: Number(member.id),
|
||||
memberName: member.name,
|
||||
userId: Number(userId),
|
||||
boundName,
|
||||
autoCreated: Boolean(autoCreated),
|
||||
};
|
||||
}
|
||||
|
||||
/** 给成员自动建一个账号(用户名 member<成员id>,随机密码;成员姓名当昵称) */
|
||||
async createTempUserForMember(member) {
|
||||
const password = crypto.randomBytes(24).toString('hex');
|
||||
const base = `member${member.id}`;
|
||||
|
||||
let lastError = null;
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const username = i === 0 ? base : `${base}_${crypto.randomBytes(3).toString('hex')}`;
|
||||
try {
|
||||
return await this.ctx.service.auth.register({
|
||||
username,
|
||||
password,
|
||||
nickname: member.name,
|
||||
email: null,
|
||||
phone: null,
|
||||
});
|
||||
} catch (err) {
|
||||
// 用户名撞了(可能撞的是软删的旧账号)→ 换个带随机后缀的再试
|
||||
if (err.status !== 409 && err.name !== 'SequelizeUniqueConstraintError') throw err;
|
||||
lastError = err;
|
||||
}
|
||||
}
|
||||
throw lastError || new Error('给成员创建账号失败');
|
||||
}
|
||||
|
||||
/** 删掉自动建的临时账号(软删;顺带清掉它的微信绑定,免得那个微信再也绑不上别的账号) */
|
||||
async dropTempUser(userId) {
|
||||
const id = Number(userId);
|
||||
if (!id) return;
|
||||
try {
|
||||
await this.app.model.WechatGatewayBinding.destroy({ where: { userId: id }, force: true });
|
||||
await this.app.model.User.destroy({ where: { id } });
|
||||
this.ctx.logger.info('[subject] 已删除临时账号 %s', id);
|
||||
} catch (err) {
|
||||
this.ctx.logger.warn('[subject] 删除临时账号 %s 失败: %s', id, err.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解除成员的账号绑定(**仅管理员**)
|
||||
*
|
||||
* 手机换了人 / 绑错了时的兜底:解绑后成员回到「未绑定」,可以重新出二维码绑别人。
|
||||
* 自动建给成员的临时账号会一并删掉(它上面没有别的登录方式,留着也没人能用)。
|
||||
*
|
||||
* @param {object} params { subjectId, memberId, operatorUserId }
|
||||
* @return {Promise<object>} 解绑后的成员(同 `members()` 里的结构)
|
||||
*/
|
||||
async unbindMember({ subjectId, memberId, operatorUserId } = {}) {
|
||||
await this.ensureAdmin(subjectId, operatorUserId);
|
||||
|
||||
const member = await this.Member.findOne({
|
||||
where: { id: Number(memberId), subjectId: Number(subjectId) },
|
||||
});
|
||||
if (!member) this.ctx.throw(404, '成员不存在');
|
||||
if (!member.userId) return this.presentMember(member, Number(subjectId));
|
||||
|
||||
const userId = Number(member.userId);
|
||||
const tempUserId = member.tempUserId ? Number(member.tempUserId) : null;
|
||||
|
||||
await member.update({
|
||||
userId: null,
|
||||
tempUserId: null,
|
||||
wechatOpenid: null,
|
||||
boundAt: null,
|
||||
});
|
||||
|
||||
// 自动建的临时账号没人能再登录了,直接删掉(顺带清它的微信绑定)
|
||||
if (tempUserId && tempUserId === userId) await this.dropTempUser(tempUserId);
|
||||
|
||||
this.ctx.logger.info('[subject] 用户 %s 解除主体 %s 成员「%s」的账号绑定(原 userId=%s)',
|
||||
operatorUserId, subjectId, member.name, userId);
|
||||
return this.presentMember(member, Number(subjectId));
|
||||
}
|
||||
|
||||
presentMember(row, subjectId) {
|
||||
const data = row.toJSON ? row.toJSON() : row;
|
||||
return {
|
||||
id: Number(data.id),
|
||||
subjectId: Number(subjectId),
|
||||
name: data.name,
|
||||
role: Number(data.role),
|
||||
status: Number(data.status),
|
||||
userId: data.userId ? Number(data.userId) : null,
|
||||
boundAt: data.boundAt || null,
|
||||
wechatBound: Boolean(data.wechatOpenid),
|
||||
user: null,
|
||||
isCreator: false,
|
||||
};
|
||||
}
|
||||
|
||||
@ -546,6 +609,111 @@ class SubjectService extends Service {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* **平台管理员视角**:所有主体(分页)
|
||||
*
|
||||
* 与 `listForUser()` 的区别:不看成员关系,谁都能列;额外带「管理员账号名 / 成员数」。
|
||||
*
|
||||
* @param {object} params { page, pageSize, keyword, status, expired }
|
||||
* keyword 模糊匹配主体名 / 备注;status = 1|0;expired = '1' 只看已过期、'0' 只看未过期
|
||||
*/
|
||||
async listAll({ page = 1, pageSize = 20, keyword, status, expired } = {}) {
|
||||
const size = Math.min(Math.max(Number(pageSize) || 20, 1), 100);
|
||||
const current = Math.max(Number(page) || 1, 1);
|
||||
|
||||
const where = {};
|
||||
if (status !== undefined && status !== '' && status !== null) where.status = Number(status) === 0 ? 0 : 1;
|
||||
if (String(expired) === '1') where.expireAt = { [Op.lte]: new Date() };
|
||||
if (String(expired) === '0') where.expireAt = { [Op.gt]: new Date() };
|
||||
if (keyword) {
|
||||
const like = `%${String(keyword).trim()}%`;
|
||||
where[Op.or] = [
|
||||
{ name: { [Op.like]: like } },
|
||||
{ remark: { [Op.like]: like } },
|
||||
];
|
||||
}
|
||||
|
||||
const { rows, count } = await this.Subject.findAndCountAll({
|
||||
where,
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
limit: size,
|
||||
offset: (current - 1) * size,
|
||||
});
|
||||
|
||||
const ids = rows.map(row => Number(row.id));
|
||||
const counts = ids.length
|
||||
? await this.Member.count({ where: { subjectId: { [Op.in]: ids }, status: 1 }, group: [ 'subject_id' ], raw: true }).catch(() => [])
|
||||
: [];
|
||||
const countRows = Array.isArray(counts) ? counts : [];
|
||||
const countMap = new Map(countRows.map(row => [ Number(row.subjectId || row.subject_id), Number(row.count) || 0 ]));
|
||||
|
||||
const adminIds = [ ...new Set(rows.map(row => Number(row.adminUserId))) ];
|
||||
const admins = adminIds.length
|
||||
? await this.app.model.User.findAll({ where: { id: { [Op.in]: adminIds } }, attributes: [ 'id', 'username', 'nickname' ], paranoid: false })
|
||||
: [];
|
||||
const adminMap = new Map(admins.map(user => [ Number(user.id), user.toJSON() ]));
|
||||
|
||||
return {
|
||||
list: rows.map(row => {
|
||||
const admin = adminMap.get(Number(row.adminUserId)) || null;
|
||||
return this.present(row, {
|
||||
memberCount: countMap.get(Number(row.id)) || 0,
|
||||
adminUser: admin ? { id: Number(admin.id), username: admin.username, nickname: admin.nickname } : null,
|
||||
});
|
||||
}),
|
||||
total: count,
|
||||
page: current,
|
||||
pageSize: size,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* **平台管理员**改授权到期时间(不校验成员关系)
|
||||
*
|
||||
* 两种用法(都不传就报错):
|
||||
* - `expireAt`:直接设成某个时间(可以设成过去 = 立即到期);
|
||||
* - `extendDays`:顺延 N 天(未过期从原到期时间算,已过期从现在算 —— 与 `update()` 一致)。
|
||||
*
|
||||
* 改完必须失效主体状态缓存,否则设备心跳/上报还会读到旧的期限。
|
||||
*
|
||||
* @param {number} subjectId 主体 id
|
||||
* @param {object} patch { expireAt?, extendDays?, remark?, status? }
|
||||
* @param {number} operatorUserId 操作人(只记日志)
|
||||
*/
|
||||
async setExpireAt(subjectId, patch = {}, operatorUserId = null) {
|
||||
const id = Number(subjectId);
|
||||
if (!Number.isInteger(id) || id <= 0) this.ctx.throw(400, '主体 id 必须是正整数');
|
||||
|
||||
const subject = await this.Subject.findByPk(id);
|
||||
if (!subject) this.ctx.throw(404, '主体不存在');
|
||||
|
||||
const fields = {};
|
||||
if (patch.expireAt !== undefined && patch.expireAt !== null && patch.expireAt !== '') {
|
||||
const at = new Date(patch.expireAt);
|
||||
if (Number.isNaN(at.getTime())) this.ctx.throw(422, '到期时间格式不对');
|
||||
fields.expireAt = at;
|
||||
} else if (patch.extendDays !== undefined && patch.extendDays !== null && patch.extendDays !== '') {
|
||||
const days = Number(patch.extendDays);
|
||||
if (!Number.isFinite(days) || days <= 0 || days > 3650) this.ctx.throw(422, '顺延天数必须在 1~3650 之间');
|
||||
const base = this.isExpired(subject) ? Date.now() : new Date(subject.expireAt).getTime();
|
||||
fields.expireAt = new Date(base + Math.round(days) * 24 * 3600 * 1000);
|
||||
}
|
||||
if (patch.remark !== undefined) fields.remark = patch.remark;
|
||||
if (patch.status !== undefined) fields.status = Number(patch.status) === 0 ? 0 : 1;
|
||||
|
||||
if (!Object.keys(fields).length) this.ctx.throw(422, '没有要修改的字段(expireAt / extendDays / remark / status)');
|
||||
|
||||
const before = subject.expireAt;
|
||||
await subject.update(fields);
|
||||
await this.ctx.service.subjectState.invalidate(id);
|
||||
|
||||
this.ctx.logger.info('[subject] 平台管理员 %s 修改主体 %s 的期限:%s → %s',
|
||||
operatorUserId, id, before ? new Date(before).toISOString() : 'null',
|
||||
subject.expireAt ? new Date(subject.expireAt).toISOString() : 'null');
|
||||
|
||||
return this.present(subject);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = SubjectService;
|
||||
|
||||
@ -17,32 +17,16 @@ function randomCode(length = 6) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 微信公众号「网页授权」地址(在微信内置浏览器里打开时用,scope=snsapi_base 静默拿 openid)
|
||||
* 手机扫码后先落到本站 `/wechat?spm=…`,再重定向到这里。
|
||||
*/
|
||||
function webAuthorizeUrl({ appid, redirectUri, state }) {
|
||||
const query = new URLSearchParams({
|
||||
appid,
|
||||
redirect_uri: redirectUri,
|
||||
response_type: 'code',
|
||||
scope: 'snsapi_base',
|
||||
state,
|
||||
});
|
||||
return `https://open.weixin.qq.com/connect/oauth2/authorize?${query.toString()}#wechat_redirect`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 登录页的微信扫码登录
|
||||
* 设备扫码登录的 6 位串码(登录码)
|
||||
*
|
||||
* - **二维码内容是本站地址**:`http://<域名>/wechat?spm=1.0.<code>.1`,`<code>` 是服务端生成的
|
||||
* 6 位数字 + 字母随机串码(存 Redis,TTL 内有效);二维码本身用零依赖的 qrcode-generator
|
||||
* 现场画成 SVG(`/api/wechat/qrcode.svg`),**全程不加载任何第三方图片/脚本**。
|
||||
* - **扫码后**:手机打开**前端路由** `/wechat?spm=…` → 配了微信就重定向到公众号网页授权(静默拿 openid),
|
||||
* 回到后端 `/api/wechat/callback` 后把「已确认的用户 id」写进 Redis;
|
||||
* 没配微信时退化成「手机确认登录」——扫码的人已经登录才能确认(`POST /api/wechat/confirm`)。
|
||||
* - **不自动建号**:只对「已绑定微信」的账号生效(绑定关系在 `wechat_oauth` 表里,
|
||||
* 可用 `POST /api/wechat/bind` 建立),未绑定就提示先用账号密码登录再绑定。
|
||||
* - 串码一次性:确认结果被电脑端取走后立即删除。
|
||||
* - **扫码后**:手机打开**前端路由** `/wechat?spm=…`,扫码的人**已登录**时点确认
|
||||
* (`POST /api/wechat/confirm`),把「已确认的用户 id」写进 Redis。
|
||||
* - 串码一次性:确认结果被电脑端/设备端取走后立即删除。
|
||||
* - 登录页扫码登录、绑定微信都已改走微信登录网关(`app/service/wx_gateway.js`),
|
||||
* 这里只剩**设备扫码登录**(`/api/device/login`)在用。
|
||||
*/
|
||||
class WechatLoginService extends Service {
|
||||
get cfg() {
|
||||
@ -53,11 +37,6 @@ class WechatLoginService extends Service {
|
||||
return this.app.redis;
|
||||
}
|
||||
|
||||
/** 是否配好了微信登录 */
|
||||
get enabled() {
|
||||
return Boolean(this.cfg.appid && this.cfg.secret);
|
||||
}
|
||||
|
||||
/** 扫码状态在 Redis 里的 key(value:'pending' = 等扫码;数字 = 已确认的用户 id) */
|
||||
stateKey(code) {
|
||||
return `${this.app.config.cache.prefix}wechat:state:${code}`;
|
||||
@ -110,15 +89,6 @@ class WechatLoginService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 回调地址:优先用配置,否则按当前请求的 origin 拼
|
||||
* (这是**后端**地址,微信授权后会带 ?code=&state= 重定向到这里,见 controller/auth/wechat.js#callback)
|
||||
*/
|
||||
redirectUri(origin) {
|
||||
if (this.cfg.redirectUri) return this.cfg.redirectUri;
|
||||
return `${String(origin || '').replace(/\/+$/, '')}/api/wechat/callback`;
|
||||
}
|
||||
|
||||
/** 把串码拼成 spm(默认 `1.0.<code>.1`,格式可用 `WECHAT_SPM_PATTERN` 配) */
|
||||
spm(code) {
|
||||
return String(this.cfg.spmPattern || '1.0.{code}.1').replace('{code}', code);
|
||||
@ -144,15 +114,6 @@ class WechatLoginService extends Service {
|
||||
return `${String(origin || '').replace(/\/+$/, '')}/wechat?spm=${this.spm(code)}`;
|
||||
}
|
||||
|
||||
/** 公众号网页授权地址(手机在微信里打开 `/wechat?spm=…` 时重定向过去) */
|
||||
oauthAuthorizeUrl({ origin, code }) {
|
||||
return webAuthorizeUrl({
|
||||
appid: this.cfg.appid,
|
||||
redirectUri: this.redirectUri(origin),
|
||||
state: code,
|
||||
});
|
||||
}
|
||||
|
||||
/** 这个串码还在等扫码吗(存在且是 pending) */
|
||||
async isPending(code) {
|
||||
if (!this.redis || !code) return false;
|
||||
@ -407,75 +368,6 @@ class WechatLoginService extends Service {
|
||||
return Buffer.from(base64, 'base64');
|
||||
}
|
||||
|
||||
/** 用 code 换 openid(只有配好 appid/secret 才会走到这里) */
|
||||
async exchangeCode(code) {
|
||||
const apiBase = String(this.cfg.apiBase || 'https://api.weixin.qq.com').replace(/\/+$/, '');
|
||||
const res = await this.ctx.curl(`${apiBase}/sns/oauth2/access_token`, {
|
||||
method: 'GET',
|
||||
data: {
|
||||
appid: this.cfg.appid,
|
||||
secret: this.cfg.secret,
|
||||
code,
|
||||
grant_type: 'authorization_code',
|
||||
},
|
||||
dataType: 'json',
|
||||
timeout: 5000,
|
||||
});
|
||||
const data = res.data || {};
|
||||
if (data.errcode) {
|
||||
this.ctx.logger.warn('[wechat] 换 openid 失败: %s %s', data.errcode, data.errmsg);
|
||||
return { ok: false, message: `微信返回错误(${data.errcode}):${data.errmsg || '未知'}` };
|
||||
}
|
||||
if (!data.openid) {
|
||||
this.ctx.logger.warn('[wechat] 微信未返回 openid: %j', data);
|
||||
return { ok: false, message: '微信未返回 openid,请重试' };
|
||||
}
|
||||
return { ok: true, openid: data.openid, unionid: data.unionid || null };
|
||||
}
|
||||
|
||||
/**
|
||||
* 扫码后微信授权回来的处理(在**扫码那台设备**上执行):串码存在 → 换 openid → 找已绑定账号 →
|
||||
* 把「已确认的用户 id」写进 Redis(key 就是串码),等电脑端登录页轮询取走。
|
||||
* @param {string} code 微信回传的 code(换 openid 用)
|
||||
* @param {string} state 微信回传的 state(= 本次扫码的 6 位串码)
|
||||
* @return {Promise<{ok:boolean, message?:string, user?:object}>}
|
||||
*/
|
||||
async login(code, state) {
|
||||
if (!this.enabled) {
|
||||
return { ok: false, message: '服务端未配置微信登录(WECHAT_APPID / WECHAT_SECRET)' };
|
||||
}
|
||||
if (!state || !this.redis) {
|
||||
return { ok: false, message: '登录状态已失效,请重新扫码' };
|
||||
}
|
||||
|
||||
let pending;
|
||||
try {
|
||||
pending = await this.redis.get(this.stateKey(state));
|
||||
} catch (err) {
|
||||
this.ctx.logger.error('[wechat] 读取扫码状态失败: %s', err.message);
|
||||
return { ok: false, message: '服务暂时不可用,请稍后再试' };
|
||||
}
|
||||
if (!pending) return { ok: false, message: '二维码已过期,请重新扫码' };
|
||||
if (!code) return { ok: false, message: '微信未回传 code,请重新扫码' };
|
||||
|
||||
const exchanged = await this.exchangeCode(code);
|
||||
if (!exchanged.ok) return exchanged;
|
||||
|
||||
const user = await this.ctx.service.user.findByOpenid(this.cfg.appid, exchanged.openid);
|
||||
if (!user) {
|
||||
this.ctx.logger.info('[wechat] openid 未绑定任何账号: %s', exchanged.openid);
|
||||
return { ok: false, message: '这个微信还没绑定账号,请先用账号密码登录,绑定微信后再扫码' };
|
||||
}
|
||||
if (Number(user.status) !== 1) {
|
||||
return { ok: false, message: '账号已被禁用,请联系管理员' };
|
||||
}
|
||||
|
||||
await this.redis.setex(this.stateKey(state), this.stateTtl, String(user.id));
|
||||
await this.notify(state); // 长轮询的请求靠这条广播立即醒来
|
||||
this.ctx.logger.info('[wechat] 扫码确认成功: %s (id=%s)', user.username, user.id);
|
||||
return { ok: true, user };
|
||||
}
|
||||
|
||||
/** state 有效期(秒):与二维码有效期一致 */
|
||||
get stateTtl() {
|
||||
return Number(this.cfg.stateTtl || 600);
|
||||
|
||||
812
backend/app/service/wx_gateway.js
Normal file
812
backend/app/service/wx_gateway.js
Normal file
@ -0,0 +1,812 @@
|
||||
'use strict';
|
||||
|
||||
const { Service } = require('egg');
|
||||
const crypto = require('crypto');
|
||||
const { Op } = require('sequelize');
|
||||
|
||||
/** 网关页面的场景(文档:`bind` 绑定页 / `login` 登录页) */
|
||||
const SCENE = {
|
||||
LOGIN: 'login',
|
||||
BIND: 'bind',
|
||||
};
|
||||
|
||||
/**
|
||||
* 本地扫码会话的用途 —— 决定「收到网关通知后怎么落地」
|
||||
* - `login`:登录页扫码登录(签发用户 JWT)
|
||||
* - `bind`:个人中心绑定微信(写 `wechat_gateway_bindings`)
|
||||
* - `workstation`:扫码登入工作台(写 `workstation_login_records`)
|
||||
* - `member`:主体成员扫码绑定(绑到已有账号 / 自动建号)
|
||||
*/
|
||||
const PURPOSE = {
|
||||
LOGIN: 'login',
|
||||
BIND: 'bind',
|
||||
WORKSTATION: 'workstation',
|
||||
MEMBER: 'member',
|
||||
};
|
||||
|
||||
const STATUS = {
|
||||
PENDING: 'pending',
|
||||
CONFIRMED: 'confirmed',
|
||||
FAILED: 'failed',
|
||||
};
|
||||
|
||||
/** 会话被取走后最多再留几秒(确认状态只需要撑住正在挂着的长轮询) */
|
||||
const TAKEN_TTL = 300;
|
||||
|
||||
/**
|
||||
* 微信登录网关(https://gateway.gztbyc.com/#/docs)
|
||||
*
|
||||
* 网关做的是「公众号网页授权」:应用服务端申请**临时码** → 前端画成二维码 →
|
||||
* 用户用手机微信扫码、在网关页确认(snsapi_base 静默拿 openid)→
|
||||
* 网关带签名 `POST` 通知应用(`notifyPath`),应用再落地自己的业务。
|
||||
*
|
||||
* 本 service 只做三件事:
|
||||
* 1. 调网关接口(`/api/auth/temp-code`),并把「这次扫码要干什么」记进本地会话;
|
||||
* 2. 校验网关回调的签名(HMAC-SHA256,密钥是 `sha256(appSecret)` 的十六进制);
|
||||
* 3. 把回调结果交回给正在长轮询的浏览器/桌面端(Redis 会话 + 发布订阅)。
|
||||
*
|
||||
* 会话存 Redis(多实例共享);没有 Redis(本地开发/单测)时退化成进程内 Map。
|
||||
*/
|
||||
class WxGatewayService extends Service {
|
||||
get cfg() {
|
||||
return this.app.config.wxGateway || {};
|
||||
}
|
||||
|
||||
/** 没配 appKey/appSecret 就直接不可用(调用方据此隐藏入口 / 返回 503) */
|
||||
get enabled() {
|
||||
return Boolean(this.cfg.appKey && this.cfg.appSecret);
|
||||
}
|
||||
|
||||
get redis() {
|
||||
return this.app.redis || null;
|
||||
}
|
||||
|
||||
/** 本地会话有效期(秒) */
|
||||
get sceneTtl() {
|
||||
return Number(this.cfg.sceneTtl || 660);
|
||||
}
|
||||
|
||||
/** 有没有 Redis(没有就走进程内 Map,只适合单实例/本地开发) */
|
||||
get hasRedis() {
|
||||
return Boolean(this.redis);
|
||||
}
|
||||
|
||||
assertEnabled() {
|
||||
if (!this.enabled) {
|
||||
this.ctx.throw(503, '未配置微信登录网关(WX_GATEWAY_APP_KEY / WX_GATEWAY_APP_SECRET)');
|
||||
}
|
||||
}
|
||||
|
||||
sessionKey(state) {
|
||||
return `${this.app.config.cache.prefix}wxgw:sess:${state}`;
|
||||
}
|
||||
|
||||
channel(state) {
|
||||
return `${this.app.config.cache.prefix}wxgw:chan:${state}`;
|
||||
}
|
||||
|
||||
/** 32 位十六进制随机串:既是本地会话 id,也原样作为网关的 `state` 回传 */
|
||||
newState() {
|
||||
return crypto.randomBytes(16).toString('hex');
|
||||
}
|
||||
|
||||
// ==================== 调网关接口 ====================
|
||||
|
||||
/**
|
||||
* 调网关的 `/api/*`(凭证放 header,见文档)
|
||||
* @param {string} path 形如 `/api/auth/temp-code`
|
||||
* @param {object} payload JSON body
|
||||
* @return {Promise<object>} 网关返回的 `data`
|
||||
*/
|
||||
async requestApi(path, payload) {
|
||||
this.assertEnabled();
|
||||
|
||||
const url = `${this.cfg.baseUrl}${path}`;
|
||||
const options = {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-App-Key': this.cfg.appKey,
|
||||
'X-App-Secret': this.cfg.appSecret,
|
||||
},
|
||||
data: payload || {},
|
||||
contentType: 'json',
|
||||
dataType: 'json',
|
||||
timeout: Number(this.cfg.timeout || 8000),
|
||||
};
|
||||
|
||||
let res = null;
|
||||
try {
|
||||
res = await this.app.curl(url, options);
|
||||
} catch (err) {
|
||||
this.ctx.logger.error('[wx-gateway] 请求 %s 失败: %s', path, err.message);
|
||||
this.ctx.throw(502, `微信登录网关不可用:${err.message}`);
|
||||
}
|
||||
|
||||
const body = (res && res.data) || {};
|
||||
const status = Number(res && res.status) || 0;
|
||||
if (status < 200 || status >= 300 || Number(body.code) !== 0) {
|
||||
const message = body.message || body.msg || `HTTP ${status}`;
|
||||
this.ctx.logger.warn('[wx-gateway] 请求 %s 被拒绝(%s): %j', path, message, body);
|
||||
this.ctx.throw(502, `微信登录网关:${message}`);
|
||||
}
|
||||
|
||||
return body.data || {};
|
||||
}
|
||||
|
||||
/**
|
||||
* 申请临时码(`POST /api/auth/temp-code`)
|
||||
* @param {object} params { scene, state }
|
||||
* @return {Promise<object>} { pageUrl, tempCode, expiresIn, ... }
|
||||
*/
|
||||
async createTempCode({ scene, state } = {}) {
|
||||
const data = await this.requestApi('/api/auth/temp-code', { scene, state });
|
||||
if (!data.pageUrl) this.ctx.throw(502, '微信登录网关没有返回二维码地址');
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 兑换绑定码拿权威信息(`POST /api/auth/verify`,一次一用;有需要时再用)
|
||||
* @param {string} bindCode 通知里的 bindCode
|
||||
* @return {Promise<object>}
|
||||
*/
|
||||
async verifyBindCode(bindCode) {
|
||||
return this.requestApi('/api/auth/verify', { bindCode: String(bindCode || '') });
|
||||
}
|
||||
|
||||
// ==================== 本地扫码会话 ====================
|
||||
|
||||
/**
|
||||
* 开一个扫码会话:先建本地会话,再向网关申请临时码(临时码是一次性的,过 10 分钟作废)
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {string} params.purpose PURPOSE.*
|
||||
* @param {string} params.scene SCENE.*
|
||||
* @param {object} [params.payload] 落地时要用到的上下文(如 workstationId / userId)
|
||||
* @return {Promise<{state:string, pageUrl:string, expiresIn:number}>}
|
||||
*/
|
||||
async openSession({ purpose, scene, payload } = {}) {
|
||||
this.assertEnabled();
|
||||
|
||||
const state = this.newState();
|
||||
const data = await this.createTempCode({ scene, state });
|
||||
|
||||
const session = {
|
||||
status: STATUS.PENDING,
|
||||
purpose,
|
||||
scene,
|
||||
pageUrl: String(data.pageUrl),
|
||||
tempCode: data.tempCode ? String(data.tempCode) : null,
|
||||
payload: payload || {},
|
||||
createdAt: Date.now(),
|
||||
};
|
||||
await this.writeSession(state, session, this.sceneTtl);
|
||||
|
||||
this.ctx.logger.info(
|
||||
'[wx-gateway] 已申请临时码:purpose=%s scene=%s state=%s',
|
||||
purpose, scene, state,
|
||||
);
|
||||
|
||||
return {
|
||||
state,
|
||||
pageUrl: session.pageUrl,
|
||||
tempCode: session.tempCode,
|
||||
expiresIn: this.sceneTtl,
|
||||
scene,
|
||||
};
|
||||
}
|
||||
|
||||
/** 二维码里要编码的内容(网关页面地址);会话没了返回空串 */
|
||||
async pageUrlOf(state) {
|
||||
const session = await this.readSession(state);
|
||||
return session && session.pageUrl ? session.pageUrl : '';
|
||||
}
|
||||
|
||||
async readSession(state) {
|
||||
if (!state) return null;
|
||||
const raw = await this.cacheGet(this.sessionKey(state));
|
||||
if (!raw) return null;
|
||||
try {
|
||||
return JSON.parse(raw);
|
||||
} catch (err) {
|
||||
this.ctx.logger.warn('[wx-gateway] 会话内容损坏(%s): %s', state, err.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async writeSession(state, session, ttl) {
|
||||
await this.cacheSet(this.sessionKey(state), JSON.stringify(session), ttl);
|
||||
}
|
||||
|
||||
async dropSession(state) {
|
||||
await this.cacheDel(this.sessionKey(state));
|
||||
}
|
||||
|
||||
/** 收到通知 → 标记成功并唤醒长轮询 */
|
||||
async confirmSession(state, result) {
|
||||
const session = await this.readSession(state);
|
||||
if (!session) return false;
|
||||
if (session.status === STATUS.CONFIRMED) return true;
|
||||
|
||||
session.status = STATUS.CONFIRMED;
|
||||
session.result = result || {};
|
||||
session.doneAt = Date.now();
|
||||
await this.writeSession(state, session, TAKEN_TTL);
|
||||
await this.publish(state);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** 收到通知但没法落地(微信没绑定账号、账号被禁用…)→ 标记失败并唤醒长轮询 */
|
||||
async failSession(state, message) {
|
||||
const session = await this.readSession(state);
|
||||
if (!session) return false;
|
||||
|
||||
session.status = STATUS.FAILED;
|
||||
session.message = String(message || '扫码失败,请重试');
|
||||
session.doneAt = Date.now();
|
||||
await this.writeSession(state, session, TAKEN_TTL);
|
||||
await this.publish(state);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 长轮询一次会话
|
||||
*
|
||||
* - 已确认 → `{ status:'confirmed', ...result }`(取走即删,一次性)
|
||||
* - 已失败 → `{ status:'failed', message }`
|
||||
* - 会话不存在/已过期 → `{ status:'expired' }`(前端重新申请一张)
|
||||
* - 还在等扫码 → 挂起最多 `wait` 秒(受 `WX_GATEWAY_POLL_WAIT` 限制)后返回 `{ status:'pending' }`
|
||||
* - 客户端提前断开(切面板/关页签)→ `{ status:'aborted' }`,不写响应
|
||||
*
|
||||
* @param {string} state 本地会话 id
|
||||
* @param {object} [options] { wait 挂起秒数 }
|
||||
* @return {Promise<object>}
|
||||
*/
|
||||
async awaitSession(state, { wait = 0 } = {}) {
|
||||
if (!state) return { status: 'expired' };
|
||||
|
||||
const maxWait = Number(this.cfg.pollWait || 55);
|
||||
const seconds = Math.min(Math.max(Number(wait) || 0, 0), maxWait);
|
||||
|
||||
// 先订阅、再查状态:避免「刚查完还是 pending,紧接着就被确认」的那一下漏掉
|
||||
const subscriber = seconds > 0 ? this.subscriber() : null;
|
||||
if (subscriber) {
|
||||
try {
|
||||
await subscriber.subscribe(this.channel(state));
|
||||
} catch (err) {
|
||||
this.ctx.logger.warn('[wx-gateway] 订阅失败: %s', err.message);
|
||||
}
|
||||
}
|
||||
|
||||
const closed = seconds > 0 ? this.clientClosed() : null;
|
||||
|
||||
try {
|
||||
const first = await this.readSession(state);
|
||||
if (!first) return { status: 'expired' };
|
||||
if (first.status !== STATUS.PENDING) return await this.takeSession(state, first);
|
||||
if (!seconds) return { status: 'pending' };
|
||||
|
||||
const hit = await this.waitPublish(subscriber, seconds * 1000, closed);
|
||||
if (hit === 'closed') {
|
||||
this.ctx.logger.info('[wx-gateway] 客户端已断开,停止等待会话 %s', state);
|
||||
return { status: 'aborted' };
|
||||
}
|
||||
if (hit) {
|
||||
const after = await this.readSession(state);
|
||||
if (after && after.status !== STATUS.PENDING) return await this.takeSession(state, after);
|
||||
}
|
||||
return { status: 'pending' };
|
||||
} finally {
|
||||
if (subscriber) subscriber.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
/** 取走会话结果(一次性) */
|
||||
async takeSession(state, session) {
|
||||
await this.dropSession(state);
|
||||
|
||||
if (session.status === STATUS.CONFIRMED) {
|
||||
return Object.assign({ status: 'confirmed' }, session.result || {});
|
||||
}
|
||||
return {
|
||||
status: 'failed',
|
||||
message: session.message || '扫码失败,请重试',
|
||||
};
|
||||
}
|
||||
|
||||
// ==================== 网关回调 ====================
|
||||
|
||||
/**
|
||||
* 校验网关回调的签名与时间戳
|
||||
*
|
||||
* 文档给的算法(Node.js 示例,两边都用 `sha256(appSecret)` 当密钥):
|
||||
* `HMAC-SHA256(sha256hex(appSecret), [appKey, userId, bindCode, timestamp, nonce].join('.'))`
|
||||
*
|
||||
* @param {object} body 通知体
|
||||
* @return {{ok:boolean, message?:string}}
|
||||
*/
|
||||
verifyNotify(body = {}) {
|
||||
if (!this.enabled) return { ok: false, message: '未配置微信登录网关' };
|
||||
|
||||
if (String(body.appKey || '') !== String(this.cfg.appKey)) {
|
||||
return { ok: false, message: 'appKey 不是本应用的' };
|
||||
}
|
||||
|
||||
const timestamp = Number(body.timestamp);
|
||||
const skewMs = Number(this.cfg.notifySkew || 300) * 1000;
|
||||
if (!Number.isFinite(timestamp) || Math.abs(Date.now() - timestamp) > skewMs) {
|
||||
return { ok: false, message: '通知已过期' };
|
||||
}
|
||||
|
||||
const sign = String(body.sign || '').toLowerCase();
|
||||
const expected = this.signOf(body);
|
||||
if (!sign || sign.length !== expected.length) return { ok: false, message: '签名不匹配' };
|
||||
if (!crypto.timingSafeEqual(Buffer.from(sign, 'utf8'), Buffer.from(expected, 'utf8'))) {
|
||||
return { ok: false, message: '签名不匹配' };
|
||||
}
|
||||
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
/** 通知签名(测试里也用它造一份合法签名) */
|
||||
signOf(body = {}) {
|
||||
const secretHash = crypto.createHash('sha256').update(String(this.cfg.appSecret || '')).digest('hex');
|
||||
const message = [ body.appKey, body.userId, body.bindCode, body.timestamp, body.nonce ].join('.');
|
||||
return crypto.createHmac('sha256', secretHash).update(message).digest('hex');
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理网关回调:按会话用途落地
|
||||
*
|
||||
* 返回值只用来写日志/回包,**真正结果通过会话交给长轮询那一侧**
|
||||
* (网关只管通知,浏览器那边看不到这次 HTTP 响应)。
|
||||
*
|
||||
* @param {object} body 通知体(已验签)
|
||||
* @return {Promise<object>}
|
||||
*/
|
||||
async handleNotify(body = {}) {
|
||||
const state = String(body.state || '').trim();
|
||||
const session = state ? await this.readSession(state) : null;
|
||||
|
||||
if (!session) {
|
||||
this.ctx.logger.warn('[wx-gateway] 通知找不到会话(二维码可能已过期):state=%s', state);
|
||||
return { ignored: 'session_expired' };
|
||||
}
|
||||
if (session.status !== STATUS.PENDING) {
|
||||
this.ctx.logger.info('[wx-gateway] 会话 %s 已是 %s,忽略重复通知', state, session.status);
|
||||
return { ignored: `session_${session.status}` };
|
||||
}
|
||||
|
||||
const openid = String(body.openid || '').trim();
|
||||
if (!openid) {
|
||||
await this.failSession(state, '网关未返回 openid,请重新扫码');
|
||||
return { failed: 'no_openid' };
|
||||
}
|
||||
|
||||
try {
|
||||
if (session.purpose === PURPOSE.BIND) {
|
||||
return await this.handleBind(state, session, body, openid);
|
||||
}
|
||||
if (session.purpose === PURPOSE.MEMBER) {
|
||||
return await this.handleMemberBind(state, session, body, openid);
|
||||
}
|
||||
return await this.handleLogin(state, session, body, openid);
|
||||
} catch (err) {
|
||||
// 记全 name + stack:Sequelize 的 "Validation error" 只有一句 message,光看日志没法定位
|
||||
this.ctx.logger.error(
|
||||
'[wx-gateway] 处理通知失败(%s):%s %s\n%s',
|
||||
state, err.name || 'Error', err.message, err.stack || '',
|
||||
);
|
||||
await this.failSession(state, err.message || '扫码失败,请重试');
|
||||
return { failed: err.message };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 成员扫码绑定:把「扫码的微信」落到管理员指定的那名成员上
|
||||
*
|
||||
* 两种情形(具体落库在 `service/subject.js#bindMemberWithWechat`):
|
||||
* - 这个微信已经是某个平台账号的登录方式 → 成员直接绑到那个账号(自动建的临时账号删掉);
|
||||
* - 这个微信还没有平台账号 → 自动给这名成员建号,微信成为它的登录方式。
|
||||
*/
|
||||
async handleMemberBind(state, session, body, openid) {
|
||||
const subjectId = Number(session.payload && session.payload.subjectId);
|
||||
const memberId = Number(session.payload && session.payload.memberId);
|
||||
if (!subjectId || !memberId) {
|
||||
await this.failSession(state, '绑定会话已失效,请重新扫码');
|
||||
return { failed: 'no_member' };
|
||||
}
|
||||
|
||||
// 这个微信已经绑到哪个平台账号?(没有就是 null,走「自动建号」那条)
|
||||
const binding = await this.findBinding(openid);
|
||||
let boundUserId = binding ? Number(binding.userId) : null;
|
||||
if (boundUserId) {
|
||||
const user = await this.ctx.service.user.findById(boundUserId);
|
||||
if (!user) {
|
||||
boundUserId = null;
|
||||
} else if (Number(user.status) !== 1) {
|
||||
await this.failSession(state, '这个微信绑定的账号已被禁用,请联系管理员');
|
||||
return { failed: 'user_disabled' };
|
||||
}
|
||||
}
|
||||
|
||||
const result = await this.ctx.service.subject.bindMemberWithWechat({
|
||||
subjectId,
|
||||
memberId,
|
||||
openid,
|
||||
unionid: body.unionid ? String(body.unionid) : null,
|
||||
boundUserId,
|
||||
});
|
||||
|
||||
await this.confirmSession(state, result);
|
||||
return { member: memberId, userId: result.userId, autoCreated: result.autoCreated };
|
||||
}
|
||||
|
||||
/** 绑定微信:把 openid 落到发起绑定的那个账号上 */
|
||||
async handleBind(state, session, body, openid) {
|
||||
const userId = Number(session.payload && session.payload.userId);
|
||||
if (!userId) {
|
||||
await this.failSession(state, '绑定会话已失效,请重新扫码');
|
||||
return { failed: 'no_user' };
|
||||
}
|
||||
|
||||
const exists = await this.findBinding(openid);
|
||||
if (exists && Number(exists.userId) !== userId) {
|
||||
const other = await this.ctx.service.user.findById(exists.userId);
|
||||
if (other && Number(other.status) === 1) {
|
||||
const who = other.nickname || other.username || `用户${other.id}`;
|
||||
await this.failSession(state, `这个微信已经绑定了其他账号(${who}):请用那个账号登录后在「个人中心 → 微信绑定」解绑,或联系管理员处理`);
|
||||
return { failed: 'openid_bound' };
|
||||
}
|
||||
|
||||
// 原账号已删除 / 被禁用:这条绑定已经"用不了"了,直接把微信改绑到当前账号
|
||||
this.ctx.logger.warn(
|
||||
'[wx-gateway] 微信 %s 原绑定账号 %s 不可用(不存在或已禁用),改绑到 userId=%s',
|
||||
openid, exists.userId, userId,
|
||||
);
|
||||
}
|
||||
|
||||
const mine = await this.findBindingByUser(userId);
|
||||
if (mine && String(mine.openid) !== openid) {
|
||||
await this.failSession(state, '当前账号已绑定其他微信,请先解绑后再绑新的');
|
||||
return { failed: 'user_bound' };
|
||||
}
|
||||
|
||||
const binding = await this.upsertBinding({
|
||||
userId,
|
||||
openid,
|
||||
unionid: body.unionid ? String(body.unionid) : null,
|
||||
bindScene: String(body.scene || SCENE.BIND),
|
||||
});
|
||||
|
||||
this.ctx.logger.info('[wx-gateway] 绑定微信成功:userId=%s openid=%s', userId, openid);
|
||||
await this.confirmSession(state, { binding: this.presentBinding(binding) });
|
||||
return { bound: userId };
|
||||
}
|
||||
|
||||
/** 登录 / 工作台登入:openid → 平台账号,再按用途落地 */
|
||||
async handleLogin(state, session, body, openid) {
|
||||
const binding = await this.findBinding(openid);
|
||||
if (!binding) {
|
||||
const message = '这个微信还没绑定平台账号:请先用账号密码登录,在「个人中心 → 微信绑定」绑好后重新扫码';
|
||||
await this.failSession(state, message);
|
||||
return { failed: 'not_bound' };
|
||||
}
|
||||
|
||||
const user = await this.ctx.service.user.findById(binding.userId);
|
||||
if (!user) {
|
||||
await this.failSession(state, '绑定的平台账号不存在,请联系管理员');
|
||||
return { failed: 'user_missing' };
|
||||
}
|
||||
if (Number(user.status) !== 1) {
|
||||
await this.failSession(state, '账号已被禁用,请联系管理员');
|
||||
return { failed: 'user_disabled' };
|
||||
}
|
||||
|
||||
await this.touchBinding(binding);
|
||||
|
||||
if (session.purpose === PURPOSE.WORKSTATION) {
|
||||
return await this.handleWorkstationLogin(state, session, user);
|
||||
}
|
||||
|
||||
// 登录页:这里只记「谁登录」,令牌等浏览器来取的时候再签(Redis 里不放令牌)
|
||||
await this.confirmSession(state, { userId: Number(user.id) });
|
||||
this.ctx.logger.info('[wx-gateway] 扫码登录成功:%s(id=%s)', user.username, user.id);
|
||||
return { login: Number(user.id) };
|
||||
}
|
||||
|
||||
/** 工作台登入:工作台由会话携带,主体/状态校验在 service 里 */
|
||||
async handleWorkstationLogin(state, session, user) {
|
||||
const workstationId = Number(session.payload && session.payload.workstationId);
|
||||
const workstation = workstationId
|
||||
? await this.app.model.Workstation.findByPk(workstationId)
|
||||
: null;
|
||||
|
||||
if (!workstation) {
|
||||
await this.failSession(state, '工作台不存在或已被删除');
|
||||
return { failed: 'workstation_missing' };
|
||||
}
|
||||
|
||||
const data = await this.ctx.service.workstationLogin.loginByUser({ user, workstation });
|
||||
|
||||
await this.confirmSession(state, {
|
||||
workstation: data.workstation,
|
||||
isMember: data.isMember,
|
||||
member: data.member,
|
||||
name: data.name,
|
||||
record: data.record,
|
||||
});
|
||||
return { workstation: Number(workstation.id), user: Number(user.id) };
|
||||
}
|
||||
|
||||
// ==================== 绑定关系 ====================
|
||||
|
||||
get Binding() {
|
||||
return this.app.model.WechatGatewayBinding;
|
||||
}
|
||||
|
||||
/** 按 openid 反查绑定(一个 openid 只能绑一个账号) */
|
||||
async findBinding(openid) {
|
||||
if (!this.Binding || !openid) return null;
|
||||
return this.Binding.findOne({
|
||||
where: { appKey: this.cfg.appKey, openid: String(openid) },
|
||||
});
|
||||
}
|
||||
|
||||
/** 某账号在当前应用下的绑定(一个账号只留一个微信) */
|
||||
async findBindingByUser(userId) {
|
||||
if (!this.Binding || !userId) return null;
|
||||
return this.Binding.findOne({
|
||||
where: { appKey: this.cfg.appKey, userId: Number(userId) },
|
||||
});
|
||||
}
|
||||
|
||||
/** 当前账号的绑定列表(给个人中心展示) */
|
||||
async listBindings(userId) {
|
||||
if (!this.Binding || !userId) return [];
|
||||
const rows = await this.Binding.findAll({
|
||||
where: { appKey: this.cfg.appKey, userId: Number(userId) },
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
});
|
||||
return rows.map(row => this.presentBinding(row));
|
||||
}
|
||||
|
||||
/**
|
||||
* 运维视角:按 `openid` / `userId` 查绑定(**含已软删的**),带账号状态
|
||||
*
|
||||
* 用途:「这个微信绑在谁身上」「为什么他绑不了」时一眼看明白
|
||||
* @param {object} params { openid?, userId? }
|
||||
*/
|
||||
async listBindingsForOps({ openid, userId } = {}) {
|
||||
if (!this.Binding) return [];
|
||||
|
||||
const where = { appKey: this.cfg.appKey };
|
||||
if (openid) where.openid = String(openid);
|
||||
if (userId) where.userId = Number(userId);
|
||||
if (!openid && !userId) this.ctx.throw(422, 'openid 或 userId 至少要有一个');
|
||||
|
||||
const rows = await this.Binding.findAll({ where, order: [[ 'id', 'DESC' ]], paranoid: false });
|
||||
const userIds = [ ...new Set(rows.map(row => Number(row.userId)).filter(Boolean)) ];
|
||||
const users = userIds.length
|
||||
? await this.app.model.User.findAll({
|
||||
where: { id: { [Op.in]: userIds } },
|
||||
attributes: [ 'id', 'username', 'nickname', 'status' ],
|
||||
paranoid: false,
|
||||
})
|
||||
: [];
|
||||
const byId = new Map(users.map(user => [ Number(user.id), user ]));
|
||||
|
||||
return rows.map(row => {
|
||||
const data = row.toJSON();
|
||||
const user = byId.get(Number(data.userId));
|
||||
return Object.assign(this.presentBinding(row), {
|
||||
userId: data.userId ? Number(data.userId) : null,
|
||||
deletedAt: data.deletedAt || null,
|
||||
user: user ? {
|
||||
id: Number(user.id),
|
||||
username: user.username,
|
||||
nickname: user.nickname || null,
|
||||
status: Number(user.status),
|
||||
deleted: Boolean(user.deletedAt),
|
||||
} : null,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 运维:强制解绑任意一条绑定(不校验归属)
|
||||
*
|
||||
* 给「微信绑在前员工/已停用账号上,本人又拿不到那个账号」兜底;解绑后该微信可以重新绑给别人。
|
||||
* @param {number} id 绑定记录 id
|
||||
*/
|
||||
async forceUnbind(id) {
|
||||
const binding = this.Binding
|
||||
? await this.Binding.findByPk(Number(id), { paranoid: false })
|
||||
: null;
|
||||
if (!binding) this.ctx.throw(404, '绑定记录不存在');
|
||||
|
||||
if (!binding.deletedAt) await binding.destroy();
|
||||
this.ctx.logger.warn('[wx-gateway] 运维强制解绑:id=%s userId=%s openid=%s',
|
||||
binding.id, binding.userId, binding.openid);
|
||||
return { id: Number(binding.id), userId: Number(binding.userId), openid: binding.openid };
|
||||
}
|
||||
|
||||
/** 解绑(只删自己的;找不到当 404) */
|
||||
async unbind(userId, id) {
|
||||
const binding = this.Binding
|
||||
? await this.Binding.findOne({ where: { id: Number(id), userId: Number(userId) } })
|
||||
: null;
|
||||
if (!binding) this.ctx.throw(404, '绑定关系不存在');
|
||||
|
||||
await binding.destroy();
|
||||
this.ctx.logger.info('[wx-gateway] 解绑微信:userId=%s openid=%s', userId, binding.openid);
|
||||
return { id: Number(id) };
|
||||
}
|
||||
|
||||
async upsertBinding({ userId, openid, unionid = null, bindScene = SCENE.BIND } = {}) {
|
||||
const existing = await this.findBinding(openid);
|
||||
|
||||
if (existing) {
|
||||
await existing.update({
|
||||
userId: Number(userId),
|
||||
unionid: unionid || existing.unionid || null,
|
||||
bindScene,
|
||||
});
|
||||
return existing;
|
||||
}
|
||||
|
||||
// 之前解绑过的同一个微信(软删行):唯一键 (app_key, openid) 还占着,
|
||||
// 直接 create 会撞唯一索引、抛出来只有一句 "Validation error" —— 这里把它复活并改归属。
|
||||
const trashed = await this.Binding.findOne({
|
||||
where: { appKey: this.cfg.appKey, openid: String(openid) },
|
||||
paranoid: false,
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
});
|
||||
if (trashed) {
|
||||
if (trashed.deletedAt) await trashed.restore();
|
||||
await trashed.update({
|
||||
userId: Number(userId),
|
||||
unionid: unionid || trashed.unionid || null,
|
||||
bindScene,
|
||||
});
|
||||
this.ctx.logger.info('[wx-gateway] 复用已解绑的绑定记录 id=%s(openid=%s → userId=%s)', trashed.id, openid, userId);
|
||||
return trashed;
|
||||
}
|
||||
|
||||
return this.Binding.create({
|
||||
userId: Number(userId),
|
||||
appKey: this.cfg.appKey,
|
||||
openid: String(openid),
|
||||
unionid: unionid || null,
|
||||
bindScene,
|
||||
});
|
||||
}
|
||||
|
||||
/** 记一次「用这个微信登录了」 */
|
||||
async touchBinding(binding) {
|
||||
try {
|
||||
await binding.update({ lastLoginAt: new Date() });
|
||||
} catch (err) {
|
||||
this.ctx.logger.warn('[wx-gateway] 更新绑定最后登录时间失败: %s', err.message);
|
||||
}
|
||||
}
|
||||
|
||||
presentBinding(binding) {
|
||||
if (!binding) return null;
|
||||
const data = typeof binding.toJSON === 'function' ? binding.toJSON() : binding;
|
||||
return {
|
||||
id: Number(data.id),
|
||||
openid: data.openid,
|
||||
unionid: data.unionid || null,
|
||||
bindScene: data.bindScene || null,
|
||||
lastLoginAt: data.lastLoginAt || null,
|
||||
createdAt: data.createdAt || data.created_at || null,
|
||||
};
|
||||
}
|
||||
|
||||
// ==================== 缓存 / 长轮询小工具 ====================
|
||||
|
||||
/** 没有 Redis 时的进程内兜底(本地开发 / 单测) */
|
||||
get memory() {
|
||||
if (!this._memory) this._memory = new Map();
|
||||
return this._memory;
|
||||
}
|
||||
|
||||
async cacheGet(key) {
|
||||
if (this.redis) {
|
||||
try {
|
||||
return await this.redis.get(key);
|
||||
} catch (err) {
|
||||
this.ctx.logger.warn('[wx-gateway] 读缓存失败,改用进程内存: %s', err.message);
|
||||
}
|
||||
}
|
||||
|
||||
const hit = this.memory.get(key);
|
||||
if (!hit) return null;
|
||||
if (hit.expireAt && hit.expireAt <= Date.now()) {
|
||||
this.memory.delete(key);
|
||||
return null;
|
||||
}
|
||||
return hit.value;
|
||||
}
|
||||
|
||||
async cacheSet(key, value, ttl) {
|
||||
if (this.redis) {
|
||||
try {
|
||||
await this.redis.setex(key, Number(ttl) || this.sceneTtl, value);
|
||||
return;
|
||||
} catch (err) {
|
||||
this.ctx.logger.warn('[wx-gateway] 写缓存失败,改用进程内存: %s', err.message);
|
||||
}
|
||||
}
|
||||
this.memory.set(key, { value: String(value), expireAt: Date.now() + (Number(ttl) || this.sceneTtl) * 1000 });
|
||||
}
|
||||
|
||||
async cacheDel(key) {
|
||||
if (this.redis) {
|
||||
try {
|
||||
await this.redis.del(key);
|
||||
} catch (err) {
|
||||
this.ctx.logger.warn('[wx-gateway] 删缓存失败: %s', err.message);
|
||||
}
|
||||
}
|
||||
this.memory.delete(key);
|
||||
}
|
||||
|
||||
/** 通知「会话状态变了」(长轮询的请求靠它立即醒来) */
|
||||
async publish(state) {
|
||||
if (!this.redis) return;
|
||||
try {
|
||||
await this.redis.publish(this.channel(state), 'done');
|
||||
} catch (err) {
|
||||
this.ctx.logger.warn('[wx-gateway] 广播会话变化失败: %s', err.message);
|
||||
}
|
||||
}
|
||||
|
||||
/** 订阅用的独立连接(用完即 disconnect) */
|
||||
subscriber() {
|
||||
const redis = this.app.redis;
|
||||
if (!redis || typeof redis.duplicate !== 'function') return null;
|
||||
return redis.duplicate();
|
||||
}
|
||||
|
||||
/** 等一条消息;`closed` 提前 resolve 就返回 'closed',超时返回 null */
|
||||
waitPublish(subscriber, waitMs, closed) {
|
||||
const wait = new Promise(resolve => {
|
||||
if (!subscriber) {
|
||||
setTimeout(() => resolve(null), waitMs);
|
||||
return;
|
||||
}
|
||||
let done = false;
|
||||
const finish = value => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
clearTimeout(timer);
|
||||
resolve(value);
|
||||
};
|
||||
const timer = setTimeout(() => finish(null), waitMs);
|
||||
subscriber.on('message', () => finish('done'));
|
||||
});
|
||||
|
||||
return closed ? Promise.race([ wait, closed ]) : wait;
|
||||
}
|
||||
|
||||
/** 客户端断开(页面导航 / fetch abort)时 resolve 'closed' */
|
||||
clientClosed() {
|
||||
const res = this.ctx && this.ctx.res;
|
||||
if (!res || typeof res.on !== 'function') return null;
|
||||
|
||||
return new Promise(resolve => {
|
||||
const onClose = () => {
|
||||
res.removeListener('close', onClose);
|
||||
// 响应正常写完后 close 也会触发,那种不算断开
|
||||
if (!res.writableEnded) resolve('closed');
|
||||
};
|
||||
res.on('close', onClose);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WxGatewayService;
|
||||
module.exports.SCENE = SCENE;
|
||||
module.exports.PURPOSE = PURPOSE;
|
||||
@ -245,15 +245,10 @@ module.exports = (appInfo) => {
|
||||
siteUrl: env.SITE_URL || '',
|
||||
};
|
||||
|
||||
// ==================== 微信扫码登录(登录页右上角三角形切换) ====================
|
||||
// ==================== 设备扫码登录(6 位串码 + 手机页确认) ====================
|
||||
// ⚠️ 登录页扫码登录 / 绑定微信都改走微信登录网关(见下面的 config.wxGateway),
|
||||
// 这里只剩「设备扫码登录」(`/api/device/login`)用到:串码、二维码、长轮询。
|
||||
config.wechat = {
|
||||
// 微信开放平台「网站应用」的 appid / secret;不配则二维码退化为本地演示码
|
||||
appid: env.WECHAT_APPID || '',
|
||||
secret: env.WECHAT_SECRET || '',
|
||||
// 扫码回调地址(不配就按当前请求的 origin 自动拼 /login/wechat/callback)
|
||||
redirectUri: env.WECHAT_REDIRECT_URI || '',
|
||||
// 微信接口地址(默认官方;自建网关/联调时可改,如 http://127.0.0.1:7099)
|
||||
apiBase: env.WECHAT_API_BASE || 'https://api.weixin.qq.com',
|
||||
// 扫码串码:长度、二维码内容里的 spm 格式(`{code}` 占位)
|
||||
codeLength: Number(env.WECHAT_CODE_LENGTH || 6),
|
||||
spmPattern: env.WECHAT_SPM_PATTERN || '1.0.{code}.1',
|
||||
@ -264,15 +259,28 @@ module.exports = (appInfo) => {
|
||||
stateTtl: Number(env.WECHAT_STATE_TTL || 600),
|
||||
// 长轮询最长挂起秒数(默认 60s;前端建议再留一点自己的超时,比如 +10s)
|
||||
pollWait: Number(env.WECHAT_POLL_WAIT || 60),
|
||||
};
|
||||
|
||||
// 微信小程序(code2Session):与公众号的 appid/secret 不是同一套
|
||||
mp: {
|
||||
appid: env.WX_MP_APPID || '',
|
||||
secret: env.WX_MP_SECRET || '',
|
||||
// 未配置 appid/secret 时,本地/单测默认走 mock(生产必须显式 WX_MP_MOCK=true 才允许)
|
||||
mock: /^(1|true|yes|on)$/i.test(String(env.WX_MP_MOCK || '')),
|
||||
apiBase: env.WECHAT_API_BASE || 'https://api.weixin.qq.com',
|
||||
},
|
||||
// ==================== 微信登录网关(扫码登录 / 绑定微信) ====================
|
||||
// 文档:https://gateway.gztbyc.com/#/docs
|
||||
// 流程:应用服务端申请临时码 → 前端画成二维码 → 用户微信扫码确认 →
|
||||
// 网关带签名 POST 通知本服务(`config.wxGateway.notifyPath`)→ 本服务落地
|
||||
// (签发令牌 / 写绑定关系 / 扫码登入工作台)。
|
||||
// ⚠️ 不配 appKey/appSecret 时这些功能一律返回 503,登录页自动隐藏扫码入口。
|
||||
config.wxGateway = {
|
||||
baseUrl: String(env.WX_GATEWAY_BASE || 'https://gateway.gztbyc.com').replace(/\/+$/, ''),
|
||||
appKey: env.WX_GATEWAY_APP_KEY || '',
|
||||
appSecret: env.WX_GATEWAY_APP_SECRET || '',
|
||||
// 调网关接口的超时(毫秒)
|
||||
timeout: Number(env.WX_GATEWAY_TIMEOUT || 8000),
|
||||
// 本地扫码会话有效期(秒):网关临时码是 10 分钟,这里比它略长,收到通知时还有落脚点
|
||||
sceneTtl: Number(env.WX_GATEWAY_SCENE_TTL || 660),
|
||||
// 长轮询最长挂起秒数(前端自己再留一点超时,比如 +10s)
|
||||
pollWait: Number(env.WX_GATEWAY_POLL_WAIT || 55),
|
||||
// 通知里 timestamp 允许的偏差(秒):文档建议 5 分钟
|
||||
notifySkew: Number(env.WX_GATEWAY_NOTIFY_SKEW || 300),
|
||||
// 必须在网关管理台把这个路径配成「服务端通知地址」(只用于提示/自检)
|
||||
notifyPath: '/api/wechat-gateway/notify',
|
||||
};
|
||||
|
||||
// 日志(生产建议按需调整)
|
||||
|
||||
@ -0,0 +1,48 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 微信登录网关绑定表
|
||||
*
|
||||
* 登录页扫码登录 / 工作台扫码登入都需要「微信 openid → 平台账号」的映射,
|
||||
* 由 `POST /api/wechat-gateway/notify`(网关回调)写入。
|
||||
*
|
||||
* 与 `wechat_oauth`(自建公众号网页授权)、`wechat_mp_accounts`(小程序)分开:
|
||||
* 网关用的公众号 appid 我们并不掌握,只有 `appKey` + `openid`。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
const { BIGINT, STRING, DATE } = Sequelize;
|
||||
|
||||
await queryInterface.createTable('wechat_gateway_bindings', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, allowNull: false },
|
||||
user_id: {
|
||||
type: BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
references: { model: 'users', key: 'id' },
|
||||
onUpdate: 'CASCADE',
|
||||
onDelete: 'CASCADE',
|
||||
comment: '绑定的平台账号 users.id',
|
||||
},
|
||||
app_key: { type: STRING(64), allowNull: false, comment: '网关应用标识 appKey' },
|
||||
openid: { type: STRING(64), allowNull: false, comment: '网关返回的 openid' },
|
||||
unionid: { type: STRING(64), allowNull: true, comment: '开放平台 unionid' },
|
||||
bind_scene: { type: STRING(16), allowNull: false, defaultValue: 'bind', comment: '绑定场景:bind / login' },
|
||||
last_login_at: { type: DATE, allowNull: true, comment: '最近一次用这个微信登录的时间' },
|
||||
created_at: { type: DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP') },
|
||||
updated_at: { type: DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP') },
|
||||
deleted_at: { type: DATE, allowNull: true },
|
||||
}, { comment: '微信登录网关绑定表' });
|
||||
|
||||
await queryInterface.addIndex('wechat_gateway_bindings', [ 'app_key', 'openid' ], {
|
||||
name: 'uk_wechat_gateway_bindings_app_openid',
|
||||
unique: true,
|
||||
});
|
||||
await queryInterface.addIndex('wechat_gateway_bindings', [ 'user_id' ], {
|
||||
name: 'idx_wechat_gateway_bindings_user',
|
||||
});
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.dropTable('wechat_gateway_bindings');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,31 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 废弃工作台的「登录码」(`workstations.login_code`,前缀 `WSC-`)
|
||||
*
|
||||
* 扫码登入改为走微信登录网关:二维码由网关的临时码生成、一次有效,
|
||||
* 不再需要(也无法)在工作台上贴一张长期不变的码。
|
||||
*
|
||||
* `workstation_login_records.login_code` 保留(历史记录里记的是当时用的那张码)。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
await queryInterface.removeIndex('workstations', 'uk_workstations_login_code');
|
||||
await queryInterface.removeColumn('workstations', 'login_code');
|
||||
},
|
||||
|
||||
async down(queryInterface, Sequelize) {
|
||||
const { STRING } = Sequelize;
|
||||
|
||||
await queryInterface.addColumn('workstations', 'login_code', {
|
||||
type: STRING(64),
|
||||
allowNull: true,
|
||||
after: 'code',
|
||||
comment: '登录码(已废弃,扫码登入改走微信登录网关)',
|
||||
});
|
||||
await queryInterface.addIndex('workstations', [ 'login_code' ], {
|
||||
name: 'uk_workstations_login_code',
|
||||
unique: true,
|
||||
});
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,26 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 成员「临时账号」
|
||||
*
|
||||
* 成员扫码绑定(微信登录网关)时,如果扫码的微信还没绑定任何平台账号,
|
||||
* 服务端会**自动为这名成员建一个账号**并把它设成该微信的基础账号;
|
||||
* 这个账号记在 `temp_user_id` 上,方便「后来这个微信又绑了/本来就是别的账号」时把它删掉。
|
||||
*
|
||||
* - 绑定成功后 `user_id` = 实际生效的账号(可能就是 temp_user_id);
|
||||
* - 如果扫码的微信已经属于一个**已有账号**:成员改绑到那个账号,临时账号删除(软删),`temp_user_id` 置空。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.addColumn('subject_members', 'temp_user_id', {
|
||||
type: Sequelize.BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
after: 'user_id',
|
||||
comment: '自动建给成员的临时账号 users.id(被已有账号继承时删除)',
|
||||
});
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.removeColumn('subject_members', 'temp_user_id');
|
||||
},
|
||||
};
|
||||
681
backend/test/app/controller/wx-gateway.test.js
Normal file
681
backend/test/app/controller/wx-gateway.test.js
Normal file
@ -0,0 +1,681 @@
|
||||
'use strict';
|
||||
|
||||
const { app, mock, assert } = require('egg-mock/bootstrap');
|
||||
const createFakeRedis = require('../../utils/fake-redis');
|
||||
|
||||
/** 伪造的 sequelize 实例 */
|
||||
const instance = (data) => Object.assign(
|
||||
{
|
||||
toJSON: () => data,
|
||||
update: async (fields) => Object.assign(data, fields),
|
||||
destroy: async () => data,
|
||||
},
|
||||
data,
|
||||
);
|
||||
|
||||
/** 网关返回的临时码(`app.httpclient.request` 的桩) */
|
||||
const gatewayReply = (overrides = {}) => ({
|
||||
status: 200,
|
||||
data: {
|
||||
code: 0,
|
||||
data: Object.assign({
|
||||
appId: 1,
|
||||
appKey: 'gwk_test',
|
||||
scene: 'login',
|
||||
tempCode: 'tc-0001',
|
||||
expiresIn: 600,
|
||||
state: 'whatever',
|
||||
pageUrl: 'https://gateway.example.com/#/auth?code=tc-0001',
|
||||
}, overrides),
|
||||
},
|
||||
});
|
||||
|
||||
describe('test/app/controller/wx-gateway.test.js', () => {
|
||||
const APP_KEY = 'gwk_test';
|
||||
const APP_SECRET = 'gws_test';
|
||||
|
||||
const me = { id: 1, username: 'admin', nickname: '小王', status: 1, email: 'a@b.com' };
|
||||
const SUBJECT_ID = 5;
|
||||
|
||||
let origin = {};
|
||||
|
||||
beforeEach(() => {
|
||||
origin = {
|
||||
appKey: app.config.wxGateway.appKey,
|
||||
appSecret: app.config.wxGateway.appSecret,
|
||||
};
|
||||
app.config.wxGateway.appKey = APP_KEY;
|
||||
app.config.wxGateway.appSecret = APP_SECRET;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
app.config.wxGateway.appKey = origin.appKey;
|
||||
app.config.wxGateway.appSecret = origin.appSecret;
|
||||
});
|
||||
|
||||
const BEARER = 'Bearer';
|
||||
const token = () => app.createAnonymousContext().service.jwt.signUser(me);
|
||||
const withToken = (req) => req.set('Authorization', BEARER + ' ' + token());
|
||||
|
||||
/** 用服务端的算法造一份合法签名(等价于网关那边做的事) */
|
||||
const notifyBody = (fields) => {
|
||||
const body = Object.assign({
|
||||
event: 'login',
|
||||
appId: 1,
|
||||
appKey: APP_KEY,
|
||||
scene: 'login',
|
||||
userId: 12,
|
||||
openid: 'oX-test',
|
||||
unionid: null,
|
||||
bindCode: 'bc-001',
|
||||
state: '',
|
||||
timestamp: Date.now(),
|
||||
nonce: 'abcd1234',
|
||||
}, fields);
|
||||
|
||||
body.sign = app.createAnonymousContext().service.wxGateway.signOf(body);
|
||||
return body;
|
||||
};
|
||||
|
||||
/** 打桩:网关接口固定成功 */
|
||||
function mockGateway(data) {
|
||||
mock(app, 'httpclient', {
|
||||
async request() {
|
||||
return gatewayReply(data);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
it('POST /api/web/auth/wechat-gateway/qrcode:向网关申请临时码并返回可轮询的二维码', async () => {
|
||||
mock(app, 'redis', createFakeRedis().client);
|
||||
let asked = null;
|
||||
mock(app, 'httpclient', {
|
||||
async request(url, options) {
|
||||
asked = { url, options };
|
||||
return gatewayReply();
|
||||
},
|
||||
});
|
||||
|
||||
const res = await app.httpRequest().post('/api/web/auth/wechat-gateway/qrcode').expect(200);
|
||||
const d = res.body.data;
|
||||
|
||||
assert(asked.url === 'https://gateway.gztbyc.com/api/auth/temp-code', asked.url);
|
||||
assert(asked.options.headers['X-App-Key'] === APP_KEY, '必须带 appKey');
|
||||
assert(asked.options.headers['X-App-Secret'] === APP_SECRET, 'appSecret 只在服务端');
|
||||
assert(asked.options.data.scene === 'login', JSON.stringify(asked.options.data));
|
||||
assert(/^[0-9a-f]{32}$/.test(d.state), `state 是本地会话 id:${d.state}`);
|
||||
assert(asked.options.data.state === d.state, 'state 要原样带给网关(回调时用来找回会话)');
|
||||
assert(d.pageUrl === 'https://gateway.example.com/#/auth?code=tc-0001', d.pageUrl);
|
||||
assert(d.qrUrl === `/api/wechat-gateway/qrcode.svg?state=${d.state}`, d.qrUrl);
|
||||
assert(d.expiresIn > 0, '要返回有效期');
|
||||
});
|
||||
|
||||
it('二维码图片:SVG 给浏览器、GIF 给桌面端(WPF 不能渲染 SVG)', async () => {
|
||||
mock(app, 'redis', createFakeRedis().client);
|
||||
mockGateway();
|
||||
|
||||
const issued = await app.httpRequest().post('/api/web/auth/wechat-gateway/qrcode').expect(200);
|
||||
const state = issued.body.data.state;
|
||||
|
||||
const svg = await app.httpRequest().get(`/api/wechat-gateway/qrcode.svg?state=${state}`).expect(200);
|
||||
assert(/^image\/svg\+xml/.test(svg.headers['content-type']), svg.headers['content-type']);
|
||||
const svgText = Buffer.isBuffer(svg.body) ? svg.body.toString('utf8') : String(svg.text || '');
|
||||
assert(svgText.includes('<svg'), 'SVG 里要有 <svg 标签');
|
||||
|
||||
const gif = await app.httpRequest().get(`/api/wechat-gateway/qrcode.gif?state=${state}`).expect(200);
|
||||
assert(String(gif.headers['content-type']).startsWith('image/gif'), gif.headers['content-type']);
|
||||
assert(Buffer.isBuffer(gif.body), `GIF 要按二进制返回(桌面端直接读字节):${typeof gif.body}`);
|
||||
assert(gif.body.slice(0, 3).toString() === 'GIF', '必须是 GIF 字节(桌面端 Image 控件只吃位图)');
|
||||
assert(gif.headers['cache-control'] === 'no-store', '二维码一次有效,不能缓存');
|
||||
});
|
||||
|
||||
it('二维码图片:会话不存在 → 404(前后端都提示刷新)', async () => {
|
||||
mock(app, 'redis', createFakeRedis().client);
|
||||
|
||||
await app.httpRequest().get('/api/wechat-gateway/qrcode.svg?state=not-exists').expect(404);
|
||||
await app.httpRequest().get('/api/wechat-gateway/qrcode.gif?state=not-exists').expect(404);
|
||||
});
|
||||
|
||||
it('未配置网关 → 503(前端据此隐藏扫码入口)', async () => {
|
||||
app.config.wxGateway.appKey = '';
|
||||
app.config.wxGateway.appSecret = '';
|
||||
|
||||
const res = await app.httpRequest().post('/api/web/auth/wechat-gateway/qrcode').expect(503);
|
||||
assert(/未开通微信扫码登录/.test(res.body.message), JSON.stringify(res.body));
|
||||
});
|
||||
|
||||
it('扫码登录:通知 → 长轮询拿令牌(微信已绑定)', async () => {
|
||||
const fake = createFakeRedis();
|
||||
mock(app, 'redis', fake.client);
|
||||
mockGateway();
|
||||
|
||||
const binding = instance({
|
||||
id: 9,
|
||||
userId: 1,
|
||||
appKey: APP_KEY,
|
||||
openid: 'oX-test',
|
||||
unionid: null,
|
||||
bindScene: 'bind',
|
||||
lastLoginAt: null,
|
||||
});
|
||||
|
||||
mock(app, 'model', {
|
||||
User: {
|
||||
async findByPk() { return instance(me); },
|
||||
async findOne() { return instance(me); },
|
||||
},
|
||||
WechatGatewayBinding: {
|
||||
async findOne() { return binding; },
|
||||
async findAll() { return [ binding ]; },
|
||||
},
|
||||
});
|
||||
|
||||
const issued = await app.httpRequest().post('/api/web/auth/wechat-gateway/qrcode').expect(200);
|
||||
const state = issued.body.data.state;
|
||||
|
||||
// 还没人扫码 → pending
|
||||
let polled = await app.httpRequest().get(`/api/web/auth/wechat-gateway/login?state=${state}`).expect(200);
|
||||
assert(polled.body.data.status === 'pending', JSON.stringify(polled.body));
|
||||
|
||||
const notified = await app.httpRequest()
|
||||
.post('/api/wechat-gateway/notify')
|
||||
.send(notifyBody({ state, scene: 'login' }))
|
||||
.expect(200);
|
||||
assert(notified.body.data.login === 1, JSON.stringify(notified.body));
|
||||
assert(binding.toJSON().lastLoginAt instanceof Date, '要记「最近一次用这个微信登录」');
|
||||
|
||||
polled = await app.httpRequest().get(`/api/web/auth/wechat-gateway/login?state=${state}`).expect(200);
|
||||
const d = polled.body.data;
|
||||
assert(d.status === 'confirmed', JSON.stringify(d));
|
||||
assert(d.token && d.tokenType === 'Bearer', '要当场签发用户 JWT');
|
||||
assert(d.user.username === 'admin');
|
||||
|
||||
// 一次性:结果被取走后会话就没了
|
||||
const again = await app.httpRequest().get(`/api/web/auth/wechat-gateway/login?state=${state}`).expect(200);
|
||||
assert(again.body.data.status === 'expired', JSON.stringify(again.body));
|
||||
});
|
||||
|
||||
it('扫码登录:微信还没绑定账号 → failed 并提示先绑定', async () => {
|
||||
mock(app, 'redis', createFakeRedis().client);
|
||||
mockGateway();
|
||||
mock(app, 'model', {
|
||||
WechatGatewayBinding: { async findOne() { return null; } },
|
||||
});
|
||||
|
||||
const issued = await app.httpRequest().post('/api/web/auth/wechat-gateway/qrcode').expect(200);
|
||||
const state = issued.body.data.state;
|
||||
|
||||
await app.httpRequest().post('/api/wechat-gateway/notify')
|
||||
.send(notifyBody({ state }))
|
||||
.expect(200);
|
||||
|
||||
const polled = await app.httpRequest().get(`/api/web/auth/wechat-gateway/login?state=${state}`).expect(200);
|
||||
assert(polled.body.data.status === 'failed', JSON.stringify(polled.body));
|
||||
assert(/还没绑定平台账号/.test(polled.body.data.message), polled.body.data.message);
|
||||
});
|
||||
|
||||
it('POST /api/wechat-gateway/notify:签名不对 / 时间过期 / appKey 不对 → 401', async () => {
|
||||
mock(app, 'redis', createFakeRedis().client);
|
||||
mockGateway();
|
||||
|
||||
const body = notifyBody({ state: 'nope' });
|
||||
await app.httpRequest().post('/api/wechat-gateway/notify')
|
||||
.send(Object.assign({}, body, { sign: 'deadbeef' }))
|
||||
.expect(401);
|
||||
|
||||
await app.httpRequest().post('/api/wechat-gateway/notify')
|
||||
.send(notifyBody({ state: 'nope', timestamp: Date.now() - 10 * 60 * 1000 }))
|
||||
.expect(401);
|
||||
|
||||
await app.httpRequest().post('/api/wechat-gateway/notify')
|
||||
.send(Object.assign({}, body, { appKey: 'gwk_other', sign: app.createAnonymousContext().service.wxGateway.signOf(Object.assign({}, body, { appKey: 'gwk_other' })) }))
|
||||
.expect(401);
|
||||
});
|
||||
|
||||
it('通知里的会话已过期 → 200 + ignored(别让网关白重试)', async () => {
|
||||
mock(app, 'redis', createFakeRedis().client);
|
||||
|
||||
const res = await app.httpRequest().post('/api/wechat-gateway/notify')
|
||||
.send(notifyBody({ state: 'not-exists' }))
|
||||
.expect(200);
|
||||
assert(res.body.data.ignored === 'session_expired', JSON.stringify(res.body));
|
||||
});
|
||||
|
||||
it('绑定微信:扫码后写入绑定关系,个人中心能查到、也能解绑', async () => {
|
||||
mock(app, 'redis', createFakeRedis().client);
|
||||
mockGateway();
|
||||
|
||||
const created = [];
|
||||
let stored = null;
|
||||
mock(app, 'model', {
|
||||
User: { async findByPk() { return instance(me); } },
|
||||
WechatGatewayBinding: {
|
||||
async findOne(where) {
|
||||
if (where && where.where && where.where.openid) return null; // 这个微信还没绑
|
||||
return stored; // 按 user_id 查
|
||||
},
|
||||
async create(row) {
|
||||
stored = instance(Object.assign({ id: 33 }, row));
|
||||
created.push(row);
|
||||
return stored;
|
||||
},
|
||||
async findAll() { return stored ? [ stored ] : []; },
|
||||
},
|
||||
});
|
||||
|
||||
const issued = await withToken(app.httpRequest().post('/api/web/me/wechat/qrcode')).expect(200);
|
||||
const state = issued.body.data.state;
|
||||
|
||||
await app.httpRequest().post('/api/wechat-gateway/notify')
|
||||
.send(notifyBody({ state, event: 'bind', scene: 'bind', openid: 'oX-bind' }))
|
||||
.expect(200);
|
||||
|
||||
let polled = await withToken(app.httpRequest().get(`/api/web/me/wechat/status?state=${state}`)).expect(200);
|
||||
assert(polled.body.data.status === 'confirmed', JSON.stringify(polled.body));
|
||||
assert(polled.body.data.binding.openid === 'oX-bind', JSON.stringify(polled.body.data));
|
||||
assert(created.length === 1 && created[0].userId === 1, '绑定要落在发起绑定的账号上');
|
||||
|
||||
const list = await withToken(app.httpRequest().get('/api/web/me/wechat/bindings')).expect(200);
|
||||
assert(list.body.data.enabled === true);
|
||||
assert(list.body.data.list.length === 1 && list.body.data.list[0].openid === 'oX-bind');
|
||||
|
||||
await withToken(app.httpRequest().delete('/api/web/me/wechat/bindings/33')).expect(200);
|
||||
});
|
||||
|
||||
it('解绑后同一个微信再绑定:复用软删的绑定记录(不报 Validation error)', async () => {
|
||||
mock(app, 'redis', createFakeRedis().client);
|
||||
mockGateway();
|
||||
|
||||
const restored = [];
|
||||
const trashed = instance({
|
||||
id: 12,
|
||||
userId: 1,
|
||||
appKey: APP_KEY,
|
||||
openid: 'oX-again',
|
||||
unionid: null,
|
||||
bindScene: 'bind',
|
||||
deletedAt: new Date(),
|
||||
});
|
||||
trashed.restore = async () => {
|
||||
restored.push(Number(trashed.id));
|
||||
trashed.deletedAt = null;
|
||||
};
|
||||
|
||||
mock(app, 'model', {
|
||||
User: { async findByPk() { return instance(me); } },
|
||||
WechatGatewayBinding: {
|
||||
async findOne(options) {
|
||||
// 正常查询(不含软删)→ 看不到;带 paranoid:false → 找到那条软删的
|
||||
if (options && options.paranoid === false) return trashed;
|
||||
return null;
|
||||
},
|
||||
async create() { throw new Error('不该新建:软删的旧记录应该被复活'); },
|
||||
async findAll() { return [ trashed ]; },
|
||||
},
|
||||
});
|
||||
|
||||
const issued = await withToken(app.httpRequest().post('/api/web/me/wechat/qrcode')).expect(200);
|
||||
const state = issued.body.data.state;
|
||||
|
||||
await app.httpRequest().post('/api/wechat-gateway/notify')
|
||||
.send(notifyBody({ state, event: 'bind', scene: 'bind', openid: 'oX-again' }))
|
||||
.expect(200);
|
||||
|
||||
const polled = await withToken(app.httpRequest().get(`/api/web/me/wechat/status?state=${state}`)).expect(200);
|
||||
assert(polled.body.data.status === 'confirmed', JSON.stringify(polled.body));
|
||||
assert(polled.body.data.binding.id === 12, JSON.stringify(polled.body.data.binding));
|
||||
assert(restored.includes(12), '软删的绑定记录要被 restore,而不是 insert 撞唯一键');
|
||||
});
|
||||
|
||||
it('绑定微信:这个微信已经绑了别的账号 → failed', async () => {
|
||||
mock(app, 'redis', createFakeRedis().client);
|
||||
mockGateway();
|
||||
mock(app, 'model', {
|
||||
User: { async findByPk() { return instance(me); } },
|
||||
WechatGatewayBinding: {
|
||||
async findOne() {
|
||||
return instance({ id: 44, userId: 999, appKey: APP_KEY, openid: 'oX-taken' });
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const issued = await withToken(app.httpRequest().post('/api/web/me/wechat/qrcode')).expect(200);
|
||||
const state = issued.body.data.state;
|
||||
|
||||
await app.httpRequest().post('/api/wechat-gateway/notify')
|
||||
.send(notifyBody({ state, event: 'bind', scene: 'bind', openid: 'oX-taken' }))
|
||||
.expect(200);
|
||||
|
||||
const polled = await withToken(app.httpRequest().get(`/api/web/me/wechat/status?state=${state}`)).expect(200);
|
||||
assert(polled.body.data.status === 'failed', JSON.stringify(polled.body));
|
||||
assert(/已经绑定了其他账号/.test(polled.body.data.message), polled.body.data.message);
|
||||
});
|
||||
|
||||
it('个人中心绑定:这个微信绑的账号已被禁用 → 直接改绑到当前账号', async () => {
|
||||
mock(app, 'redis', createFakeRedis().client);
|
||||
mockGateway();
|
||||
|
||||
const binding = instance({
|
||||
id: 21,
|
||||
userId: 999,
|
||||
appKey: APP_KEY,
|
||||
openid: 'oX-disabled',
|
||||
unionid: null,
|
||||
bindScene: 'bind',
|
||||
});
|
||||
mock(app, 'model', {
|
||||
User: {
|
||||
async findByPk(id) {
|
||||
return Number(id) === 999
|
||||
? instance({ id: 999, username: 'old', nickname: '前员工', status: 0 })
|
||||
: instance(me);
|
||||
},
|
||||
},
|
||||
WechatGatewayBinding: {
|
||||
async findOne(options) {
|
||||
const where = (options && options.where) || {};
|
||||
if (where.openid) return binding; // 这个微信绑在 999(已禁用)上
|
||||
return null; // 当前账号本身还没绑微信
|
||||
},
|
||||
async findAll() { return [ binding ]; },
|
||||
},
|
||||
});
|
||||
|
||||
const issued = await withToken(app.httpRequest().post('/api/web/me/wechat/qrcode')).expect(200);
|
||||
const state = issued.body.data.state;
|
||||
|
||||
await app.httpRequest().post('/api/wechat-gateway/notify')
|
||||
.send(notifyBody({ state, event: 'bind', scene: 'bind', openid: 'oX-disabled' }))
|
||||
.expect(200);
|
||||
|
||||
const polled = await withToken(app.httpRequest().get(`/api/web/me/wechat/status?state=${state}`)).expect(200);
|
||||
assert(polled.body.data.status === 'confirmed', JSON.stringify(polled.body));
|
||||
assert(Number(binding.toJSON().userId) === 1, '要改绑到当前账号');
|
||||
});
|
||||
|
||||
it('运维强制解绑:/api/internal/wechat-bindings/:id(不需要那个账号登录)', async () => {
|
||||
mock(app, 'redis', createFakeRedis().client);
|
||||
|
||||
const destroyed = [];
|
||||
const binding = instance({ id: 31, userId: 999, appKey: APP_KEY, openid: 'oX-ops' });
|
||||
binding.deletedAt = null;
|
||||
binding.destroy = async () => {
|
||||
destroyed.push(31);
|
||||
binding.deletedAt = new Date();
|
||||
};
|
||||
mock(app, 'model', {
|
||||
WechatGatewayBinding: { async findByPk() { return binding; } },
|
||||
});
|
||||
|
||||
const res = await app.httpRequest()
|
||||
.delete('/api/internal/wechat-bindings/31')
|
||||
.set('X-Internal-Token', 'test-internal-token')
|
||||
.expect(200);
|
||||
assert(res.body.data.openid === 'oX-ops', JSON.stringify(res.body));
|
||||
assert(destroyed.includes(31), '要真的解绑');
|
||||
|
||||
await app.httpRequest().delete('/api/internal/wechat-bindings/31').expect(401);
|
||||
});
|
||||
|
||||
it('工作台扫码登入:申请二维码 → 通知 → 轮询拿到登录的成员', async () => {
|
||||
mock(app, 'redis', createFakeRedis().client);
|
||||
mockGateway();
|
||||
|
||||
const subject = instance({
|
||||
id: SUBJECT_ID,
|
||||
name: '测试主体',
|
||||
adminUserId: 1,
|
||||
status: 1,
|
||||
expireAt: new Date(Date.now() + 86400000),
|
||||
});
|
||||
const workstation = instance({
|
||||
id: 3,
|
||||
subjectId: SUBJECT_ID,
|
||||
userId: 1,
|
||||
code: 'WS-01',
|
||||
name: '1号工作台',
|
||||
wsType: 1,
|
||||
status: 1,
|
||||
});
|
||||
let loginRecord = null;
|
||||
|
||||
mock(app, 'model', {
|
||||
User: { async findByPk() { return instance(me); } },
|
||||
Subject: { async findByPk() { return subject; } },
|
||||
SubjectMember: {
|
||||
async findOne() { return instance({ id: 11, subjectId: SUBJECT_ID, userId: 1, name: 'K0012', role: 1, status: 1 }); },
|
||||
},
|
||||
Workstation: {
|
||||
async findByPk() { return workstation; },
|
||||
},
|
||||
WorkstationLoginRecord: {
|
||||
async update() { return [ 0 ]; },
|
||||
async create(row) { loginRecord = instance(Object.assign({ id: 77 }, row)); return loginRecord; },
|
||||
},
|
||||
WechatGatewayBinding: {
|
||||
async findOne() {
|
||||
return instance({ id: 9, userId: 1, appKey: APP_KEY, openid: 'oX-test', bindScene: 'bind' });
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const qr = await withToken(app.httpRequest().post('/api/web/workstations/3/login-qr'))
|
||||
.set('X-Subject-Id', String(SUBJECT_ID))
|
||||
.expect(200);
|
||||
const state = qr.body.data.state;
|
||||
|
||||
await app.httpRequest().post('/api/wechat-gateway/notify')
|
||||
.send(notifyBody({ state, event: 'login', scene: 'login' }))
|
||||
.expect(200);
|
||||
|
||||
const polled = await withToken(app.httpRequest()
|
||||
.get(`/api/web/workstations/3/login-qr/status?state=${state}`)
|
||||
.set('X-Subject-Id', String(SUBJECT_ID)))
|
||||
.expect(200);
|
||||
|
||||
const d = polled.body.data;
|
||||
assert(d.status === 'confirmed', JSON.stringify(d));
|
||||
assert(d.workstation.id === 3 && d.name === 'K0012', JSON.stringify(d));
|
||||
assert(d.record.status === 1, '确认后应该留下一条在线登录记录');
|
||||
assert(loginRecord && loginRecord.workstationId === 3, '登录记录要落在工作台上');
|
||||
});
|
||||
|
||||
/** 成员扫码绑定用到的模型桩(成员 findOne 按 where 分派,账号表用内存 Map) */
|
||||
function memberBindModels({ member, boundUser = null, destroyed = [] }) {
|
||||
const users = new Map();
|
||||
let nextId = 900;
|
||||
|
||||
return {
|
||||
Subject: {
|
||||
async findByPk() {
|
||||
return instance({
|
||||
id: SUBJECT_ID,
|
||||
name: '测试主体',
|
||||
adminUserId: 1,
|
||||
status: 1,
|
||||
expireAt: new Date(Date.now() + 86400000),
|
||||
});
|
||||
},
|
||||
},
|
||||
SubjectMember: {
|
||||
async findOne(options) {
|
||||
const where = (options && options.where) || {};
|
||||
// 按 id 查 = 管理员指定的那名成员;按 user_id 查 = 「这个账号是不是已经在主体里」
|
||||
if (where.id) return member;
|
||||
// 操作人(id=1)是本主体管理员
|
||||
if (Number(where.userId) === 1) {
|
||||
return instance({ id: 99, subjectId: SUBJECT_ID, userId: 1, name: '管理员', role: 1, status: 1 });
|
||||
}
|
||||
return null;
|
||||
},
|
||||
},
|
||||
User: {
|
||||
async findOne() { return null; },
|
||||
async create(row) {
|
||||
const created = instance(Object.assign({ id: nextId++, status: 1 }, row));
|
||||
users.set(Number(created.id), created);
|
||||
return created;
|
||||
},
|
||||
async findByPk(id) {
|
||||
const numeric = Number(id);
|
||||
if (users.has(numeric)) return users.get(numeric);
|
||||
if (numeric === 1) return instance(me);
|
||||
if (boundUser && numeric === Number(boundUser.id)) return instance(boundUser);
|
||||
return null;
|
||||
},
|
||||
async update() { return [ 1 ]; },
|
||||
async destroy(options) {
|
||||
destroyed.push(Number(options.where.id));
|
||||
return 1;
|
||||
},
|
||||
},
|
||||
WechatGatewayBinding: {
|
||||
async findOne(options) {
|
||||
const where = (options && options.where) || {};
|
||||
if (!where.openid) return null;
|
||||
// 这个微信已经属于哪个平台账号(没有就 null)
|
||||
return boundUser
|
||||
? instance({ id: 5, userId: boundUser.id, appKey: APP_KEY, openid: where.openid })
|
||||
: null;
|
||||
},
|
||||
async create(row) { return instance(Object.assign({ id: 6 }, row)); },
|
||||
async destroy() { return 1; },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
it('成员扫码绑定:微信已经是平台账号 → 成员直接继承它,自动建的临时账号被删掉', async () => {
|
||||
mock(app, 'redis', createFakeRedis().client);
|
||||
mockGateway();
|
||||
|
||||
const destroyed = [];
|
||||
const member = instance({
|
||||
id: 11,
|
||||
subjectId: SUBJECT_ID,
|
||||
userId: 77, // 之前自动建的临时账号
|
||||
tempUserId: 77,
|
||||
name: 'K0012',
|
||||
role: 2,
|
||||
status: 1,
|
||||
});
|
||||
// 扫码的微信属于「老张」(id=33,还不是本主体成员)
|
||||
mock(app, 'model', memberBindModels({
|
||||
member,
|
||||
boundUser: { id: 33, username: 'zhang', nickname: '老张', status: 1 },
|
||||
destroyed,
|
||||
}));
|
||||
|
||||
const qr = await withToken(app.httpRequest().post('/api/web/subjects/5/members/11/bind-qr'))
|
||||
.set('X-Subject-Id', String(SUBJECT_ID))
|
||||
.expect(200);
|
||||
assert(qr.body.data.qrUrl.includes('/api/wechat-gateway/qrcode.svg'), JSON.stringify(qr.body));
|
||||
|
||||
await app.httpRequest().post('/api/wechat-gateway/notify')
|
||||
.send(notifyBody({ state: qr.body.data.state, event: 'bind', scene: 'bind', openid: 'oX-member' }))
|
||||
.expect(200);
|
||||
|
||||
const polled = await withToken(app.httpRequest()
|
||||
.get(`/api/web/subjects/5/members/11/bind-qr/status?state=${qr.body.data.state}`)
|
||||
.set('X-Subject-Id', String(SUBJECT_ID)))
|
||||
.expect(200);
|
||||
|
||||
const d = polled.body.data;
|
||||
assert(d.status === 'confirmed', JSON.stringify(d));
|
||||
assert(d.userId === 33, '要绑到微信已有的那个账号');
|
||||
assert(d.boundName === '老张', d.boundName);
|
||||
assert(d.autoCreated === false);
|
||||
|
||||
const saved = member.toJSON();
|
||||
assert(saved.userId === 33 && saved.tempUserId === null, JSON.stringify(saved));
|
||||
assert(saved.wechatOpenid === 'oX-member');
|
||||
assert(destroyed.includes(77), '临时账号要删掉');
|
||||
});
|
||||
|
||||
it('成员扫码绑定:微信还没有平台账号 → 自动给成员建号,并把微信绑成它的登录方式', async () => {
|
||||
mock(app, 'redis', createFakeRedis().client);
|
||||
mockGateway();
|
||||
|
||||
const member = instance({
|
||||
id: 12,
|
||||
subjectId: SUBJECT_ID,
|
||||
userId: null,
|
||||
tempUserId: null,
|
||||
name: 'K0013',
|
||||
role: 2,
|
||||
status: 1,
|
||||
});
|
||||
let createdBinding = null;
|
||||
const models = memberBindModels({ member });
|
||||
const originalCreate = models.WechatGatewayBinding.create;
|
||||
models.WechatGatewayBinding.create = async row => {
|
||||
createdBinding = row;
|
||||
return originalCreate(row);
|
||||
};
|
||||
mock(app, 'model', models);
|
||||
|
||||
const qr = await withToken(app.httpRequest().post('/api/web/subjects/5/members/12/bind-qr'))
|
||||
.set('X-Subject-Id', String(SUBJECT_ID))
|
||||
.expect(200);
|
||||
|
||||
await app.httpRequest().post('/api/wechat-gateway/notify')
|
||||
.send(notifyBody({ state: qr.body.data.state, event: 'bind', scene: 'bind', openid: 'oX-new' }))
|
||||
.expect(200);
|
||||
|
||||
const polled = await withToken(app.httpRequest()
|
||||
.get(`/api/web/subjects/5/members/12/bind-qr/status?state=${qr.body.data.state}`)
|
||||
.set('X-Subject-Id', String(SUBJECT_ID)))
|
||||
.expect(200);
|
||||
|
||||
const d = polled.body.data;
|
||||
assert(d.status === 'confirmed', JSON.stringify(d));
|
||||
assert(d.autoCreated === true, JSON.stringify(d));
|
||||
assert(d.userId >= 900, '要自动建一个新账号');
|
||||
|
||||
const saved = member.toJSON();
|
||||
assert(saved.userId === d.userId && saved.tempUserId === d.userId, JSON.stringify(saved));
|
||||
assert(saved.wechatOpenid === 'oX-new');
|
||||
assert(createdBinding && createdBinding.openid === 'oX-new' && createdBinding.userId === d.userId,
|
||||
JSON.stringify(createdBinding));
|
||||
});
|
||||
|
||||
it('成员解除绑定:回到未绑定,自动建的临时账号一并删除', async () => {
|
||||
mock(app, 'redis', createFakeRedis().client);
|
||||
mockGateway();
|
||||
|
||||
const destroyed = [];
|
||||
const member = instance({
|
||||
id: 14,
|
||||
subjectId: SUBJECT_ID,
|
||||
userId: 901,
|
||||
tempUserId: 901,
|
||||
name: 'K0015',
|
||||
role: 2,
|
||||
status: 1,
|
||||
wechatOpenid: 'oX-temp',
|
||||
});
|
||||
mock(app, 'model', memberBindModels({ member, destroyed }));
|
||||
|
||||
const res = await withToken(app.httpRequest().post('/api/web/subjects/5/members/14/unbind'))
|
||||
.set('X-Subject-Id', String(SUBJECT_ID))
|
||||
.expect(200);
|
||||
|
||||
assert(res.body.data.userId === null, JSON.stringify(res.body));
|
||||
const saved = member.toJSON();
|
||||
assert(saved.userId === null && saved.tempUserId === null && saved.wechatOpenid === null, JSON.stringify(saved));
|
||||
assert(destroyed.includes(901), '自动建的临时账号要删掉');
|
||||
});
|
||||
|
||||
it('成员扫码绑定:成员已绑真实账号 → 生成二维码直接 409', async () => {
|
||||
mock(app, 'redis', createFakeRedis().client);
|
||||
mockGateway();
|
||||
|
||||
mock(app, 'model', memberBindModels({
|
||||
member: instance({ id: 13, subjectId: SUBJECT_ID, userId: 1, tempUserId: null, name: 'K0014', role: 2, status: 1 }),
|
||||
}));
|
||||
|
||||
const res = await withToken(app.httpRequest().post('/api/web/subjects/5/members/13/bind-qr'))
|
||||
.set('X-Subject-Id', String(SUBJECT_ID))
|
||||
.expect(409);
|
||||
assert(/已绑定账号/.test(res.body.message), JSON.stringify(res.body));
|
||||
});
|
||||
});
|
||||
@ -14,8 +14,9 @@ namespace YuncangTrace.LocalService;
|
||||
/// 登录窗
|
||||
///
|
||||
/// - 账号密码登录:`POST /api/web/auth/login` 拿 user JWT(顺带下发主体列表);
|
||||
/// - **微信扫码登录**:`GET /api/wechat/login` 发码 → 显示二维码(GIF,WPF 可直接显示)→ 长轮询
|
||||
/// `GET /api/wechat/login?code=&wait=25`,手机确认后直接拿到令牌;
|
||||
/// - **微信扫码登录**:`POST /api/web/auth/wechat-gateway/qrcode` 申请二维码(微信登录网关)→
|
||||
/// 显示二维码(GIF,WPF 可直接显示)→ 长轮询
|
||||
/// `GET /api/web/auth/wechat-gateway/login?state=&wait=25`,手机微信确认后直接拿到令牌;
|
||||
/// - 本地已有令牌时,先调 `GET /api/web/me` 验证,还有效就直接跳过登录(窗口一闪而过);
|
||||
/// - 成功后把令牌存到 `%LOCALAPPDATA%\YuncangTrace\session.json`。
|
||||
/// </summary>
|
||||
@ -202,16 +203,16 @@ public partial class LoginWindow : Window
|
||||
var api = new ApiClient(AppSettings.Normalize(_settings.ServerBaseUrl));
|
||||
var ticket = await api.StartWechatLoginAsync(cts.Token);
|
||||
|
||||
// WPF 不能渲染 SVG,这里拿同一张二维码的 GIF
|
||||
// WPF 不能渲染 SVG,这里拿同一张二维码的 GIF(内容是网关下发的授权页地址)
|
||||
var bytes = await api.GetImageAsync(
|
||||
$"/api/wechat/qrcode.gif?code={Uri.EscapeDataString(ticket.Code)}", cts.Token);
|
||||
$"/api/wechat-gateway/qrcode.gif?state={Uri.EscapeDataString(ticket.State)}", cts.Token);
|
||||
|
||||
QrImage.Source = ToBitmap(bytes);
|
||||
QrPlaceholder.Visibility = Visibility.Collapsed;
|
||||
QrTip.Text = "请用手机微信扫码,确认后自动登录";
|
||||
|
||||
AppLog.Write($"[wechat] 已生成登录二维码:{ticket.Code}");
|
||||
_ = PollWechatAsync(api, ticket.Code, cts.Token);
|
||||
AppLog.Write($"[wechat] 已生成登录二维码:{ticket.State}");
|
||||
_ = PollWechatAsync(api, ticket.State, cts.Token);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
@ -225,10 +226,10 @@ public partial class LoginWindow : Window
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>长轮询:确认了就登录;码过期(refreshed)就换一张继续等</summary>
|
||||
private async Task PollWechatAsync(ApiClient api, string code, CancellationToken ct)
|
||||
/// <summary>长轮询:确认了就登录;二维码过期(expired)就换一张继续等</summary>
|
||||
private async Task PollWechatAsync(ApiClient api, string state, CancellationToken ct)
|
||||
{
|
||||
var current = code;
|
||||
var current = state;
|
||||
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
@ -255,13 +256,22 @@ public partial class LoginWindow : Window
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.Status == "refreshed" && !string.IsNullOrWhiteSpace(result.Code))
|
||||
if (result.Status == "failed")
|
||||
{
|
||||
current = result.Code!;
|
||||
// 微信没绑定平台账号等:服务端给了原因,直接告诉用户
|
||||
QrTip.Text = result.Message ?? "扫码失败,请重试";
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.Status == "expired")
|
||||
{
|
||||
// 二维码是一次性的:过期就重新申请一张(会话也换成新的)
|
||||
try
|
||||
{
|
||||
var next = await api.StartWechatLoginAsync(ct);
|
||||
current = next.State;
|
||||
var bytes = await api.GetImageAsync(
|
||||
$"/api/wechat/qrcode.gif?code={Uri.EscapeDataString(current)}", ct);
|
||||
$"/api/wechat-gateway/qrcode.gif?state={Uri.EscapeDataString(current)}", ct);
|
||||
QrImage.Source = ToBitmap(bytes);
|
||||
QrTip.Text = "二维码已刷新,请重新扫码";
|
||||
}
|
||||
|
||||
@ -61,11 +61,11 @@ public sealed record ApiSubject(int Id, string Name, string? ExpireAt, bool Expi
|
||||
/// <summary>登录结果:会话 + 用户 + 可进入的主体列表(后端登录接口一起下发)</summary>
|
||||
public sealed record LoginResult(Session Session, ApiUser User, IReadOnlyList<ApiSubject> Subjects);
|
||||
|
||||
/// <summary>微信扫码登录:发码结果</summary>
|
||||
public sealed record WechatTicket(string Code, string QrUrl);
|
||||
/// <summary>微信扫码登录:发码结果(`State` 是本地会话 id,轮询用它;`QrUrl` 是本站画的二维码图片)</summary>
|
||||
public sealed record WechatTicket(string State, string QrUrl);
|
||||
|
||||
/// <summary>微信扫码登录:轮询结果</summary>
|
||||
public sealed record WechatPollResult(string Status, Session? Session, ApiUser? User, string? Code, string? QrUrl, IReadOnlyList<ApiSubject> Subjects);
|
||||
/// <summary>微信扫码登录:轮询结果(`Message` 只在失败时有值)</summary>
|
||||
public sealed record WechatPollResult(string Status, Session? Session, ApiUser? User, string? Message = null);
|
||||
|
||||
/// <summary>本机设备(scanners 表的一行,够桌面端展示用)</summary>
|
||||
public sealed record ApiDevice(int Id, string Sn, string? Name, string? LastSeenAt);
|
||||
@ -181,26 +181,30 @@ public sealed class ApiClient
|
||||
return new LoginResult(session, user, subjects);
|
||||
}
|
||||
|
||||
/// <summary>微信扫码登录:发一个码(`GET /api/wechat/login`,无需令牌)</summary>
|
||||
/// <summary>微信扫码登录:申请一张二维码(`POST /api/web/auth/wechat-gateway/qrcode`,无需令牌)</summary>
|
||||
public async Task<WechatTicket> StartWechatLoginAsync(CancellationToken ct = default)
|
||||
{
|
||||
using var response = await SendAsync(
|
||||
() => new HttpRequestMessage(HttpMethod.Get, $"{BaseUrl}/api/wechat/login"),
|
||||
() => new HttpRequestMessage(HttpMethod.Post, $"{BaseUrl}/api/web/auth/wechat-gateway/qrcode")
|
||||
{
|
||||
Content = new StringContent("{}", Encoding.UTF8, "application/json"),
|
||||
},
|
||||
"生成登录二维码", ct).ConfigureAwait(false);
|
||||
|
||||
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||||
var (data, message) = ReadEnvelope(response, text);
|
||||
if (data is null) throw Failure(response, text, message);
|
||||
|
||||
var code = GetString(data.Value, "code") ?? throw new ApiException("没有拿到登录码");
|
||||
var qrUrl = GetString(data.Value, "qrUrl") ?? $"/api/wechat/qrcode.svg?code={code}";
|
||||
return new WechatTicket(code, qrUrl);
|
||||
var state = GetString(data.Value, "state") ?? throw new ApiException("没有拿到扫码会话");
|
||||
var qrUrl = GetString(data.Value, "qrUrl")
|
||||
?? $"/api/wechat-gateway/qrcode.svg?state={Uri.EscapeDataString(state)}";
|
||||
return new WechatTicket(state, qrUrl);
|
||||
}
|
||||
|
||||
/// <summary>微信扫码登录:轮询一次(`GET /api/wechat/login?code=&wait=`)</summary>
|
||||
public async Task<WechatPollResult> PollWechatLoginAsync(string code, int waitSeconds, CancellationToken ct = default)
|
||||
/// <summary>微信扫码登录:轮询一次(`GET /api/web/auth/wechat-gateway/login?state=&wait=`)</summary>
|
||||
public async Task<WechatPollResult> PollWechatLoginAsync(string state, int waitSeconds, CancellationToken ct = default)
|
||||
{
|
||||
var url = $"{BaseUrl}/api/wechat/login?code={Uri.EscapeDataString(code)}&wait={waitSeconds}";
|
||||
var url = $"{BaseUrl}/api/web/auth/wechat-gateway/login?state={Uri.EscapeDataString(state)}&wait={waitSeconds}";
|
||||
using var response = await SendAsync(
|
||||
() => new HttpRequestMessage(HttpMethod.Get, url), "等待扫码", ct).ConfigureAwait(false);
|
||||
|
||||
@ -211,8 +215,7 @@ public sealed class ApiClient
|
||||
var status = GetString(data.Value, "status") ?? "pending";
|
||||
if (status != "confirmed")
|
||||
{
|
||||
return new WechatPollResult(status, null, null, GetString(data.Value, "code"), GetString(data.Value, "qrUrl"),
|
||||
Array.Empty<ApiSubject>());
|
||||
return new WechatPollResult(status, null, null, GetString(data.Value, "message"));
|
||||
}
|
||||
|
||||
var token = GetString(data.Value, "token") ?? throw new ApiException("扫码确认了但没有令牌");
|
||||
@ -224,7 +227,7 @@ public sealed class ApiClient
|
||||
DisplayName = user.DisplayName,
|
||||
ServerBaseUrl = BaseUrl,
|
||||
};
|
||||
return new WechatPollResult(status, session, user, null, null, Array.Empty<ApiSubject>());
|
||||
return new WechatPollResult(status, session, user);
|
||||
}
|
||||
|
||||
/// <summary>拉图片字节(二维码用;`qrcode.gif` 返回 GIF,WPF 能直接显示)</summary>
|
||||
@ -840,6 +843,23 @@ public sealed class ApiClient
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 拉取本机的**面单摄像头识别配置**(设备令牌;`GET /api/scanner/label-cameras`)。
|
||||
///
|
||||
/// 服务端只返回本主体、散单、启用中工作台里被设为「面单摄像头」的那几路,
|
||||
/// 附上报通道 + 录像机凭据(含密码)。`revision` 是内容指纹,用来判断要不要重建识别任务。
|
||||
/// </summary>
|
||||
public async Task<JsonElement> GetLabelCamerasAsync(string deviceToken, CancellationToken ct = default)
|
||||
{
|
||||
using var response = await SendDeviceAsync(HttpMethod.Get, "/api/scanner/label-cameras", deviceToken, null,
|
||||
"拉取面单识别配置", ct).ConfigureAwait(false);
|
||||
|
||||
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||||
var (data, message) = ReadEnvelope(response, text);
|
||||
if (data is null) throw Failure(response, text, message);
|
||||
return data.Value;
|
||||
}
|
||||
|
||||
// ==================== 内部:请求 ====================
|
||||
|
||||
/// <summary>带用户令牌 + 主体 header 的请求</summary>
|
||||
|
||||
@ -37,10 +37,12 @@ interface RequestOptions {
|
||||
body?: unknown;
|
||||
/** 带上令牌(默认带;登录等公开接口可传 false) */
|
||||
auth?: boolean;
|
||||
/** 中断信号:长轮询(扫码登录 / 绑定 / 工作台登入)在切面板、关弹窗时要能立刻断开 */
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
|
||||
const { method = 'GET', body, auth = true } = options;
|
||||
const { method = 'GET', body, auth = true, signal } = options;
|
||||
const headers: Record<string, string> = {};
|
||||
if (body !== undefined) headers['Content-Type'] = 'application/json';
|
||||
if (auth) {
|
||||
@ -55,6 +57,7 @@ async function request<T>(path: string, options: RequestOptions = {}): Promise<T
|
||||
method,
|
||||
headers,
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
signal,
|
||||
});
|
||||
|
||||
let payload: ApiResult<T> | null = null;
|
||||
|
||||
@ -44,45 +44,54 @@ export function updateSubjectMemberRole(
|
||||
return api.put<SubjectMemberItem>(`/api/web/subjects/${id}/members/${memberId}/role`, { role });
|
||||
}
|
||||
|
||||
export interface MemberBindCode {
|
||||
code: string;
|
||||
export interface MemberBindQr {
|
||||
memberId: number;
|
||||
memberName: string;
|
||||
bindUrl: string;
|
||||
/** 本地扫码会话 id(长轮询用它) */
|
||||
state: string;
|
||||
pageUrl: string;
|
||||
qrUrl: string;
|
||||
expiresIn: number;
|
||||
}
|
||||
|
||||
/** 生成成员绑定码(手机扫码后绑定成员) */
|
||||
export function createMemberBindCode(id: number, memberId: number): Promise<MemberBindCode> {
|
||||
return api.post<MemberBindCode>(`/api/web/subjects/${id}/members/${memberId}/bind-code`, {});
|
||||
/** 生成「扫码绑定」二维码(微信登录网关;成员用微信扫码即绑定) */
|
||||
export function createMemberBindQr(id: number, memberId: number): Promise<MemberBindQr> {
|
||||
return api.post<MemberBindQr>(`/api/web/subjects/${id}/members/${memberId}/bind-qr`, {});
|
||||
}
|
||||
|
||||
export interface MemberBindStatus {
|
||||
status: 'pending' | 'confirmed' | 'expired' | 'bad_format' | string;
|
||||
code?: string;
|
||||
/** pending 等扫码 / confirmed 已绑定 / failed 失败(附 message)/ expired 二维码过期 */
|
||||
status: 'pending' | 'confirmed' | 'failed' | 'expired';
|
||||
message?: string;
|
||||
subjectId?: number;
|
||||
subjectName?: string;
|
||||
memberId?: number;
|
||||
memberName?: string;
|
||||
userId?: number;
|
||||
boundName?: string;
|
||||
/** 这个微信之前没有平台账号,服务端自动给成员建了号 */
|
||||
autoCreated?: boolean;
|
||||
}
|
||||
|
||||
/** 绑定码状态(公开接口,手机扫码页轮询) */
|
||||
export function fetchMemberBindStatus(code: string): Promise<MemberBindStatus> {
|
||||
return api.get<MemberBindStatus>(`/api/subject/member-bind?code=${encodeURIComponent(code)}`, { auth: false });
|
||||
/** 长轮询绑定结果(`wait` 秒内有人确认就立即返回) */
|
||||
export function fetchMemberBindStatus(
|
||||
id: number,
|
||||
memberId: number,
|
||||
state: string,
|
||||
wait = 0,
|
||||
signal?: AbortSignal,
|
||||
): Promise<MemberBindStatus> {
|
||||
const query = new URLSearchParams({ state });
|
||||
if (wait) query.set('wait', String(wait));
|
||||
return api.get<MemberBindStatus>(
|
||||
`/api/web/subjects/${id}/members/${memberId}/bind-qr/status?${query.toString()}`,
|
||||
{ signal },
|
||||
);
|
||||
}
|
||||
|
||||
/** 确认绑定:把当前登录账号绑到该成员(需登录) */
|
||||
export function confirmMemberBind(code: string): Promise<{
|
||||
status: string;
|
||||
subjectId: number;
|
||||
subjectName: string;
|
||||
memberId: number;
|
||||
memberName: string;
|
||||
boundName: string;
|
||||
}> {
|
||||
return api.post('/api/subject/member-bind/confirm', { code });
|
||||
/** 解除成员的账号绑定(绑错了 / 手机换人时用;自动建的临时账号会被删掉) */
|
||||
export function unbindSubjectMember(id: number, memberId: number): Promise<SubjectMemberItem> {
|
||||
return api.post<SubjectMemberItem>(`/api/web/subjects/${id}/members/${memberId}/unbind`, {});
|
||||
}
|
||||
|
||||
// ---------------- 续期:套餐 + 订单 ----------------
|
||||
|
||||
@ -13,6 +13,7 @@
|
||||
import { computed, onBeforeUnmount, onMounted, reactive, ref } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { api, ApiError } from '@/api/client';
|
||||
import { createWechatLoginQr, fetchWechatLoginStatus } from '@/api/web';
|
||||
import { setSession, type CurrentUser } from '@/composables/useAuth';
|
||||
import { applySubjects, type SubjectItem } from '@/composables/useSubject';
|
||||
|
||||
@ -129,7 +130,7 @@ async function doRegister() {
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- 扫码登录(长轮询,60s 挂起 + 客户端 70s 超时) ----------------
|
||||
// ---------------- 扫码登录(微信登录网关:长轮询,55s 挂起 + 客户端 70s 超时) ----------------
|
||||
const qrUrl = ref('');
|
||||
const qrTip = ref('');
|
||||
let polling = false;
|
||||
@ -140,38 +141,44 @@ async function startWechat() {
|
||||
qrUrl.value = '';
|
||||
qrTip.value = '';
|
||||
try {
|
||||
const data = await api.get<{ code: string; qrUrl: string }>('/api/wechat/login', { auth: false });
|
||||
const data = await createWechatLoginQr();
|
||||
qrUrl.value = data.qrUrl;
|
||||
poll(data.code);
|
||||
poll(data.state);
|
||||
} catch (err) {
|
||||
error.value = err instanceof ApiError ? err.message : '二维码生成失败';
|
||||
}
|
||||
}
|
||||
|
||||
/** 长轮询:有人确认就拿到令牌;码过期(refreshed)就换一张继续等 */
|
||||
async function poll(code: string) {
|
||||
/** 长轮询:有人确认就拿到令牌;二维码过期(expired)就换一张继续等 */
|
||||
async function poll(state: string) {
|
||||
polling = true;
|
||||
let current = code;
|
||||
let current = state;
|
||||
let failures = 0;
|
||||
|
||||
while (polling) {
|
||||
abort = new AbortController();
|
||||
const timer = setTimeout(() => abort?.abort(), 70000);
|
||||
try {
|
||||
const res = await fetch(`/api/wechat/login?code=${encodeURIComponent(current)}&wait=60`, { signal: abort.signal });
|
||||
const body = await res.json();
|
||||
const data = body?.data || {};
|
||||
const data = await fetchWechatLoginStatus(current, 55, abort.signal);
|
||||
failures = 0;
|
||||
|
||||
if (data.status === 'confirmed' && data.token) {
|
||||
setSession(data.token, data.user);
|
||||
if (!polling) return;
|
||||
if (data.status === 'confirmed' && data.token && data.user) {
|
||||
setSession(data.token, data.user as CurrentUser);
|
||||
polling = false;
|
||||
go();
|
||||
return;
|
||||
}
|
||||
if (data.status === 'refreshed' && data.code) {
|
||||
current = data.code;
|
||||
qrUrl.value = data.qrUrl;
|
||||
if (data.status === 'failed') {
|
||||
error.value = data.message || '扫码失败,请重试';
|
||||
polling = false;
|
||||
return;
|
||||
}
|
||||
if (data.status === 'expired') {
|
||||
// 二维码是一次性的:过期就重新申请一张(会话已换,继续在新会话上等)
|
||||
const next = await createWechatLoginQr();
|
||||
current = next.state;
|
||||
qrUrl.value = next.qrUrl;
|
||||
qrTip.value = '二维码已刷新,请重新扫码';
|
||||
}
|
||||
} catch {
|
||||
|
||||
@ -1,10 +1,19 @@
|
||||
<script setup lang="ts">
|
||||
/** 个人中心:改资料 / 改密码(都是 `/api/web/me*`,用户 ID 取自令牌) */
|
||||
import { onMounted, reactive, ref } from 'vue';
|
||||
/** 个人中心:改资料 / 改密码 / 绑定微信(都是 `/api/web/me*`,用户 ID 取自令牌) */
|
||||
import { onBeforeUnmount, onMounted, reactive, ref } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import AppLayout from '@/components/AppLayout.vue';
|
||||
import ModalBox from '@/components/ModalBox.vue';
|
||||
import { api, ApiError } from '@/api/client';
|
||||
import {
|
||||
createWechatBindQr,
|
||||
fetchWechatBindings,
|
||||
fetchWechatBindStatus,
|
||||
unbindWechat,
|
||||
type WxBinding,
|
||||
} from '@/api/web';
|
||||
import { clearToken, currentUser, setUser, type CurrentUser } from '@/composables/useAuth';
|
||||
import { formatTime } from '@/utils/format';
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
@ -14,6 +23,103 @@ const busy = ref(false);
|
||||
const error = ref('');
|
||||
const ok = ref('');
|
||||
|
||||
// ---------------- 微信绑定(微信登录网关) ----------------
|
||||
const bindEnabled = ref(false);
|
||||
const bindings = ref<WxBinding[]>([]);
|
||||
const bindListError = ref('');
|
||||
const bindOpen = ref(false);
|
||||
const bindQrUrl = ref('');
|
||||
const bindTip = ref('');
|
||||
let bindPolling = false;
|
||||
let bindAbort: AbortController | null = null;
|
||||
|
||||
async function loadBindings() {
|
||||
bindListError.value = '';
|
||||
try {
|
||||
const data = await fetchWechatBindings();
|
||||
bindEnabled.value = data.enabled;
|
||||
bindings.value = data.list;
|
||||
} catch (err) {
|
||||
bindListError.value = err instanceof ApiError ? err.message : '微信绑定信息加载失败';
|
||||
}
|
||||
}
|
||||
|
||||
/** 申请二维码并开始长轮询(确认后自动关弹窗、刷新列表) */
|
||||
async function startBind() {
|
||||
bindOpen.value = true;
|
||||
bindQrUrl.value = '';
|
||||
bindTip.value = '正在生成二维码…';
|
||||
try {
|
||||
const ticket = await createWechatBindQr();
|
||||
bindQrUrl.value = ticket.qrUrl;
|
||||
bindTip.value = '请用微信扫码,确认后自动绑定';
|
||||
pollBind(ticket.state);
|
||||
} catch (err) {
|
||||
bindTip.value = err instanceof ApiError ? err.message : '二维码生成失败';
|
||||
}
|
||||
}
|
||||
|
||||
/** 二维码是一次性的:过期就重新申请一张继续等 */
|
||||
async function pollBind(state: string) {
|
||||
bindPolling = true;
|
||||
let current = state;
|
||||
|
||||
while (bindPolling) {
|
||||
try {
|
||||
bindAbort = new AbortController();
|
||||
const data = await fetchWechatBindStatus(current, 55, bindAbort.signal);
|
||||
if (!bindPolling) return;
|
||||
|
||||
if (data.status === 'confirmed') {
|
||||
bindPolling = false;
|
||||
bindOpen.value = false;
|
||||
ok.value = '微信已绑定';
|
||||
await loadBindings();
|
||||
return;
|
||||
}
|
||||
if (data.status === 'failed') {
|
||||
bindPolling = false;
|
||||
bindTip.value = data.message || '绑定失败,请重新扫码';
|
||||
return;
|
||||
}
|
||||
if (data.status === 'expired') {
|
||||
const next = await createWechatBindQr();
|
||||
current = next.state;
|
||||
bindQrUrl.value = next.qrUrl;
|
||||
bindTip.value = '二维码已刷新,请重新扫码';
|
||||
}
|
||||
} catch (err) {
|
||||
if (!bindPolling) return;
|
||||
bindTip.value = err instanceof ApiError ? err.message : '连接中断,正在重试…';
|
||||
await new Promise(resolve => setTimeout(resolve, 800));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function stopBind() {
|
||||
bindPolling = false;
|
||||
bindAbort?.abort();
|
||||
}
|
||||
|
||||
function closeBind() {
|
||||
stopBind();
|
||||
bindOpen.value = false;
|
||||
}
|
||||
|
||||
async function doUnbind(item: WxBinding) {
|
||||
if (!window.confirm('解绑后不能再用它扫码登录,确认解绑?')) return;
|
||||
|
||||
ok.value = '';
|
||||
bindListError.value = '';
|
||||
try {
|
||||
await unbindWechat(item.id);
|
||||
ok.value = '微信已解绑';
|
||||
await loadBindings();
|
||||
} catch (err) {
|
||||
bindListError.value = err instanceof ApiError ? err.message : '解绑失败';
|
||||
}
|
||||
}
|
||||
|
||||
function fill(user: CurrentUser | null) {
|
||||
form.nickname = user?.nickname || '';
|
||||
form.email = user?.email || '';
|
||||
@ -22,6 +128,7 @@ function fill(user: CurrentUser | null) {
|
||||
|
||||
onMounted(async () => {
|
||||
fill(currentUser.value);
|
||||
loadBindings();
|
||||
try {
|
||||
const me = await api.get<CurrentUser>('/api/web/me');
|
||||
setUser(me);
|
||||
@ -31,6 +138,8 @@ onMounted(async () => {
|
||||
}
|
||||
});
|
||||
|
||||
onBeforeUnmount(stopBind);
|
||||
|
||||
async function saveProfile() {
|
||||
error.value = '';
|
||||
ok.value = '';
|
||||
@ -117,7 +226,41 @@ async function savePassword() {
|
||||
</label>
|
||||
<button class="btn" :disabled="busy">修改密码</button>
|
||||
</form>
|
||||
|
||||
<div class="card">
|
||||
<h3>微信绑定</h3>
|
||||
<div v-if="bindListError" class="alert alert-error">{{ bindListError }}</div>
|
||||
|
||||
<p v-if="!bindEnabled" class="hint">服务端未开通微信扫码登录(未配置微信登录网关)。</p>
|
||||
<template v-else>
|
||||
<p class="hint">
|
||||
绑定后可以直接用微信扫码登录;扫码登入工作台也认这个微信。
|
||||
<br />一个微信只能绑一个账号,一个账号也只绑一个微信。
|
||||
</p>
|
||||
<ul v-if="bindings.length" class="bind-list">
|
||||
<li v-for="item in bindings" :key="item.id">
|
||||
<span class="mono">{{ item.openid.slice(0, 6) }}…{{ item.openid.slice(-4) }}</span>
|
||||
<span class="hint">{{ item.lastLoginAt ? `最近登录 ${formatTime(item.lastLoginAt)}` : '还没用它登录过' }}</span>
|
||||
<button class="btn btn-sm btn-ghost" @click="doUnbind(item)">解绑</button>
|
||||
</li>
|
||||
</ul>
|
||||
<p v-else class="hint">还没有绑定微信。</p>
|
||||
<button v-if="!bindings.length" class="btn" type="button" @click="startBind">+ 扫码绑定微信</button>
|
||||
<p v-else class="hint">换绑请先解绑上面这个微信。</p>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ModalBox :open="bindOpen" title="绑定微信" width="360px" @close="closeBind">
|
||||
<div class="bind-qr">
|
||||
<img v-if="bindQrUrl" class="qr-img" :src="bindQrUrl" width="200" height="200" alt="绑定微信二维码" />
|
||||
<p v-else class="hint center">二维码生成中…</p>
|
||||
<p class="hint center">{{ bindTip || '请用微信扫码' }}</p>
|
||||
</div>
|
||||
<template #footer>
|
||||
<button class="btn btn-ghost" @click="closeBind">关闭</button>
|
||||
</template>
|
||||
</ModalBox>
|
||||
</AppLayout>
|
||||
</template>
|
||||
|
||||
@ -131,4 +274,36 @@ h3 {
|
||||
margin: 0 0 14px;
|
||||
font-size: 15px;
|
||||
}
|
||||
.bind-list {
|
||||
list-style: none;
|
||||
margin: 0 0 14px;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
.bind-list li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
justify-content: space-between;
|
||||
}
|
||||
.bind-qr {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
.mono {
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
font-size: 12px;
|
||||
}
|
||||
.qr-img {
|
||||
width: 200px;
|
||||
height: 200px;
|
||||
padding: 6px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
background: #fff;
|
||||
}
|
||||
</style>
|
||||
|
||||
@ -4,7 +4,9 @@
|
||||
*
|
||||
* - 列表:我加入的主体(角色 / 使用期限 / 成员数),可切换、续期(管理员)
|
||||
* - 创建主体:默认赠送 7 天使用期限(天数由后端下发 `trialDays`)
|
||||
* - 成员管理:按姓名快速添加(先不绑账号)→ 生成绑定码 → 手机扫码确认后绑定账号
|
||||
* - 成员管理:按姓名快速添加(先不绑账号)→「扫码绑定」出微信二维码 →
|
||||
* 成员用手机微信扫码:已是平台账号的直接继承(自动建的临时账号删除),
|
||||
* 还没有账号的由服务端自动建号并把微信绑成它的登录方式
|
||||
*/
|
||||
import { computed, onMounted, onBeforeUnmount, reactive, ref } from 'vue';
|
||||
import AppLayout from '@/components/AppLayout.vue';
|
||||
@ -13,7 +15,7 @@ import { ApiError } from '@/api/client';
|
||||
import {
|
||||
addSubjectMember,
|
||||
closeSubjectOrder,
|
||||
createMemberBindCode,
|
||||
createMemberBindQr,
|
||||
createSubject,
|
||||
createSubjectOrder,
|
||||
fetchMemberBindStatus,
|
||||
@ -21,8 +23,9 @@ import {
|
||||
fetchSubjectOrder,
|
||||
fetchSubjectPlans,
|
||||
removeSubjectMember,
|
||||
unbindSubjectMember,
|
||||
updateSubjectMemberRole,
|
||||
type MemberBindCode,
|
||||
type MemberBindQr,
|
||||
type SubjectOrder,
|
||||
type SubjectPlan,
|
||||
} from '@/api/subjectApi';
|
||||
@ -256,7 +259,7 @@ async function addMember() {
|
||||
const created = await addSubjectMember(subject.id, { name });
|
||||
members.value = [ ...members.value, created ];
|
||||
newMemberName.value = '';
|
||||
ok.value = `成员「${created.name}」已添加,可生成绑定码让他扫码绑定账号`;
|
||||
ok.value = `成员「${created.name}」已添加,可点「扫码绑定」让他用微信扫码绑定账号`;
|
||||
} catch (err) {
|
||||
error.value = err instanceof ApiError ? err.message : '添加成员失败';
|
||||
} finally {
|
||||
@ -279,6 +282,22 @@ async function removeMember(member: SubjectMemberItem) {
|
||||
}
|
||||
}
|
||||
|
||||
/** 解除成员的账号绑定(绑错了 / 手机换人:解绑后可以重新扫码绑别人) */
|
||||
async function unbindMember(member: SubjectMemberItem) {
|
||||
const subject = memberSubject.value;
|
||||
if (!subject) return;
|
||||
if (!window.confirm(`确认解除「${member.name}」的账号绑定?解绑后需要用微信重新扫码绑定。`)) return;
|
||||
error.value = '';
|
||||
ok.value = '';
|
||||
try {
|
||||
const data = await unbindSubjectMember(subject.id, member.id);
|
||||
members.value = members.value.map(item => (item.id === member.id ? data : item));
|
||||
ok.value = `已解除「${member.name}」的账号绑定,可以重新扫码绑定`;
|
||||
} catch (err) {
|
||||
error.value = err instanceof ApiError ? err.message : '解除绑定失败';
|
||||
}
|
||||
}
|
||||
|
||||
/** 设/取消管理员:一个主体可以有多个管理员(创建者恒为管理员,不能降级) */
|
||||
const roleUpdating = ref(0);
|
||||
|
||||
@ -309,68 +328,83 @@ async function toggleRole(member: SubjectMemberItem) {
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- 成员绑定码 ----------------
|
||||
// ---------------- 成员扫码绑定(微信登录网关) ----------------
|
||||
const bindOpen = ref(false);
|
||||
const bindData = ref<MemberBindCode | null>(null);
|
||||
const bindQr = ref<MemberBindQr | null>(null);
|
||||
const bindStatus = ref('');
|
||||
const bindBoundName = ref('');
|
||||
let bindTimer: number | null = null;
|
||||
const bindMessage = ref('');
|
||||
let bindPolling = false;
|
||||
let bindAbort: AbortController | null = null;
|
||||
|
||||
async function openBindCode(member: SubjectMemberItem) {
|
||||
const subject = memberSubject.value;
|
||||
if (!subject) return;
|
||||
error.value = '';
|
||||
bindBoundName.value = '';
|
||||
bindMessage.value = '';
|
||||
bindStatus.value = '';
|
||||
try {
|
||||
const data = await createMemberBindCode(subject.id, member.id);
|
||||
bindData.value = data;
|
||||
const data = await createMemberBindQr(subject.id, member.id);
|
||||
bindQr.value = data;
|
||||
bindStatus.value = 'pending';
|
||||
bindOpen.value = true;
|
||||
startBindPolling(data.code);
|
||||
pollBind(subject.id, member.id, data.state);
|
||||
} catch (err) {
|
||||
error.value = err instanceof ApiError ? err.message : '绑定码生成失败';
|
||||
error.value = err instanceof ApiError ? err.message : '二维码生成失败';
|
||||
}
|
||||
}
|
||||
|
||||
function startBindPolling(code: string) {
|
||||
stopBindPolling();
|
||||
bindTimer = window.setInterval(async () => {
|
||||
/**
|
||||
* 长轮询:有人扫码就刷新成员列表;二维码一次性,过期(expired)就换一张继续等
|
||||
* (确认后弹窗保留、展示「已绑定」,管理员点关闭即可)
|
||||
*/
|
||||
async function pollBind(subjectId: number, memberId: number, state: string) {
|
||||
bindPolling = true;
|
||||
let current = state;
|
||||
|
||||
while (bindPolling) {
|
||||
try {
|
||||
const status = await fetchMemberBindStatus(code);
|
||||
if (status.status === 'confirmed') {
|
||||
bindAbort = new AbortController();
|
||||
const data = await fetchMemberBindStatus(subjectId, memberId, current, 50, bindAbort.signal);
|
||||
if (!bindPolling) return;
|
||||
|
||||
if (data.status === 'confirmed') {
|
||||
bindStatus.value = 'confirmed';
|
||||
bindBoundName.value = status.boundName || '';
|
||||
stopBindPolling();
|
||||
bindMessage.value = data.autoCreated
|
||||
? `已绑定:${data.boundName || '账号'}(这个微信还没有平台账号,已自动为「${data.memberName || ''}」建号)`
|
||||
: `已绑定:${data.boundName || '账号'}`;
|
||||
bindPolling = false;
|
||||
await loadMembers();
|
||||
} else if (status.status === 'expired') {
|
||||
bindStatus.value = 'expired';
|
||||
stopBindPolling();
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
/* 网络抖动忽略,下一轮继续 */
|
||||
if (data.status === 'failed') {
|
||||
bindStatus.value = 'failed';
|
||||
bindMessage.value = data.message || '绑定失败,请重新扫码';
|
||||
bindPolling = false;
|
||||
return;
|
||||
}
|
||||
if (data.status === 'expired') {
|
||||
const next = await createMemberBindQr(subjectId, memberId);
|
||||
bindQr.value = next;
|
||||
current = next.state;
|
||||
bindMessage.value = '二维码已刷新,请重新扫码';
|
||||
}
|
||||
} catch (err) {
|
||||
if (!bindPolling) return;
|
||||
bindMessage.value = err instanceof ApiError ? err.message : '连接中断,正在重试…';
|
||||
await new Promise(resolve => setTimeout(resolve, 800));
|
||||
}
|
||||
}, 2000);
|
||||
}
|
||||
}
|
||||
|
||||
function stopBindPolling() {
|
||||
if (bindTimer !== null) {
|
||||
window.clearInterval(bindTimer);
|
||||
bindTimer = null;
|
||||
}
|
||||
bindPolling = false;
|
||||
bindAbort?.abort();
|
||||
}
|
||||
|
||||
function closeBind() {
|
||||
stopBindPolling();
|
||||
bindOpen.value = false;
|
||||
bindData.value = null;
|
||||
}
|
||||
|
||||
function copyBindUrl() {
|
||||
if (!bindData.value) return;
|
||||
navigator.clipboard?.writeText(bindData.value.bindUrl).then(
|
||||
() => { ok.value = '绑定链接已复制'; },
|
||||
() => { error.value = '复制失败,请手动选择二维码下方的链接'; },
|
||||
);
|
||||
bindQr.value = null;
|
||||
}
|
||||
|
||||
onMounted(load);
|
||||
@ -383,7 +417,7 @@ onBeforeUnmount(() => {
|
||||
const currentId = computed(() => currentSubjectId.value);
|
||||
const canRenew = (item: SubjectItem) => Number(item.role) === 1;
|
||||
|
||||
/** 成员管理(增 / 删 / 绑定码 / 改角色)只有主体管理员能做,其他成员只读 */
|
||||
/** 成员管理(增 / 删 / 扫码绑定 / 改角色)只有主体管理员能做,其他成员只读 */
|
||||
const canManageMembers = computed(() => Number(memberSubject.value?.role || 0) === 1);
|
||||
|
||||
/** 这一行是不是我自己(后端也不允许改自己的角色 / 删自己) */
|
||||
@ -487,10 +521,11 @@ function isSelf(member: SubjectMemberItem) {
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="canManageMembers" class="hint">
|
||||
添加后成员还没有账号:点「绑定码」出二维码,让成员用手机扫码并登录确认,即可绑定到该成员。
|
||||
添加后成员还没有账号:点「扫码绑定」出二维码,让成员用手机微信扫码——已经是平台账号的直接绑上去,
|
||||
还没有账号的服务端会自动给他建一个(微信就是该账号的登录方式)。
|
||||
</p>
|
||||
<p v-else class="hint">
|
||||
你在这个主体里是「成员」,只能查看成员列表;添加成员、发绑定码、设为管理员、移除都需要主体管理员操作。
|
||||
你在这个主体里是「成员」,只能查看成员列表;添加成员、扫码绑定、设为管理员、移除都需要主体管理员操作。
|
||||
</p>
|
||||
|
||||
<div class="table-wrap member-table">
|
||||
@ -522,7 +557,14 @@ function isSelf(member: SubjectMemberItem) {
|
||||
<span v-else class="muted">未绑定</span>
|
||||
</td>
|
||||
<td v-if="canManageMembers" class="ops">
|
||||
<button v-if="!member.userId" class="btn btn-sm" @click="openBindCode(member)">绑定码</button>
|
||||
<button v-if="!member.userId" class="btn btn-sm" @click="openBindCode(member)">扫码绑定</button>
|
||||
<button
|
||||
v-else-if="!member.isCreator && !isSelf(member)"
|
||||
class="btn btn-sm btn-ghost"
|
||||
@click="unbindMember(member)"
|
||||
>
|
||||
解除绑定
|
||||
</button>
|
||||
<button
|
||||
v-if="member.role !== 1"
|
||||
class="btn btn-sm btn-ghost"
|
||||
@ -561,21 +603,22 @@ function isSelf(member: SubjectMemberItem) {
|
||||
</template>
|
||||
</ModalBox>
|
||||
|
||||
<!-- 成员绑定码 -->
|
||||
<ModalBox :open="bindOpen" title="成员绑定码" @close="closeBind">
|
||||
<div v-if="bindData" class="bind-box">
|
||||
<img v-if="bindStatus !== 'expired'" :src="bindData.qrUrl" alt="成员绑定二维码" class="bind-qr" />
|
||||
<p class="bind-code">绑定码:<b>{{ bindData.code }}</b></p>
|
||||
<p class="hint">成员用手机扫码(或打开下面的链接)→ 登录后点「确认绑定」,即成为「{{ bindData.memberName }}」。</p>
|
||||
<p class="bind-url">{{ bindData.bindUrl }}</p>
|
||||
<p v-if="bindStatus === 'pending'" class="hint">等待扫码确认…({{ Math.round(bindData.expiresIn / 60) }} 分钟内有效)</p>
|
||||
<p v-else-if="bindStatus === 'confirmed'" class="alert alert-ok">
|
||||
已绑定:{{ bindBoundName || '账号' }}
|
||||
<!-- 成员扫码绑定(微信登录网关) -->
|
||||
<ModalBox :open="bindOpen" title="扫码绑定成员" width="380px" @close="closeBind">
|
||||
<div v-if="bindQr" class="bind-box">
|
||||
<img :src="bindQr.qrUrl" alt="成员绑定二维码" class="bind-qr" />
|
||||
<p class="hint center">
|
||||
让「{{ bindQr.memberName }}」用手机微信扫码并确认:<br />
|
||||
已经是平台账号的直接绑到这个成员;还没有账号的会自动给他建一个。
|
||||
</p>
|
||||
<p v-else-if="bindStatus === 'expired'" class="alert alert-error">绑定码已过期,请重新生成</p>
|
||||
<p v-if="bindStatus === 'pending'" class="hint center">
|
||||
等待扫码…({{ Math.round(bindQr.expiresIn / 60) }} 分钟内有效,过期会自动换新)
|
||||
</p>
|
||||
<p v-else-if="bindStatus === 'confirmed'" class="alert alert-ok">{{ bindMessage }}</p>
|
||||
<p v-else-if="bindStatus === 'failed'" class="alert alert-error">{{ bindMessage }}</p>
|
||||
<p v-else-if="bindMessage" class="hint center">{{ bindMessage }}</p>
|
||||
</div>
|
||||
<template #footer>
|
||||
<button class="btn btn-ghost" @click="copyBindUrl">复制链接</button>
|
||||
<button class="btn" @click="closeBind">关闭</button>
|
||||
</template>
|
||||
</ModalBox>
|
||||
@ -705,18 +748,6 @@ function isSelf(member: SubjectMemberItem) {
|
||||
padding: 6px;
|
||||
}
|
||||
|
||||
.bind-code {
|
||||
font-size: 15px;
|
||||
margin: 10px 0 4px;
|
||||
}
|
||||
|
||||
.bind-url {
|
||||
word-break: break-all;
|
||||
font-size: 12px;
|
||||
color: #64748b;
|
||||
margin: 6px 0;
|
||||
}
|
||||
|
||||
.text-danger {
|
||||
color: #b91c1c;
|
||||
}
|
||||
|
||||
@ -1,86 +1,29 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 手机扫码后打开的页面,两种用途:
|
||||
* 手机扫码后打开的页面(**设备扫码登录**专用)
|
||||
*
|
||||
* 1. **扫码登录**:`/wechat?spm=1.0.<码>.1`
|
||||
* - 配了微信:本页把手机重定向到公众号网页授权,回来时由后端 `/api/wechat/callback`
|
||||
* 处理完再把浏览器转回本页(带 `?ok=1|0&message=`);
|
||||
* - 没配微信(本机默认):要求手机端**已登录**,点确认调 `POST /api/wechat/confirm`。
|
||||
* 2. **主体成员绑定**:`/wechat?bind=<码>`
|
||||
* - 已登录的账号点「确认绑定」→ `POST /api/subject/member-bind/confirm`
|
||||
* → 该账号被写进主体成员,之后可以进入这个主体。
|
||||
* `/wechat?spm=1.0.<码>.1`
|
||||
* - 要求手机端**已登录**(没登录先去登录页,登录后回到本页),点确认调 `POST /api/wechat/confirm`;
|
||||
* - 确认成功后设备端的长轮询立刻拿到长期令牌,设备就算注册/登录完成。
|
||||
*
|
||||
* ⚠️ 登录页扫码登录、绑定微信、主体成员绑定都已改走微信登录网关(`/api/wechat-gateway/*`),
|
||||
* 手机侧由网关自己的页面完成确认,不再经过本页。
|
||||
*/
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { api, ApiError } from '@/api/client';
|
||||
import { isLoggedIn } from '@/composables/useAuth';
|
||||
import { fetchMemberBindStatus, confirmMemberBind, type MemberBindStatus } from '@/api/subjectApi';
|
||||
import { loadSubjects } from '@/composables/useSubject';
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
|
||||
/** 成员绑定码(`?bind=`) */
|
||||
const bindCode = computed(() => String(route.query.bind || '').toUpperCase());
|
||||
|
||||
const spm = computed(() => String(route.query.spm || ''));
|
||||
const code = computed(() => spm.value.split('.').find(seg => /^[0-9A-Za-z]{6}$/.test(seg))?.toUpperCase() || '');
|
||||
|
||||
const busy = ref(false);
|
||||
const done = ref(route.query.ok === '1');
|
||||
const error = ref(route.query.ok === '0' ? String(route.query.message || '扫码失败,请重新扫码') : '');
|
||||
const tip = ref('');
|
||||
const done = ref(false);
|
||||
const error = ref('');
|
||||
|
||||
// ---------------- 成员绑定 ----------------
|
||||
const bindInfo = ref<MemberBindStatus | null>(null);
|
||||
const bindDone = ref(false);
|
||||
const bindError = ref('');
|
||||
let timer: number | null = null;
|
||||
|
||||
async function refreshBind() {
|
||||
if (!bindCode.value) return;
|
||||
try {
|
||||
bindInfo.value = await fetchMemberBindStatus(bindCode.value);
|
||||
if (bindInfo.value.status === 'expired') bindError.value = '绑定码已过期,请让管理员重新生成';
|
||||
if (bindInfo.value.status === 'confirmed') {
|
||||
bindDone.value = true;
|
||||
stopPolling();
|
||||
}
|
||||
} catch (err) {
|
||||
bindError.value = err instanceof ApiError ? err.message : '绑定码查询失败';
|
||||
}
|
||||
}
|
||||
|
||||
function stopPolling() {
|
||||
if (timer !== null) {
|
||||
window.clearInterval(timer);
|
||||
timer = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmBind() {
|
||||
bindError.value = '';
|
||||
if (!isLoggedIn()) {
|
||||
// 手机端没登录 → 去登录,登录完回到本页(绑定码在 URL 里,不会丢)
|
||||
router.replace({ name: 'login', query: { redirect: route.fullPath } });
|
||||
return;
|
||||
}
|
||||
busy.value = true;
|
||||
try {
|
||||
const data = await confirmMemberBind(bindCode.value);
|
||||
bindDone.value = true;
|
||||
tip.value = `已绑定为「${data.memberName}」(${data.subjectName})`;
|
||||
stopPolling();
|
||||
// 新加入的主体要出现在切换器里
|
||||
loadSubjects().catch(() => undefined);
|
||||
} catch (err) {
|
||||
bindError.value = err instanceof ApiError ? err.message : '绑定失败,请稍后再试';
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- 扫码登录 ----------------
|
||||
async function confirm() {
|
||||
error.value = '';
|
||||
if (!isLoggedIn()) {
|
||||
@ -99,50 +42,24 @@ async function confirm() {
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
if (bindCode.value) {
|
||||
refreshBind();
|
||||
timer = window.setInterval(refreshBind, 3000);
|
||||
// 旧链接(`/wechat?bind=<码>`)已经失效:直接说清楚,别让用户对着按钮点半天
|
||||
if (route.query.bind) {
|
||||
error.value = '成员绑定码已停用:请让管理员在「主体 / 成员」里重新生成二维码,用微信扫码即可绑定。';
|
||||
}
|
||||
});
|
||||
|
||||
onBeforeUnmount(stopPolling);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="bare-page">
|
||||
<div class="card bare-card">
|
||||
<!-- ============ 成员绑定 ============ -->
|
||||
<template v-if="bindCode">
|
||||
<h1 class="title">确认绑定主体成员</h1>
|
||||
<h1 class="title">确认登录</h1>
|
||||
|
||||
<div v-if="bindDone" class="alert alert-ok">
|
||||
{{ tip || '已绑定成功' }},可以回到电脑上继续操作。
|
||||
</div>
|
||||
<div v-else-if="bindError" class="alert alert-error">{{ bindError }}</div>
|
||||
<template v-else>
|
||||
<p class="code-line">绑定码 <code>{{ bindCode }}</code></p>
|
||||
<p v-if="bindInfo?.memberName" class="hint center">
|
||||
将把当前登录账号绑定为主体「{{ bindInfo.subjectName || bindInfo.subjectId }}」的成员
|
||||
<b>{{ bindInfo.memberName }}</b>
|
||||
</p>
|
||||
<p v-if="!isLoggedIn()" class="hint center">请先登录你的账号,登录后会自动回到本页。</p>
|
||||
<button class="btn btn-block" :disabled="busy" @click="confirmBind">
|
||||
{{ isLoggedIn() ? (busy ? '绑定中…' : '确认绑定') : '去登录' }}
|
||||
</button>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
<!-- ============ 扫码登录 ============ -->
|
||||
<div v-if="done" class="alert alert-ok">已确认登录,请回到电脑上继续操作。</div>
|
||||
<div v-else-if="!code" class="alert alert-error">{{ error || '登录码格式不对,请重新扫码。' }}</div>
|
||||
<template v-else>
|
||||
<h1 class="title">确认登录</h1>
|
||||
|
||||
<div v-if="done" class="alert alert-ok">已确认登录,请回到电脑上继续操作。</div>
|
||||
<div v-else-if="!code" class="alert alert-error">登录码格式不对,请重新扫码。</div>
|
||||
<template v-else>
|
||||
<div v-if="error" class="alert alert-error">{{ error }}</div>
|
||||
<p class="code-line">登录码 <code>{{ code }}</code></p>
|
||||
<button class="btn btn-block" :disabled="busy" @click="confirm">确认登录</button>
|
||||
</template>
|
||||
<div v-if="error" class="alert alert-error">{{ error }}</div>
|
||||
<p class="code-line">登录码 <code>{{ code }}</code></p>
|
||||
<button class="btn btn-block" :disabled="busy" @click="confirm">确认登录</button>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
@ -164,8 +81,4 @@ onBeforeUnmount(stopPolling);
|
||||
text-align: center;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.center {
|
||||
text-align: center;
|
||||
}
|
||||
</style>
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user