From b2eea280013eda3e0b70903b1516cfb67cbf50d2 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 29 Oct 2026 17:19:52 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E5=BE=AE=E4=BF=A1=E7=BD=91=E5=85=B3):=20?= =?UTF-8?q?=E6=89=AB=E7=A0=81=E7=99=BB=E5=BD=95=20/=20=E7=BB=91=E5=AE=9A?= =?UTF-8?q?=E5=BE=AE=E4=BF=A1=20/=20=E5=B7=A5=E4=BD=9C=E5=8F=B0=E6=89=AB?= =?UTF-8?q?=E7=A0=81=E7=99=BB=E5=85=A5=EF=BC=8C=E5=BA=9F=E5=BC=83=E8=87=AA?= =?UTF-8?q?=E5=BB=BA=E7=99=BB=E5=BD=95=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 对接 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> --- backend/app/controller/auth/member_bind.js | 66 -- backend/app/controller/auth/wechat.js | 138 +-- backend/app/controller/device/auth.js | 4 +- backend/app/controller/gateway/notify.js | 42 + backend/app/controller/internal/wechat.js | 92 +- backend/app/controller/web/subject.js | 69 +- backend/app/controller/web/wx_gateway.js | 204 +++++ backend/app/middleware/api_auth.js | 3 +- backend/app/model/subject_member.js | 4 +- backend/app/model/wechat_gateway_binding.js | 35 + backend/app/service/subject.js | 428 ++++++--- backend/app/service/wechat_login.js | 120 +-- backend/app/service/wx_gateway.js | 812 ++++++++++++++++++ backend/config/config.default.js | 40 +- ...28120000-create-wechat-gateway-bindings.js | 48 ++ ...61028121000-drop-workstation-login-code.js | 31 + ...1028121500-add-subject-member-temp-user.js | 26 + .../test/app/controller/wx-gateway.test.js | 681 +++++++++++++++ desktop/LoginWindow.xaml.cs | 34 +- desktop/Services/ApiClient.cs | 50 +- frontend/src/api/client.ts | 5 +- frontend/src/api/subjectApi.ts | 51 +- frontend/src/views/LoginView.vue | 35 +- frontend/src/views/ProfileView.vue | 179 +++- frontend/src/views/SubjectsView.vue | 165 ++-- frontend/src/views/WechatConfirmView.vue | 125 +-- 26 files changed, 2716 insertions(+), 771 deletions(-) delete mode 100644 backend/app/controller/auth/member_bind.js create mode 100644 backend/app/controller/gateway/notify.js create mode 100644 backend/app/controller/web/wx_gateway.js create mode 100644 backend/app/model/wechat_gateway_binding.js create mode 100644 backend/app/service/wx_gateway.js create mode 100644 backend/database/migrations/20261028120000-create-wechat-gateway-bindings.js create mode 100644 backend/database/migrations/20261028121000-drop-workstation-login-code.js create mode 100644 backend/database/migrations/20261028121500-add-subject-member-temp-user.js create mode 100644 backend/test/app/controller/wx-gateway.test.js diff --git a/backend/app/controller/auth/member_bind.js b/backend/app/controller/auth/member_bind.js deleted file mode 100644 index cc70b48..0000000 --- a/backend/app/controller/auth/member_bind.js +++ /dev/null @@ -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; diff --git a/backend/app/controller/auth/wechat.js b/backend/app/controller/auth/wechat.js index 4899a38..2c195f6 100644 --- a/backend/app/controller/auth/wechat.js +++ b/backend/app/controller/auth/wechat.js @@ -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`, - * 不配就用 `/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 —— 查串码状态(**无需登录**,小程序/网页先问一下再决定怎么提示) * diff --git a/backend/app/controller/device/auth.js b/backend/app/controller/device/auth.js index 9ca8d05..dc7aa68 100644 --- a/backend/app/controller/device/auth.js +++ b/backend/app/controller/device/auth.js @@ -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)—— diff --git a/backend/app/controller/gateway/notify.js b/backend/app/controller/gateway/notify.js new file mode 100644 index 0000000..e7e50bc --- /dev/null +++ b/backend/app/controller/gateway/notify.js @@ -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; diff --git a/backend/app/controller/internal/wechat.js b/backend/app/controller/internal/wechat.js index 16b0537..4ca1db8 100644 --- a/backend/app/controller/internal/wechat.js +++ b/backend/app/controller/internal/wechat.js @@ -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) }; } } diff --git a/backend/app/controller/web/subject.js b/backend/app/controller/web/subject.js index e891186..5b27fe9 100644 --- a/backend/app/controller/web/subject.js +++ b/backend/app/controller/web/subject.js @@ -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, diff --git a/backend/app/controller/web/wx_gateway.js b/backend/app/controller/web/wx_gateway.js new file mode 100644 index 0000000..3205b4f --- /dev/null +++ b/backend/app/controller/web/wx_gateway.js @@ -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; diff --git a/backend/app/middleware/api_auth.js b/backend/app/middleware/api_auth.js index e8fe809..758d542 100644 --- a/backend/app/middleware/api_auth.js +++ b/backend/app/middleware/api_auth.js @@ -6,7 +6,8 @@ * 用法:`router.post('/api/xxx', middleware.apiAuth(), controller.xxx.yyy)` * * - 令牌:`Authorization: Bearer `(也认 `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 }`; diff --git a/backend/app/model/subject_member.js b/backend/app/model/subject_member.js index 47cd383..b98c448 100644 --- a/backend/app/model/subject_member.js +++ b/backend/app/model/subject_member.js @@ -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' }, diff --git a/backend/app/model/wechat_gateway_binding.js b/backend/app/model/wechat_gateway_binding.js new file mode 100644 index 0000000..80f8851 --- /dev/null +++ b/backend/app/model/wechat_gateway_binding.js @@ -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; +}; diff --git a/backend/app/service/subject.js b/backend/app/service/subject.js index 696e731..fe2b818 100644 --- a/backend/app/service/subject.js +++ b/backend/app/service/subject.js @@ -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} { code, bindUrl, qrUrl, expiresIn } + * 走微信登录网关(`scene=bind`):成员用手机微信扫码 → 网关回调后按两种情形落地: + * - 这个微信**已经是某个平台账号**的登录方式 → 成员直接绑到那个账号(之前自动建的临时账号删掉); + * - 这个微信**还没有平台账号** → 自动给这名成员建一个账号,并把微信绑成它的登录方式。 + * + * @param {object} params { subjectId, memberId, operatorUserId } + * @return {Promise} { 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} { 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} 解绑后的成员(同 `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; diff --git a/backend/app/service/wechat_login.js b/backend/app/service/wechat_login.js index 282ea2b..349b5aa 100644 --- a/backend/app/service/wechat_login.js +++ b/backend/app/service/wechat_login.js @@ -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..1`,`` 是服务端生成的 * 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..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); diff --git a/backend/app/service/wx_gateway.js b/backend/app/service/wx_gateway.js new file mode 100644 index 0000000..336d59f --- /dev/null +++ b/backend/app/service/wx_gateway.js @@ -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} 网关返回的 `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} { 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} + */ + 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} + */ + 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} + */ + 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; diff --git a/backend/config/config.default.js b/backend/config/config.default.js index 6f5fba4..c40a559 100644 --- a/backend/config/config.default.js +++ b/backend/config/config.default.js @@ -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', }; // 日志(生产建议按需调整) diff --git a/backend/database/migrations/20261028120000-create-wechat-gateway-bindings.js b/backend/database/migrations/20261028120000-create-wechat-gateway-bindings.js new file mode 100644 index 0000000..f373930 --- /dev/null +++ b/backend/database/migrations/20261028120000-create-wechat-gateway-bindings.js @@ -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'); + }, +}; diff --git a/backend/database/migrations/20261028121000-drop-workstation-login-code.js b/backend/database/migrations/20261028121000-drop-workstation-login-code.js new file mode 100644 index 0000000..910db4d --- /dev/null +++ b/backend/database/migrations/20261028121000-drop-workstation-login-code.js @@ -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, + }); + }, +}; diff --git a/backend/database/migrations/20261028121500-add-subject-member-temp-user.js b/backend/database/migrations/20261028121500-add-subject-member-temp-user.js new file mode 100644 index 0000000..fc990ff --- /dev/null +++ b/backend/database/migrations/20261028121500-add-subject-member-temp-user.js @@ -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'); + }, +}; diff --git a/backend/test/app/controller/wx-gateway.test.js b/backend/test/app/controller/wx-gateway.test.js new file mode 100644 index 0000000..a9842a1 --- /dev/null +++ b/backend/test/app/controller/wx-gateway.test.js @@ -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(' { + 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)); + }); +}); diff --git a/desktop/LoginWindow.xaml.cs b/desktop/LoginWindow.xaml.cs index 5a590be..817fdba 100644 --- a/desktop/LoginWindow.xaml.cs +++ b/desktop/LoginWindow.xaml.cs @@ -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`。 /// @@ -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 } } - /// 长轮询:确认了就登录;码过期(refreshed)就换一张继续等 - private async Task PollWechatAsync(ApiClient api, string code, CancellationToken ct) + /// 长轮询:确认了就登录;二维码过期(expired)就换一张继续等 + 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 = "二维码已刷新,请重新扫码"; } diff --git a/desktop/Services/ApiClient.cs b/desktop/Services/ApiClient.cs index 1f754f8..6b04b03 100644 --- a/desktop/Services/ApiClient.cs +++ b/desktop/Services/ApiClient.cs @@ -61,11 +61,11 @@ public sealed record ApiSubject(int Id, string Name, string? ExpireAt, bool Expi /// 登录结果:会话 + 用户 + 可进入的主体列表(后端登录接口一起下发) public sealed record LoginResult(Session Session, ApiUser User, IReadOnlyList Subjects); -/// 微信扫码登录:发码结果 -public sealed record WechatTicket(string Code, string QrUrl); +/// 微信扫码登录:发码结果(`State` 是本地会话 id,轮询用它;`QrUrl` 是本站画的二维码图片) +public sealed record WechatTicket(string State, string QrUrl); -/// 微信扫码登录:轮询结果 -public sealed record WechatPollResult(string Status, Session? Session, ApiUser? User, string? Code, string? QrUrl, IReadOnlyList Subjects); +/// 微信扫码登录:轮询结果(`Message` 只在失败时有值) +public sealed record WechatPollResult(string Status, Session? Session, ApiUser? User, string? Message = null); /// 本机设备(scanners 表的一行,够桌面端展示用) 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); } - /// 微信扫码登录:发一个码(`GET /api/wechat/login`,无需令牌) + /// 微信扫码登录:申请一张二维码(`POST /api/web/auth/wechat-gateway/qrcode`,无需令牌) public async Task 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); } - /// 微信扫码登录:轮询一次(`GET /api/wechat/login?code=&wait=`) - public async Task PollWechatLoginAsync(string code, int waitSeconds, CancellationToken ct = default) + /// 微信扫码登录:轮询一次(`GET /api/web/auth/wechat-gateway/login?state=&wait=`) + public async Task 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()); + 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()); + return new WechatPollResult(status, session, user); } /// 拉图片字节(二维码用;`qrcode.gif` 返回 GIF,WPF 能直接显示) @@ -840,6 +843,23 @@ public sealed class ApiClient return result; } + /// + /// 拉取本机的**面单摄像头识别配置**(设备令牌;`GET /api/scanner/label-cameras`)。 + /// + /// 服务端只返回本主体、散单、启用中工作台里被设为「面单摄像头」的那几路, + /// 附上报通道 + 录像机凭据(含密码)。`revision` 是内容指纹,用来判断要不要重建识别任务。 + /// + public async Task 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; + } + // ==================== 内部:请求 ==================== /// 带用户令牌 + 主体 header 的请求 diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts index b5292c6..df1f2b4 100644 --- a/frontend/src/api/client.ts +++ b/frontend/src/api/client.ts @@ -37,10 +37,12 @@ interface RequestOptions { body?: unknown; /** 带上令牌(默认带;登录等公开接口可传 false) */ auth?: boolean; + /** 中断信号:长轮询(扫码登录 / 绑定 / 工作台登入)在切面板、关弹窗时要能立刻断开 */ + signal?: AbortSignal; } async function request(path: string, options: RequestOptions = {}): Promise { - const { method = 'GET', body, auth = true } = options; + const { method = 'GET', body, auth = true, signal } = options; const headers: Record = {}; if (body !== undefined) headers['Content-Type'] = 'application/json'; if (auth) { @@ -55,6 +57,7 @@ async function request(path: string, options: RequestOptions = {}): Promise | null = null; diff --git a/frontend/src/api/subjectApi.ts b/frontend/src/api/subjectApi.ts index f906824..0afaf80 100644 --- a/frontend/src/api/subjectApi.ts +++ b/frontend/src/api/subjectApi.ts @@ -44,45 +44,54 @@ export function updateSubjectMemberRole( return api.put(`/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 { - return api.post(`/api/web/subjects/${id}/members/${memberId}/bind-code`, {}); +/** 生成「扫码绑定」二维码(微信登录网关;成员用微信扫码即绑定) */ +export function createMemberBindQr(id: number, memberId: number): Promise { + return api.post(`/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 { - return api.get(`/api/subject/member-bind?code=${encodeURIComponent(code)}`, { auth: false }); +/** 长轮询绑定结果(`wait` 秒内有人确认就立即返回) */ +export function fetchMemberBindStatus( + id: number, + memberId: number, + state: string, + wait = 0, + signal?: AbortSignal, +): Promise { + const query = new URLSearchParams({ state }); + if (wait) query.set('wait', String(wait)); + return api.get( + `/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 { + return api.post(`/api/web/subjects/${id}/members/${memberId}/unbind`, {}); } // ---------------- 续期:套餐 + 订单 ---------------- diff --git a/frontend/src/views/LoginView.vue b/frontend/src/views/LoginView.vue index 9ef7c5c..6a10ed4 100644 --- a/frontend/src/views/LoginView.vue +++ b/frontend/src/views/LoginView.vue @@ -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 { diff --git a/frontend/src/views/ProfileView.vue b/frontend/src/views/ProfileView.vue index b74fcb3..d45fa0f 100644 --- a/frontend/src/views/ProfileView.vue +++ b/frontend/src/views/ProfileView.vue @@ -1,10 +1,19 @@