'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)); }); });