对接 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>
813 lines
28 KiB
JavaScript
813 lines
28 KiB
JavaScript
'use strict';
|
||
|
||
const { Service } = require('egg');
|
||
const crypto = require('crypto');
|
||
const { Op } = require('sequelize');
|
||
|
||
/** 网关页面的场景(文档:`bind` 绑定页 / `login` 登录页) */
|
||
const SCENE = {
|
||
LOGIN: 'login',
|
||
BIND: 'bind',
|
||
};
|
||
|
||
/**
|
||
* 本地扫码会话的用途 —— 决定「收到网关通知后怎么落地」
|
||
* - `login`:登录页扫码登录(签发用户 JWT)
|
||
* - `bind`:个人中心绑定微信(写 `wechat_gateway_bindings`)
|
||
* - `workstation`:扫码登入工作台(写 `workstation_login_records`)
|
||
* - `member`:主体成员扫码绑定(绑到已有账号 / 自动建号)
|
||
*/
|
||
const PURPOSE = {
|
||
LOGIN: 'login',
|
||
BIND: 'bind',
|
||
WORKSTATION: 'workstation',
|
||
MEMBER: 'member',
|
||
};
|
||
|
||
const STATUS = {
|
||
PENDING: 'pending',
|
||
CONFIRMED: 'confirmed',
|
||
FAILED: 'failed',
|
||
};
|
||
|
||
/** 会话被取走后最多再留几秒(确认状态只需要撑住正在挂着的长轮询) */
|
||
const TAKEN_TTL = 300;
|
||
|
||
/**
|
||
* 微信登录网关(https://gateway.gztbyc.com/#/docs)
|
||
*
|
||
* 网关做的是「公众号网页授权」:应用服务端申请**临时码** → 前端画成二维码 →
|
||
* 用户用手机微信扫码、在网关页确认(snsapi_base 静默拿 openid)→
|
||
* 网关带签名 `POST` 通知应用(`notifyPath`),应用再落地自己的业务。
|
||
*
|
||
* 本 service 只做三件事:
|
||
* 1. 调网关接口(`/api/auth/temp-code`),并把「这次扫码要干什么」记进本地会话;
|
||
* 2. 校验网关回调的签名(HMAC-SHA256,密钥是 `sha256(appSecret)` 的十六进制);
|
||
* 3. 把回调结果交回给正在长轮询的浏览器/桌面端(Redis 会话 + 发布订阅)。
|
||
*
|
||
* 会话存 Redis(多实例共享);没有 Redis(本地开发/单测)时退化成进程内 Map。
|
||
*/
|
||
class WxGatewayService extends Service {
|
||
get cfg() {
|
||
return this.app.config.wxGateway || {};
|
||
}
|
||
|
||
/** 没配 appKey/appSecret 就直接不可用(调用方据此隐藏入口 / 返回 503) */
|
||
get enabled() {
|
||
return Boolean(this.cfg.appKey && this.cfg.appSecret);
|
||
}
|
||
|
||
get redis() {
|
||
return this.app.redis || null;
|
||
}
|
||
|
||
/** 本地会话有效期(秒) */
|
||
get sceneTtl() {
|
||
return Number(this.cfg.sceneTtl || 660);
|
||
}
|
||
|
||
/** 有没有 Redis(没有就走进程内 Map,只适合单实例/本地开发) */
|
||
get hasRedis() {
|
||
return Boolean(this.redis);
|
||
}
|
||
|
||
assertEnabled() {
|
||
if (!this.enabled) {
|
||
this.ctx.throw(503, '未配置微信登录网关(WX_GATEWAY_APP_KEY / WX_GATEWAY_APP_SECRET)');
|
||
}
|
||
}
|
||
|
||
sessionKey(state) {
|
||
return `${this.app.config.cache.prefix}wxgw:sess:${state}`;
|
||
}
|
||
|
||
channel(state) {
|
||
return `${this.app.config.cache.prefix}wxgw:chan:${state}`;
|
||
}
|
||
|
||
/** 32 位十六进制随机串:既是本地会话 id,也原样作为网关的 `state` 回传 */
|
||
newState() {
|
||
return crypto.randomBytes(16).toString('hex');
|
||
}
|
||
|
||
// ==================== 调网关接口 ====================
|
||
|
||
/**
|
||
* 调网关的 `/api/*`(凭证放 header,见文档)
|
||
* @param {string} path 形如 `/api/auth/temp-code`
|
||
* @param {object} payload JSON body
|
||
* @return {Promise<object>} 网关返回的 `data`
|
||
*/
|
||
async requestApi(path, payload) {
|
||
this.assertEnabled();
|
||
|
||
const url = `${this.cfg.baseUrl}${path}`;
|
||
const options = {
|
||
method: 'POST',
|
||
headers: {
|
||
'Content-Type': 'application/json',
|
||
'X-App-Key': this.cfg.appKey,
|
||
'X-App-Secret': this.cfg.appSecret,
|
||
},
|
||
data: payload || {},
|
||
contentType: 'json',
|
||
dataType: 'json',
|
||
timeout: Number(this.cfg.timeout || 8000),
|
||
};
|
||
|
||
let res = null;
|
||
try {
|
||
res = await this.app.curl(url, options);
|
||
} catch (err) {
|
||
this.ctx.logger.error('[wx-gateway] 请求 %s 失败: %s', path, err.message);
|
||
this.ctx.throw(502, `微信登录网关不可用:${err.message}`);
|
||
}
|
||
|
||
const body = (res && res.data) || {};
|
||
const status = Number(res && res.status) || 0;
|
||
if (status < 200 || status >= 300 || Number(body.code) !== 0) {
|
||
const message = body.message || body.msg || `HTTP ${status}`;
|
||
this.ctx.logger.warn('[wx-gateway] 请求 %s 被拒绝(%s): %j', path, message, body);
|
||
this.ctx.throw(502, `微信登录网关:${message}`);
|
||
}
|
||
|
||
return body.data || {};
|
||
}
|
||
|
||
/**
|
||
* 申请临时码(`POST /api/auth/temp-code`)
|
||
* @param {object} params { scene, state }
|
||
* @return {Promise<object>} { pageUrl, tempCode, expiresIn, ... }
|
||
*/
|
||
async createTempCode({ scene, state } = {}) {
|
||
const data = await this.requestApi('/api/auth/temp-code', { scene, state });
|
||
if (!data.pageUrl) this.ctx.throw(502, '微信登录网关没有返回二维码地址');
|
||
return data;
|
||
}
|
||
|
||
/**
|
||
* 兑换绑定码拿权威信息(`POST /api/auth/verify`,一次一用;有需要时再用)
|
||
* @param {string} bindCode 通知里的 bindCode
|
||
* @return {Promise<object>}
|
||
*/
|
||
async verifyBindCode(bindCode) {
|
||
return this.requestApi('/api/auth/verify', { bindCode: String(bindCode || '') });
|
||
}
|
||
|
||
// ==================== 本地扫码会话 ====================
|
||
|
||
/**
|
||
* 开一个扫码会话:先建本地会话,再向网关申请临时码(临时码是一次性的,过 10 分钟作废)
|
||
*
|
||
* @param {object} params
|
||
* @param {string} params.purpose PURPOSE.*
|
||
* @param {string} params.scene SCENE.*
|
||
* @param {object} [params.payload] 落地时要用到的上下文(如 workstationId / userId)
|
||
* @return {Promise<{state:string, pageUrl:string, expiresIn:number}>}
|
||
*/
|
||
async openSession({ purpose, scene, payload } = {}) {
|
||
this.assertEnabled();
|
||
|
||
const state = this.newState();
|
||
const data = await this.createTempCode({ scene, state });
|
||
|
||
const session = {
|
||
status: STATUS.PENDING,
|
||
purpose,
|
||
scene,
|
||
pageUrl: String(data.pageUrl),
|
||
tempCode: data.tempCode ? String(data.tempCode) : null,
|
||
payload: payload || {},
|
||
createdAt: Date.now(),
|
||
};
|
||
await this.writeSession(state, session, this.sceneTtl);
|
||
|
||
this.ctx.logger.info(
|
||
'[wx-gateway] 已申请临时码:purpose=%s scene=%s state=%s',
|
||
purpose, scene, state,
|
||
);
|
||
|
||
return {
|
||
state,
|
||
pageUrl: session.pageUrl,
|
||
tempCode: session.tempCode,
|
||
expiresIn: this.sceneTtl,
|
||
scene,
|
||
};
|
||
}
|
||
|
||
/** 二维码里要编码的内容(网关页面地址);会话没了返回空串 */
|
||
async pageUrlOf(state) {
|
||
const session = await this.readSession(state);
|
||
return session && session.pageUrl ? session.pageUrl : '';
|
||
}
|
||
|
||
async readSession(state) {
|
||
if (!state) return null;
|
||
const raw = await this.cacheGet(this.sessionKey(state));
|
||
if (!raw) return null;
|
||
try {
|
||
return JSON.parse(raw);
|
||
} catch (err) {
|
||
this.ctx.logger.warn('[wx-gateway] 会话内容损坏(%s): %s', state, err.message);
|
||
return null;
|
||
}
|
||
}
|
||
|
||
async writeSession(state, session, ttl) {
|
||
await this.cacheSet(this.sessionKey(state), JSON.stringify(session), ttl);
|
||
}
|
||
|
||
async dropSession(state) {
|
||
await this.cacheDel(this.sessionKey(state));
|
||
}
|
||
|
||
/** 收到通知 → 标记成功并唤醒长轮询 */
|
||
async confirmSession(state, result) {
|
||
const session = await this.readSession(state);
|
||
if (!session) return false;
|
||
if (session.status === STATUS.CONFIRMED) return true;
|
||
|
||
session.status = STATUS.CONFIRMED;
|
||
session.result = result || {};
|
||
session.doneAt = Date.now();
|
||
await this.writeSession(state, session, TAKEN_TTL);
|
||
await this.publish(state);
|
||
return true;
|
||
}
|
||
|
||
/** 收到通知但没法落地(微信没绑定账号、账号被禁用…)→ 标记失败并唤醒长轮询 */
|
||
async failSession(state, message) {
|
||
const session = await this.readSession(state);
|
||
if (!session) return false;
|
||
|
||
session.status = STATUS.FAILED;
|
||
session.message = String(message || '扫码失败,请重试');
|
||
session.doneAt = Date.now();
|
||
await this.writeSession(state, session, TAKEN_TTL);
|
||
await this.publish(state);
|
||
return true;
|
||
}
|
||
|
||
/**
|
||
* 长轮询一次会话
|
||
*
|
||
* - 已确认 → `{ status:'confirmed', ...result }`(取走即删,一次性)
|
||
* - 已失败 → `{ status:'failed', message }`
|
||
* - 会话不存在/已过期 → `{ status:'expired' }`(前端重新申请一张)
|
||
* - 还在等扫码 → 挂起最多 `wait` 秒(受 `WX_GATEWAY_POLL_WAIT` 限制)后返回 `{ status:'pending' }`
|
||
* - 客户端提前断开(切面板/关页签)→ `{ status:'aborted' }`,不写响应
|
||
*
|
||
* @param {string} state 本地会话 id
|
||
* @param {object} [options] { wait 挂起秒数 }
|
||
* @return {Promise<object>}
|
||
*/
|
||
async awaitSession(state, { wait = 0 } = {}) {
|
||
if (!state) return { status: 'expired' };
|
||
|
||
const maxWait = Number(this.cfg.pollWait || 55);
|
||
const seconds = Math.min(Math.max(Number(wait) || 0, 0), maxWait);
|
||
|
||
// 先订阅、再查状态:避免「刚查完还是 pending,紧接着就被确认」的那一下漏掉
|
||
const subscriber = seconds > 0 ? this.subscriber() : null;
|
||
if (subscriber) {
|
||
try {
|
||
await subscriber.subscribe(this.channel(state));
|
||
} catch (err) {
|
||
this.ctx.logger.warn('[wx-gateway] 订阅失败: %s', err.message);
|
||
}
|
||
}
|
||
|
||
const closed = seconds > 0 ? this.clientClosed() : null;
|
||
|
||
try {
|
||
const first = await this.readSession(state);
|
||
if (!first) return { status: 'expired' };
|
||
if (first.status !== STATUS.PENDING) return await this.takeSession(state, first);
|
||
if (!seconds) return { status: 'pending' };
|
||
|
||
const hit = await this.waitPublish(subscriber, seconds * 1000, closed);
|
||
if (hit === 'closed') {
|
||
this.ctx.logger.info('[wx-gateway] 客户端已断开,停止等待会话 %s', state);
|
||
return { status: 'aborted' };
|
||
}
|
||
if (hit) {
|
||
const after = await this.readSession(state);
|
||
if (after && after.status !== STATUS.PENDING) return await this.takeSession(state, after);
|
||
}
|
||
return { status: 'pending' };
|
||
} finally {
|
||
if (subscriber) subscriber.disconnect();
|
||
}
|
||
}
|
||
|
||
/** 取走会话结果(一次性) */
|
||
async takeSession(state, session) {
|
||
await this.dropSession(state);
|
||
|
||
if (session.status === STATUS.CONFIRMED) {
|
||
return Object.assign({ status: 'confirmed' }, session.result || {});
|
||
}
|
||
return {
|
||
status: 'failed',
|
||
message: session.message || '扫码失败,请重试',
|
||
};
|
||
}
|
||
|
||
// ==================== 网关回调 ====================
|
||
|
||
/**
|
||
* 校验网关回调的签名与时间戳
|
||
*
|
||
* 文档给的算法(Node.js 示例,两边都用 `sha256(appSecret)` 当密钥):
|
||
* `HMAC-SHA256(sha256hex(appSecret), [appKey, userId, bindCode, timestamp, nonce].join('.'))`
|
||
*
|
||
* @param {object} body 通知体
|
||
* @return {{ok:boolean, message?:string}}
|
||
*/
|
||
verifyNotify(body = {}) {
|
||
if (!this.enabled) return { ok: false, message: '未配置微信登录网关' };
|
||
|
||
if (String(body.appKey || '') !== String(this.cfg.appKey)) {
|
||
return { ok: false, message: 'appKey 不是本应用的' };
|
||
}
|
||
|
||
const timestamp = Number(body.timestamp);
|
||
const skewMs = Number(this.cfg.notifySkew || 300) * 1000;
|
||
if (!Number.isFinite(timestamp) || Math.abs(Date.now() - timestamp) > skewMs) {
|
||
return { ok: false, message: '通知已过期' };
|
||
}
|
||
|
||
const sign = String(body.sign || '').toLowerCase();
|
||
const expected = this.signOf(body);
|
||
if (!sign || sign.length !== expected.length) return { ok: false, message: '签名不匹配' };
|
||
if (!crypto.timingSafeEqual(Buffer.from(sign, 'utf8'), Buffer.from(expected, 'utf8'))) {
|
||
return { ok: false, message: '签名不匹配' };
|
||
}
|
||
|
||
return { ok: true };
|
||
}
|
||
|
||
/** 通知签名(测试里也用它造一份合法签名) */
|
||
signOf(body = {}) {
|
||
const secretHash = crypto.createHash('sha256').update(String(this.cfg.appSecret || '')).digest('hex');
|
||
const message = [ body.appKey, body.userId, body.bindCode, body.timestamp, body.nonce ].join('.');
|
||
return crypto.createHmac('sha256', secretHash).update(message).digest('hex');
|
||
}
|
||
|
||
/**
|
||
* 处理网关回调:按会话用途落地
|
||
*
|
||
* 返回值只用来写日志/回包,**真正结果通过会话交给长轮询那一侧**
|
||
* (网关只管通知,浏览器那边看不到这次 HTTP 响应)。
|
||
*
|
||
* @param {object} body 通知体(已验签)
|
||
* @return {Promise<object>}
|
||
*/
|
||
async handleNotify(body = {}) {
|
||
const state = String(body.state || '').trim();
|
||
const session = state ? await this.readSession(state) : null;
|
||
|
||
if (!session) {
|
||
this.ctx.logger.warn('[wx-gateway] 通知找不到会话(二维码可能已过期):state=%s', state);
|
||
return { ignored: 'session_expired' };
|
||
}
|
||
if (session.status !== STATUS.PENDING) {
|
||
this.ctx.logger.info('[wx-gateway] 会话 %s 已是 %s,忽略重复通知', state, session.status);
|
||
return { ignored: `session_${session.status}` };
|
||
}
|
||
|
||
const openid = String(body.openid || '').trim();
|
||
if (!openid) {
|
||
await this.failSession(state, '网关未返回 openid,请重新扫码');
|
||
return { failed: 'no_openid' };
|
||
}
|
||
|
||
try {
|
||
if (session.purpose === PURPOSE.BIND) {
|
||
return await this.handleBind(state, session, body, openid);
|
||
}
|
||
if (session.purpose === PURPOSE.MEMBER) {
|
||
return await this.handleMemberBind(state, session, body, openid);
|
||
}
|
||
return await this.handleLogin(state, session, body, openid);
|
||
} catch (err) {
|
||
// 记全 name + stack:Sequelize 的 "Validation error" 只有一句 message,光看日志没法定位
|
||
this.ctx.logger.error(
|
||
'[wx-gateway] 处理通知失败(%s):%s %s\n%s',
|
||
state, err.name || 'Error', err.message, err.stack || '',
|
||
);
|
||
await this.failSession(state, err.message || '扫码失败,请重试');
|
||
return { failed: err.message };
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 成员扫码绑定:把「扫码的微信」落到管理员指定的那名成员上
|
||
*
|
||
* 两种情形(具体落库在 `service/subject.js#bindMemberWithWechat`):
|
||
* - 这个微信已经是某个平台账号的登录方式 → 成员直接绑到那个账号(自动建的临时账号删掉);
|
||
* - 这个微信还没有平台账号 → 自动给这名成员建号,微信成为它的登录方式。
|
||
*/
|
||
async handleMemberBind(state, session, body, openid) {
|
||
const subjectId = Number(session.payload && session.payload.subjectId);
|
||
const memberId = Number(session.payload && session.payload.memberId);
|
||
if (!subjectId || !memberId) {
|
||
await this.failSession(state, '绑定会话已失效,请重新扫码');
|
||
return { failed: 'no_member' };
|
||
}
|
||
|
||
// 这个微信已经绑到哪个平台账号?(没有就是 null,走「自动建号」那条)
|
||
const binding = await this.findBinding(openid);
|
||
let boundUserId = binding ? Number(binding.userId) : null;
|
||
if (boundUserId) {
|
||
const user = await this.ctx.service.user.findById(boundUserId);
|
||
if (!user) {
|
||
boundUserId = null;
|
||
} else if (Number(user.status) !== 1) {
|
||
await this.failSession(state, '这个微信绑定的账号已被禁用,请联系管理员');
|
||
return { failed: 'user_disabled' };
|
||
}
|
||
}
|
||
|
||
const result = await this.ctx.service.subject.bindMemberWithWechat({
|
||
subjectId,
|
||
memberId,
|
||
openid,
|
||
unionid: body.unionid ? String(body.unionid) : null,
|
||
boundUserId,
|
||
});
|
||
|
||
await this.confirmSession(state, result);
|
||
return { member: memberId, userId: result.userId, autoCreated: result.autoCreated };
|
||
}
|
||
|
||
/** 绑定微信:把 openid 落到发起绑定的那个账号上 */
|
||
async handleBind(state, session, body, openid) {
|
||
const userId = Number(session.payload && session.payload.userId);
|
||
if (!userId) {
|
||
await this.failSession(state, '绑定会话已失效,请重新扫码');
|
||
return { failed: 'no_user' };
|
||
}
|
||
|
||
const exists = await this.findBinding(openid);
|
||
if (exists && Number(exists.userId) !== userId) {
|
||
const other = await this.ctx.service.user.findById(exists.userId);
|
||
if (other && Number(other.status) === 1) {
|
||
const who = other.nickname || other.username || `用户${other.id}`;
|
||
await this.failSession(state, `这个微信已经绑定了其他账号(${who}):请用那个账号登录后在「个人中心 → 微信绑定」解绑,或联系管理员处理`);
|
||
return { failed: 'openid_bound' };
|
||
}
|
||
|
||
// 原账号已删除 / 被禁用:这条绑定已经"用不了"了,直接把微信改绑到当前账号
|
||
this.ctx.logger.warn(
|
||
'[wx-gateway] 微信 %s 原绑定账号 %s 不可用(不存在或已禁用),改绑到 userId=%s',
|
||
openid, exists.userId, userId,
|
||
);
|
||
}
|
||
|
||
const mine = await this.findBindingByUser(userId);
|
||
if (mine && String(mine.openid) !== openid) {
|
||
await this.failSession(state, '当前账号已绑定其他微信,请先解绑后再绑新的');
|
||
return { failed: 'user_bound' };
|
||
}
|
||
|
||
const binding = await this.upsertBinding({
|
||
userId,
|
||
openid,
|
||
unionid: body.unionid ? String(body.unionid) : null,
|
||
bindScene: String(body.scene || SCENE.BIND),
|
||
});
|
||
|
||
this.ctx.logger.info('[wx-gateway] 绑定微信成功:userId=%s openid=%s', userId, openid);
|
||
await this.confirmSession(state, { binding: this.presentBinding(binding) });
|
||
return { bound: userId };
|
||
}
|
||
|
||
/** 登录 / 工作台登入:openid → 平台账号,再按用途落地 */
|
||
async handleLogin(state, session, body, openid) {
|
||
const binding = await this.findBinding(openid);
|
||
if (!binding) {
|
||
const message = '这个微信还没绑定平台账号:请先用账号密码登录,在「个人中心 → 微信绑定」绑好后重新扫码';
|
||
await this.failSession(state, message);
|
||
return { failed: 'not_bound' };
|
||
}
|
||
|
||
const user = await this.ctx.service.user.findById(binding.userId);
|
||
if (!user) {
|
||
await this.failSession(state, '绑定的平台账号不存在,请联系管理员');
|
||
return { failed: 'user_missing' };
|
||
}
|
||
if (Number(user.status) !== 1) {
|
||
await this.failSession(state, '账号已被禁用,请联系管理员');
|
||
return { failed: 'user_disabled' };
|
||
}
|
||
|
||
await this.touchBinding(binding);
|
||
|
||
if (session.purpose === PURPOSE.WORKSTATION) {
|
||
return await this.handleWorkstationLogin(state, session, user);
|
||
}
|
||
|
||
// 登录页:这里只记「谁登录」,令牌等浏览器来取的时候再签(Redis 里不放令牌)
|
||
await this.confirmSession(state, { userId: Number(user.id) });
|
||
this.ctx.logger.info('[wx-gateway] 扫码登录成功:%s(id=%s)', user.username, user.id);
|
||
return { login: Number(user.id) };
|
||
}
|
||
|
||
/** 工作台登入:工作台由会话携带,主体/状态校验在 service 里 */
|
||
async handleWorkstationLogin(state, session, user) {
|
||
const workstationId = Number(session.payload && session.payload.workstationId);
|
||
const workstation = workstationId
|
||
? await this.app.model.Workstation.findByPk(workstationId)
|
||
: null;
|
||
|
||
if (!workstation) {
|
||
await this.failSession(state, '工作台不存在或已被删除');
|
||
return { failed: 'workstation_missing' };
|
||
}
|
||
|
||
const data = await this.ctx.service.workstationLogin.loginByUser({ user, workstation });
|
||
|
||
await this.confirmSession(state, {
|
||
workstation: data.workstation,
|
||
isMember: data.isMember,
|
||
member: data.member,
|
||
name: data.name,
|
||
record: data.record,
|
||
});
|
||
return { workstation: Number(workstation.id), user: Number(user.id) };
|
||
}
|
||
|
||
// ==================== 绑定关系 ====================
|
||
|
||
get Binding() {
|
||
return this.app.model.WechatGatewayBinding;
|
||
}
|
||
|
||
/** 按 openid 反查绑定(一个 openid 只能绑一个账号) */
|
||
async findBinding(openid) {
|
||
if (!this.Binding || !openid) return null;
|
||
return this.Binding.findOne({
|
||
where: { appKey: this.cfg.appKey, openid: String(openid) },
|
||
});
|
||
}
|
||
|
||
/** 某账号在当前应用下的绑定(一个账号只留一个微信) */
|
||
async findBindingByUser(userId) {
|
||
if (!this.Binding || !userId) return null;
|
||
return this.Binding.findOne({
|
||
where: { appKey: this.cfg.appKey, userId: Number(userId) },
|
||
});
|
||
}
|
||
|
||
/** 当前账号的绑定列表(给个人中心展示) */
|
||
async listBindings(userId) {
|
||
if (!this.Binding || !userId) return [];
|
||
const rows = await this.Binding.findAll({
|
||
where: { appKey: this.cfg.appKey, userId: Number(userId) },
|
||
order: [[ 'id', 'DESC' ]],
|
||
});
|
||
return rows.map(row => this.presentBinding(row));
|
||
}
|
||
|
||
/**
|
||
* 运维视角:按 `openid` / `userId` 查绑定(**含已软删的**),带账号状态
|
||
*
|
||
* 用途:「这个微信绑在谁身上」「为什么他绑不了」时一眼看明白
|
||
* @param {object} params { openid?, userId? }
|
||
*/
|
||
async listBindingsForOps({ openid, userId } = {}) {
|
||
if (!this.Binding) return [];
|
||
|
||
const where = { appKey: this.cfg.appKey };
|
||
if (openid) where.openid = String(openid);
|
||
if (userId) where.userId = Number(userId);
|
||
if (!openid && !userId) this.ctx.throw(422, 'openid 或 userId 至少要有一个');
|
||
|
||
const rows = await this.Binding.findAll({ where, order: [[ 'id', 'DESC' ]], paranoid: false });
|
||
const userIds = [ ...new Set(rows.map(row => Number(row.userId)).filter(Boolean)) ];
|
||
const users = userIds.length
|
||
? await this.app.model.User.findAll({
|
||
where: { id: { [Op.in]: userIds } },
|
||
attributes: [ 'id', 'username', 'nickname', 'status' ],
|
||
paranoid: false,
|
||
})
|
||
: [];
|
||
const byId = new Map(users.map(user => [ Number(user.id), user ]));
|
||
|
||
return rows.map(row => {
|
||
const data = row.toJSON();
|
||
const user = byId.get(Number(data.userId));
|
||
return Object.assign(this.presentBinding(row), {
|
||
userId: data.userId ? Number(data.userId) : null,
|
||
deletedAt: data.deletedAt || null,
|
||
user: user ? {
|
||
id: Number(user.id),
|
||
username: user.username,
|
||
nickname: user.nickname || null,
|
||
status: Number(user.status),
|
||
deleted: Boolean(user.deletedAt),
|
||
} : null,
|
||
});
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 运维:强制解绑任意一条绑定(不校验归属)
|
||
*
|
||
* 给「微信绑在前员工/已停用账号上,本人又拿不到那个账号」兜底;解绑后该微信可以重新绑给别人。
|
||
* @param {number} id 绑定记录 id
|
||
*/
|
||
async forceUnbind(id) {
|
||
const binding = this.Binding
|
||
? await this.Binding.findByPk(Number(id), { paranoid: false })
|
||
: null;
|
||
if (!binding) this.ctx.throw(404, '绑定记录不存在');
|
||
|
||
if (!binding.deletedAt) await binding.destroy();
|
||
this.ctx.logger.warn('[wx-gateway] 运维强制解绑:id=%s userId=%s openid=%s',
|
||
binding.id, binding.userId, binding.openid);
|
||
return { id: Number(binding.id), userId: Number(binding.userId), openid: binding.openid };
|
||
}
|
||
|
||
/** 解绑(只删自己的;找不到当 404) */
|
||
async unbind(userId, id) {
|
||
const binding = this.Binding
|
||
? await this.Binding.findOne({ where: { id: Number(id), userId: Number(userId) } })
|
||
: null;
|
||
if (!binding) this.ctx.throw(404, '绑定关系不存在');
|
||
|
||
await binding.destroy();
|
||
this.ctx.logger.info('[wx-gateway] 解绑微信:userId=%s openid=%s', userId, binding.openid);
|
||
return { id: Number(id) };
|
||
}
|
||
|
||
async upsertBinding({ userId, openid, unionid = null, bindScene = SCENE.BIND } = {}) {
|
||
const existing = await this.findBinding(openid);
|
||
|
||
if (existing) {
|
||
await existing.update({
|
||
userId: Number(userId),
|
||
unionid: unionid || existing.unionid || null,
|
||
bindScene,
|
||
});
|
||
return existing;
|
||
}
|
||
|
||
// 之前解绑过的同一个微信(软删行):唯一键 (app_key, openid) 还占着,
|
||
// 直接 create 会撞唯一索引、抛出来只有一句 "Validation error" —— 这里把它复活并改归属。
|
||
const trashed = await this.Binding.findOne({
|
||
where: { appKey: this.cfg.appKey, openid: String(openid) },
|
||
paranoid: false,
|
||
order: [[ 'id', 'DESC' ]],
|
||
});
|
||
if (trashed) {
|
||
if (trashed.deletedAt) await trashed.restore();
|
||
await trashed.update({
|
||
userId: Number(userId),
|
||
unionid: unionid || trashed.unionid || null,
|
||
bindScene,
|
||
});
|
||
this.ctx.logger.info('[wx-gateway] 复用已解绑的绑定记录 id=%s(openid=%s → userId=%s)', trashed.id, openid, userId);
|
||
return trashed;
|
||
}
|
||
|
||
return this.Binding.create({
|
||
userId: Number(userId),
|
||
appKey: this.cfg.appKey,
|
||
openid: String(openid),
|
||
unionid: unionid || null,
|
||
bindScene,
|
||
});
|
||
}
|
||
|
||
/** 记一次「用这个微信登录了」 */
|
||
async touchBinding(binding) {
|
||
try {
|
||
await binding.update({ lastLoginAt: new Date() });
|
||
} catch (err) {
|
||
this.ctx.logger.warn('[wx-gateway] 更新绑定最后登录时间失败: %s', err.message);
|
||
}
|
||
}
|
||
|
||
presentBinding(binding) {
|
||
if (!binding) return null;
|
||
const data = typeof binding.toJSON === 'function' ? binding.toJSON() : binding;
|
||
return {
|
||
id: Number(data.id),
|
||
openid: data.openid,
|
||
unionid: data.unionid || null,
|
||
bindScene: data.bindScene || null,
|
||
lastLoginAt: data.lastLoginAt || null,
|
||
createdAt: data.createdAt || data.created_at || null,
|
||
};
|
||
}
|
||
|
||
// ==================== 缓存 / 长轮询小工具 ====================
|
||
|
||
/** 没有 Redis 时的进程内兜底(本地开发 / 单测) */
|
||
get memory() {
|
||
if (!this._memory) this._memory = new Map();
|
||
return this._memory;
|
||
}
|
||
|
||
async cacheGet(key) {
|
||
if (this.redis) {
|
||
try {
|
||
return await this.redis.get(key);
|
||
} catch (err) {
|
||
this.ctx.logger.warn('[wx-gateway] 读缓存失败,改用进程内存: %s', err.message);
|
||
}
|
||
}
|
||
|
||
const hit = this.memory.get(key);
|
||
if (!hit) return null;
|
||
if (hit.expireAt && hit.expireAt <= Date.now()) {
|
||
this.memory.delete(key);
|
||
return null;
|
||
}
|
||
return hit.value;
|
||
}
|
||
|
||
async cacheSet(key, value, ttl) {
|
||
if (this.redis) {
|
||
try {
|
||
await this.redis.setex(key, Number(ttl) || this.sceneTtl, value);
|
||
return;
|
||
} catch (err) {
|
||
this.ctx.logger.warn('[wx-gateway] 写缓存失败,改用进程内存: %s', err.message);
|
||
}
|
||
}
|
||
this.memory.set(key, { value: String(value), expireAt: Date.now() + (Number(ttl) || this.sceneTtl) * 1000 });
|
||
}
|
||
|
||
async cacheDel(key) {
|
||
if (this.redis) {
|
||
try {
|
||
await this.redis.del(key);
|
||
} catch (err) {
|
||
this.ctx.logger.warn('[wx-gateway] 删缓存失败: %s', err.message);
|
||
}
|
||
}
|
||
this.memory.delete(key);
|
||
}
|
||
|
||
/** 通知「会话状态变了」(长轮询的请求靠它立即醒来) */
|
||
async publish(state) {
|
||
if (!this.redis) return;
|
||
try {
|
||
await this.redis.publish(this.channel(state), 'done');
|
||
} catch (err) {
|
||
this.ctx.logger.warn('[wx-gateway] 广播会话变化失败: %s', err.message);
|
||
}
|
||
}
|
||
|
||
/** 订阅用的独立连接(用完即 disconnect) */
|
||
subscriber() {
|
||
const redis = this.app.redis;
|
||
if (!redis || typeof redis.duplicate !== 'function') return null;
|
||
return redis.duplicate();
|
||
}
|
||
|
||
/** 等一条消息;`closed` 提前 resolve 就返回 'closed',超时返回 null */
|
||
waitPublish(subscriber, waitMs, closed) {
|
||
const wait = new Promise(resolve => {
|
||
if (!subscriber) {
|
||
setTimeout(() => resolve(null), waitMs);
|
||
return;
|
||
}
|
||
let done = false;
|
||
const finish = value => {
|
||
if (done) return;
|
||
done = true;
|
||
clearTimeout(timer);
|
||
resolve(value);
|
||
};
|
||
const timer = setTimeout(() => finish(null), waitMs);
|
||
subscriber.on('message', () => finish('done'));
|
||
});
|
||
|
||
return closed ? Promise.race([ wait, closed ]) : wait;
|
||
}
|
||
|
||
/** 客户端断开(页面导航 / fetch abort)时 resolve 'closed' */
|
||
clientClosed() {
|
||
const res = this.ctx && this.ctx.res;
|
||
if (!res || typeof res.on !== 'function') return null;
|
||
|
||
return new Promise(resolve => {
|
||
const onClose = () => {
|
||
res.removeListener('close', onClose);
|
||
// 响应正常写完后 close 也会触发,那种不算断开
|
||
if (!res.writableEnded) resolve('closed');
|
||
};
|
||
res.on('close', onClose);
|
||
});
|
||
}
|
||
}
|
||
|
||
module.exports = WxGatewayService;
|
||
module.exports.SCENE = SCENE;
|
||
module.exports.PURPOSE = PURPOSE;
|