From 4f637f13075a90eeb28d05c83e6c92a3f5665163 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 21 Oct 2026 00:47:11 +0800 Subject: [PATCH] =?UTF-8?q?feat(web):=20=E5=BE=AE=E4=BF=A1=E5=B0=8F?= =?UTF-8?q?=E7=A8=8B=E5=BA=8F=20code2Session=20=E7=99=BB=E5=BD=95=E4=B8=8E?= =?UTF-8?q?=E8=B4=A6=E5=8F=B7=E7=BB=91=E5=AE=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - POST /api/web/auth/wechat/login:code 换 openid,已绑定直接签发令牌, 未绑定自动建平台账号(首登标记 firstTime) - bind / bindings / unbind:登录态下绑定、查询、解绑小程序账号 - wechat_mp_accounts 表 + 迁移;未配置 WX_MP_APPID/SECRET 时本地与单测走 mock - 新增 cors 中间件(小程序 H5 预览直连后端;鉴权只靠 header 令牌,不依赖 cookie) - 补充 wechat-mp 接口单测 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- backend/app/controller/web/wechat_mp.js | 83 ++++++ backend/app/middleware/cors.js | 54 ++++ backend/app/model/wechat_mp_account.js | 35 +++ backend/app/router.js | 6 + backend/app/service/wechat_mp.js | 272 ++++++++++++++++++ backend/config/config.default.js | 22 +- backend/config/config.unittest.js | 6 + ...0261020230000-create-wechat-mp-accounts.js | 48 ++++ backend/test/app/controller/wechat-mp.test.js | 156 ++++++++++ 9 files changed, 681 insertions(+), 1 deletion(-) create mode 100644 backend/app/controller/web/wechat_mp.js create mode 100644 backend/app/middleware/cors.js create mode 100644 backend/app/model/wechat_mp_account.js create mode 100644 backend/app/service/wechat_mp.js create mode 100644 backend/database/migrations/20261020230000-create-wechat-mp-accounts.js create mode 100644 backend/test/app/controller/wechat-mp.test.js diff --git a/backend/app/controller/web/wechat_mp.js b/backend/app/controller/web/wechat_mp.js new file mode 100644 index 0000000..10f6a9e --- /dev/null +++ b/backend/app/controller/web/wechat_mp.js @@ -0,0 +1,83 @@ +'use strict'; + +const { Controller } = require('egg'); + +/** 路径参数转正整数,非法返回 null */ +function toId(value) { + const id = Number(value); + return Number.isInteger(id) && id > 0 ? id : null; +} + +/** + * web 用户端:微信小程序登录 / 绑定 + * + * - `POST /api/web/auth/wechat/login`(公开):`uni.login()` 的 code 换 openid, + * 未绑定就自动建账号;小程序客户端同样要先同意协议(与账号密码登录一致) + * - `POST /api/web/auth/wechat/bind`(需令牌):把微信绑到当前账号 + * - `GET /api/web/auth/wechat/bindings`(需令牌):当前账号的微信绑定 + * - `DELETE /api/web/auth/wechat/bindings/:id`(需令牌):解绑 + */ +class WebWechatMpController extends Controller { + /** + * POST /api/web/auth/wechat/login + * body: `{ code, userInfo?: { nickname, avatar }, client?, agreements? }` + * → `{ token, tokenType, expiresIn, user, subjects, firstTime, wechat, agreements? }` + */ + async login() { + const { ctx } = this; + const body = ctx.request.body || {}; + const client = ctx.service.login.normalizeClient(body.client) || 'mini_program'; + + let accepted = null; + if (ctx.service.login.shouldEnforceAgreement(client)) { + accepted = await ctx.service.login.requireAgreements(body.agreements); + if (!accepted) return; + } + + const result = await ctx.service.wechatMp.login({ + code: body.code, + userInfo: body.userInfo, + }); + + const data = await ctx.service.login.issue(result.user); + data.firstTime = result.firstTime; + data.wechat = result.binding; + if (accepted) { + data.agreements = await ctx.service.login.recordAgreements(result.user, accepted, client); + } + ctx.body = { ok: true, data }; + } + + /** + * POST /api/web/auth/wechat/bind + * body: `{ code, userInfo? }` → 绑定详情 + */ + async bind() { + const { ctx } = this; + const body = ctx.request.body || {}; + const data = await ctx.service.wechatMp.bind(ctx.state.user.id, { + code: body.code, + userInfo: body.userInfo, + }); + ctx.body = { ok: true, data }; + } + + /** GET /api/web/auth/wechat/bindings —— 当前账号的微信绑定 */ + async bindings() { + const { ctx } = this; + const list = await ctx.service.wechatMp.listByUser(ctx.state.user.id); + ctx.body = { ok: true, data: { list } }; + } + + /** DELETE /api/web/auth/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.wechatMp.unbind(ctx.state.user.id, id); + ctx.body = { ok: true, data }; + } +} + +module.exports = WebWechatMpController; diff --git a/backend/app/middleware/cors.js b/backend/app/middleware/cors.js new file mode 100644 index 0000000..140409d --- /dev/null +++ b/backend/app/middleware/cors.js @@ -0,0 +1,54 @@ +'use strict'; + +/** + * 跨域(CORS) + * + * 为什么需要:小程序 H5 预览(7304)与前端 SPA 一样用浏览器发起请求, + * 但接口现在**统一走后端绝对地址**(不再经 Vite 同源代理),所以后端必须回 CORS 头。 + * 小程序真机 / 桌面端 / 扩展走的是原生请求,不受同源策略限制,这段对它们没有影响。 + * + * 配置(`config.cors`): + * - `origins`: `'*'`(默认)或逗号分隔白名单(env `CORS_ORIGINS`),白名单外返回不带 CORS 头; + * - `enable: false` 可整体关闭。 + * + * 说明:鉴权只用 header 里的令牌(Authorization / X-Subject-Id),**不依赖 cookie**, + * 所以不需要 `Access-Control-Allow-Credentials`。 + */ +module.exports = () => { + return async function cors(ctx, next) { + const cfg = ctx.app.config.cors || {}; + + if (cfg.enable !== false) { + const origin = ctx.get('origin'); + const allowed = pickOrigin(origin, cfg.origins); + + if (allowed) { + ctx.set('Access-Control-Allow-Origin', allowed); + ctx.set('Vary', 'Origin'); + ctx.set('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS'); + ctx.set( + 'Access-Control-Allow-Headers', + 'Authorization,Content-Type,X-Subject-Id,X-Access-Token,X-Internal-Token,X-Scanner-Token,X-Pay-Sign', + ); + ctx.set('Access-Control-Max-Age', '86400'); + ctx.set('Access-Control-Expose-Headers', 'Content-Disposition'); + } + } + + // 预检请求直接结束(后续路由没有 OPTIONS,否则会 404 让浏览器判成跨域失败) + if (ctx.method === 'OPTIONS') { + ctx.status = 204; + return; + } + + await next(); + }; +}; + +/** 命中白名单返回要回填的 Origin;`*` 时回显实际 Origin(没有 Origin 就不加头) */ +function pickOrigin(origin, origins) { + if (!origin) return ''; + const list = Array.isArray(origins) ? origins : []; + if (list.includes('*')) return '*'; + return list.includes(origin) ? origin : ''; +} diff --git a/backend/app/model/wechat_mp_account.js b/backend/app/model/wechat_mp_account.js new file mode 100644 index 0000000..ae05909 --- /dev/null +++ b/backend/app/model/wechat_mp_account.js @@ -0,0 +1,35 @@ +'use strict'; + +/** + * 微信小程序授权账号(wechat_mp_accounts) + * + * 一行 = 某个小程序 appid 下的一个 openid,以及它绑定的平台账号(`user_id`)。 + * 解绑后 `user_id` 置空,记录保留(重新绑定 / 审计用)。 + */ +module.exports = (app) => { + const { BIGINT, STRING, TINYINT, DATE } = app.Sequelize; + + const WechatMpAccount = app.model.define('wechat_mp_account', { + id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' }, + userId: { type: BIGINT.UNSIGNED, allowNull: true, comment: '绑定的平台账号 users.id(解绑后为空)' }, + appid: { type: STRING(64), allowNull: false, comment: '小程序 appid' }, + openid: { type: STRING(64), allowNull: false, comment: '用户在该 appid 下的 openid' }, + unionid: { type: STRING(64), allowNull: true, comment: '开放平台 unionid' }, + nickname: { type: STRING(64), allowNull: false, defaultValue: '', comment: '微信昵称(有授权时)' }, + avatar: { type: STRING(255), allowNull: false, defaultValue: '', comment: '微信头像(有授权时)' }, + sessionKey: { type: STRING(128), allowNull: true, comment: 'jscode2session 返回的 session_key' }, + lastLoginAt: { type: DATE, allowNull: true, comment: '最近一次微信登录时间' }, + loginCount: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 0, comment: '微信登录次数' }, + status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1正常 0停用' }, + }, { + tableName: 'wechat_mp_accounts', + paranoid: true, + comment: '微信小程序授权账号表', + }); + + WechatMpAccount.associate = function() { + app.model.WechatMpAccount.belongsTo(app.model.User, { foreignKey: 'user_id', as: 'user' }); + }; + + return WechatMpAccount; +}; diff --git a/backend/app/router.js b/backend/app/router.js index 786d92d..e66729f 100644 --- a/backend/app/router.js +++ b/backend/app/router.js @@ -40,6 +40,12 @@ module.exports = (app) => { router.post('/api/web/auth/forgot', controller.web.auth.forgot); router.post('/api/web/auth/reset', controller.web.auth.reset); + // ---------- 微信小程序登录(code2Session → openid → 绑定/新建平台账号) ---------- + router.post('/api/web/auth/wechat/login', controller.web.wechatMp.login); + router.post('/api/web/auth/wechat/bind', apiAuth, controller.web.wechatMp.bind); + router.get('/api/web/auth/wechat/bindings', apiAuth, controller.web.wechatMp.bindings); + router.delete('/api/web/auth/wechat/bindings/:id', apiAuth, controller.web.wechatMp.unbind); + router.get('/api/web/me', apiAuth, controller.web.profile.show); router.put('/api/web/me', apiAuth, controller.web.profile.update); router.put('/api/web/me/password', apiAuth, controller.web.profile.changePassword); diff --git a/backend/app/service/wechat_mp.js b/backend/app/service/wechat_mp.js new file mode 100644 index 0000000..00aa1bd --- /dev/null +++ b/backend/app/service/wechat_mp.js @@ -0,0 +1,272 @@ +'use strict'; + +const { Service } = require('egg'); +const crypto = require('crypto'); +const { Op } = require('sequelize'); + +/** 小程序登录的 mock 前缀:`mock:` 直接指定 openid,方便本地联调固定账号 */ +const MOCK_PREFIX = 'mock:'; + +/** + * 微信小程序登录 / 绑定 + * + * 链路:`uni.login()` 拿 code → `jscode2session` 换 openid → + * 按 (appid, openid) 找 `wechat_mp_accounts`: + * - 已绑定平台账号 → 签发该账号的 user JWT(`firstTime: false`); + * - 未绑定 → 自动建平台账号(`wx_`,随机密码)并绑定(`firstTime: true`)。 + * + * 未配置 `WX_MP_APPID / WX_MP_SECRET` 时(本地 / 单测),走 mock: + * 传 `mock:` 固定账号,或任意 code 按 sha1 推导 openid。生产必须显式 `WX_MP_MOCK=true` 才允许 mock。 + */ +class WechatMpService extends Service { + get cfg() { + return this.app.config.wechat.mp || {}; + } + + get Account() { + return this.app.model.WechatMpAccount; + } + + /** 配置齐全(有 appid + secret)才算真机模式 */ + get enabled() { + return Boolean(this.cfg.appid && this.cfg.secret); + } + + /** mock 是否可用 */ + get mockEnabled() { + if (this.cfg.mock) return true; + return !this.enabled && this.app.config.env !== 'prod'; + } + + get appid() { + return this.cfg.appid || 'mock-appid'; + } + + get apiBase() { + return this.cfg.apiBase || 'https://api.weixin.qq.com'; + } + + /** + * code → openid + * @param {string} code `uni.login()` 返回的 code(本地可用 `mock:`) + */ + async code2Session(code) { + const jsCode = String(code || '').trim(); + if (!jsCode) this.ctx.throw(422, '缺少微信登录 code'); + + if (jsCode.startsWith(MOCK_PREFIX)) { + if (!this.mockEnabled) this.ctx.throw(400, 'mock 微信登录未开启'); + const openid = this.normalizeOpenid(jsCode.slice(MOCK_PREFIX.length)); + return { openid, unionid: null, sessionKey: null, devMode: true }; + } + + if (!this.enabled) { + if (!this.mockEnabled) { + this.ctx.throw(503, '微信小程序登录未配置(WX_MP_APPID / WX_MP_SECRET)'); + } + const digest = crypto.createHash('sha1').update(jsCode).digest('hex').slice(0, 24); + this.ctx.logger.warn('[wechat-mp] 未配置 appid/secret,使用 mock openid=%s', digest); + return { openid: `mock_${digest}`, unionid: null, sessionKey: null, devMode: true }; + } + + const res = await this.ctx.curl(`${this.apiBase}/sns/jscode2session`, { + data: { + appid: this.cfg.appid, + secret: this.cfg.secret, + js_code: jsCode, + grant_type: 'authorization_code', + }, + dataType: 'json', + timeout: 8000, + }); + const data = res.data || {}; + if (data.errcode) { + this.ctx.logger.warn('[wechat-mp] jscode2session 失败: %s %s', data.errcode, data.errmsg); + this.ctx.throw(401, `微信登录失败:${data.errmsg || data.errcode}(code 可能已过期,请重试)`); + } + if (!data.openid) { + this.ctx.logger.error('[wechat-mp] jscode2session 未返回 openid: %s', JSON.stringify(data)); + this.ctx.throw(502, '微信登录失败:未获取到 openid'); + } + return { + openid: String(data.openid), + unionid: data.unionid || null, + sessionKey: data.session_key || null, + devMode: false, + }; + } + + /** 只保留 openid 允许的字符,并限制长度(DB 是 varchar(64)) */ + normalizeOpenid(value) { + const openid = String(value || '').replace(/[^A-Za-z0-9_\-@.]/g, '').slice(0, 64); + return openid || 'mock_default'; + } + + /** + * 小程序登录 + * @param {object} params code / userInfo(可选微信昵称头像)/ client + * @return {Promise<{user:object, binding:object, firstTime:boolean}>} + */ + async login({ code, userInfo }) { + const session = await this.code2Session(code); + const appid = this.appid; + + let account = await this.Account.findOne({ where: { appid, openid: session.openid } }); + let firstTime = false; + + if (!account) { + account = await this.Account.create({ + appid, + openid: session.openid, + unionid: session.unionid, + nickname: this.pickNickname(userInfo), + avatar: this.pickAvatar(userInfo), + sessionKey: session.sessionKey, + lastLoginAt: new Date(), + loginCount: 0, + }); + firstTime = true; + } + + if (account.status === 0) { + this.ctx.throw(403, '该微信已被停用,请联系管理员'); + } + + let user = account.userId ? await this.ctx.service.user.findById(account.userId) : null; + if (!user) { + user = await this.createUserFor(account, userInfo); + firstTime = true; + } + + await account.update({ + userId: user.id, + unionid: session.unionid || account.unionid, + sessionKey: session.sessionKey, + nickname: this.pickNickname(userInfo) || account.nickname, + avatar: this.pickAvatar(userInfo) || account.avatar, + lastLoginAt: new Date(), + loginCount: Number(account.loginCount || 0) + 1, + }); + + if (Number(user.status) !== 1) { + this.ctx.throw(403, '账号已被禁用,请联系管理员'); + } + await this.ctx.service.user.touchLogin(user.id); + + this.ctx.logger.info('[wechat-mp] 登录成功 userId=%s openid=%s firstTime=%s', user.id, session.openid, firstTime); + return { user, binding: this.toPublic(account.toJSON()), firstTime }; + } + + /** + * 把微信绑定到已有账号(需 user 令牌) + * 该 openid 已绑定别的账号 → 409(先解绑) + */ + async bind(userId, { code, userInfo }) { + const session = await this.code2Session(code); + const appid = this.appid; + + const exists = await this.Account.findOne({ where: { appid, openid: session.openid } }); + if (exists && exists.userId && Number(exists.userId) !== Number(userId)) { + this.ctx.throw(409, '该微信已绑定其他账号,请先在对应账号里解绑'); + } + if (exists && exists.status === 0) this.ctx.throw(403, '该微信已被停用'); + + const payload = { + userId, + unionid: session.unionid || (exists && exists.unionid) || null, + sessionKey: session.sessionKey, + nickname: this.pickNickname(userInfo) || (exists && exists.nickname) || '', + avatar: this.pickAvatar(userInfo) || (exists && exists.avatar) || '', + lastLoginAt: new Date(), + }; + + const account = exists + ? await exists.update(payload) + : await this.Account.create(Object.assign({ appid, openid: session.openid, loginCount: 0 }, payload)); + + this.ctx.logger.info('[wechat-mp] 用户 %s 绑定微信 openid=%s', userId, session.openid); + return this.toPublic((account.toJSON ? account.toJSON() : account)); + } + + /** 当前账号的微信绑定列表 */ + async listByUser(userId) { + const rows = await this.Account.findAll({ where: { userId }, order: [[ 'id', 'DESC' ]] }); + return rows.map(row => this.toPublic(row.toJSON())); + } + + /** 解绑:解绑后该 openid 不能再登录;至少要保留一种登录方式 */ + async unbind(userId, id) { + const account = await this.Account.findByPk(id); + if (!account || Number(account.userId) !== Number(userId)) this.ctx.throw(404, '绑定不存在'); + + const user = await this.ctx.service.user.findByIdWithPassword(userId); + const others = await this.Account.count({ where: { userId, id: { [Op.ne]: account.id } } }); + if (!(user && user.passwordHash) && others === 0) { + this.ctx.throw(422, '这是唯一的登录方式,请先设置密码再解绑'); + } + + await account.update({ userId: null }); + this.ctx.logger.info('[wechat-mp] 用户 %s 解绑微信 id=%s', userId, id); + return { id: Number(account.id) }; + } + + /** 给新 openid 建一个平台账号(用户名 wx_xxx,随机密码,用户可用「找回密码」设置) */ + async createUserFor(account, userInfo) { + const nickname = this.pickNickname(userInfo) || '微信用户'; + const password = crypto.randomBytes(24).toString('hex'); + + let lastError = null; + for (let i = 0; i < 5; i++) { + const username = this.candidateUsername(account.openid, i); + try { + const user = await this.ctx.service.auth.register({ + username, + password, + nickname, + email: null, + phone: null, + }); + const avatar = this.pickAvatar(userInfo); + if (avatar) await this.ctx.service.user.update(user.id, { avatar }); + this.ctx.logger.info('[wechat-mp] 新用户注册: %s (id=%s, openid=%s)', username, user.id, account.openid); + return this.ctx.service.user.findById(user.id) || user; + } catch (err) { + if (err.status !== 409) throw err; + lastError = err; + } + } + throw lastError || new Error('创建微信账号失败'); + } + + /** `wx_` + openid 末尾 12 位;重名时加随机后缀 */ + candidateUsername(openid, attempt) { + const tail = String(openid).replace(/[^A-Za-z0-9_]/g, '').slice(-12) || 'user'; + if (attempt === 0) return `wx_${tail}`; + return `wx_${tail}_${crypto.randomBytes(3).toString('hex')}`; + } + + pickNickname(userInfo) { + const nickname = String((userInfo && userInfo.nickname) || '').trim().slice(0, 64); + return nickname || ''; + } + + pickAvatar(userInfo) { + const avatar = String((userInfo && userInfo.avatar) || '').trim().slice(0, 255); + return avatar || ''; + } + + /** 对外结构(不吐 session_key / appid 内部细节) */ + toPublic(row) { + return { + id: Number(row.id), + userId: row.userId ? Number(row.userId) : null, + nickname: row.nickname || '', + avatar: row.avatar || '', + unionid: row.unionid || null, + lastLoginAt: row.lastLoginAt || null, + loginCount: Number(row.loginCount || 0), + }; + } +} + +module.exports = WechatMpService; diff --git a/backend/config/config.default.js b/backend/config/config.default.js index 9954c63..4076484 100644 --- a/backend/config/config.default.js +++ b/backend/config/config.default.js @@ -19,9 +19,20 @@ module.exports = (appInfo) => { config.siteName = env.SITE_NAME || '云仓视频溯源系统'; // 中间件(app/middleware/xxx.js 后写 'xxx') + // cors:跨域头(小程序 H5 预览直连后端用;鉴权只靠 header 令牌,不依赖 cookie) // errorHandler:接口异常统一返回 JSON // frontend:**后端不渲染页面** —— 开发时把页面请求反代给前端 dev server,生产时托管前端构建产物 - config.middleware = [ 'errorHandler', 'frontend' ]; + config.middleware = [ 'cors', 'errorHandler', 'frontend' ]; + + // ==================== 跨域 ==================== + // `'*'` = 回显任意 Origin;需要收紧就设 CORS_ORIGINS=http://127.0.0.1:7304,https://trace.example.com + config.cors = { + enable: !/^(0|false|no|off)$/i.test(String(env.CORS_ENABLE === undefined ? 'true' : env.CORS_ENABLE)), + origins: String(env.CORS_ORIGINS || '*') + .split(',') + .map(value => value.trim()) + .filter(Boolean), + }; // ==================== 安装包分发(软件自动更新) ==================== // 打包脚本(desktop/installer/build.ps1)会把: @@ -236,6 +247,15 @@ 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', + }, }; // 日志(生产建议按需调整) diff --git a/backend/config/config.unittest.js b/backend/config/config.unittest.js index 9a3725f..1fb0261 100644 --- a/backend/config/config.unittest.js +++ b/backend/config/config.unittest.js @@ -10,4 +10,10 @@ module.exports = { internal: { token: 'test-internal-token', }, + // 单测没有真实小程序 appid:允许 `mock:` 走 mock 登录 + wechat: { + mp: { + mock: true, + }, + }, }; diff --git a/backend/database/migrations/20261020230000-create-wechat-mp-accounts.js b/backend/database/migrations/20261020230000-create-wechat-mp-accounts.js new file mode 100644 index 0000000..a41beea --- /dev/null +++ b/backend/database/migrations/20261020230000-create-wechat-mp-accounts.js @@ -0,0 +1,48 @@ +'use strict'; + +/** + * 微信小程序授权账号表 + * + * 与公众号/网页授权的 `wechat_oauth` 分开:小程序登录是「openid → 平台账号」的一对一绑定关系, + * 解绑时只把 `user_id` 置空,记录保留(重新绑定、审计都能用)。 + */ +module.exports = { + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, TINYINT, DATE } = Sequelize; + + await queryInterface.createTable('wechat_mp_accounts', { + id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, allowNull: false }, + user_id: { + type: BIGINT.UNSIGNED, + allowNull: true, + references: { model: 'users', key: 'id' }, + onUpdate: 'CASCADE', + onDelete: 'SET NULL', + comment: '绑定的平台账号 users.id(解绑后为空)', + }, + appid: { type: STRING(64), allowNull: false, comment: '小程序 appid' }, + openid: { type: STRING(64), allowNull: false, comment: '用户在该 appid 下的 openid' }, + unionid: { type: STRING(64), allowNull: true, comment: '开放平台 unionid' }, + nickname: { type: STRING(64), allowNull: false, defaultValue: '', comment: '微信昵称(有授权时)' }, + avatar: { type: STRING(255), allowNull: false, defaultValue: '', comment: '微信头像(有授权时)' }, + session_key: { type: STRING(128), allowNull: true, comment: 'jscode2session 返回的 session_key' }, + last_login_at: { type: DATE, allowNull: true, comment: '最近一次微信登录时间' }, + login_count: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 0, comment: '微信登录次数' }, + status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1正常 0停用' }, + 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_mp_accounts', [ 'appid', 'openid' ], { + name: 'uk_wechat_mp_accounts_appid_openid', + unique: true, + }); + await queryInterface.addIndex('wechat_mp_accounts', [ 'user_id' ], { name: 'idx_wechat_mp_accounts_user' }); + await queryInterface.addIndex('wechat_mp_accounts', [ 'unionid' ], { name: 'idx_wechat_mp_accounts_unionid' }); + }, + + async down(queryInterface) { + await queryInterface.dropTable('wechat_mp_accounts'); + }, +}; diff --git a/backend/test/app/controller/wechat-mp.test.js b/backend/test/app/controller/wechat-mp.test.js new file mode 100644 index 0000000..69a92f5 --- /dev/null +++ b/backend/test/app/controller/wechat-mp.test.js @@ -0,0 +1,156 @@ +'use strict'; + +const { app, mock, assert } = require('egg-mock/bootstrap'); +const createFakeRedis = require('../../utils/fake-redis'); + +const instance = (data) => Object.assign( + { + toJSON: () => data, + update: async (fields) => Object.assign(data, fields), + }, + data, +); + +describe('test/app/controller/wechat-mp.test.js', () => { + const agreement = { + id: 9, + code: 'user_agreement', + name: '用户协议', + required: true, + version: { id: 11, version: '1.0.0', title: '用户协议', content: '正文' }, + }; + const accepted = [{ code: 'user_agreement', versionId: 11 }]; + + it('未同意协议 → 428(与账号密码登录一致)', async () => { + mock(app, 'redis', createFakeRedis().client); + app.mockService('agreement', 'requiredVersions', async () => [ agreement ]); + + const res = await app.httpRequest() + .post('/api/web/auth/wechat/login') + .send({ code: 'mock:openid-abc' }) + .expect(428); + + assert(res.body.status === 'agreement_required', JSON.stringify(res.body)); + assert(res.body.data.agreements[0].code === 'user_agreement', JSON.stringify(res.body)); + }); + + it('首次登录:按 openid 建账号 + 绑定,返回 firstTime=true', async () => { + mock(app, 'redis', createFakeRedis().client); + + let account = null; + mock(app, 'model', { + WechatMpAccount: { + async findOne() { + return account ? instance(account.data) : null; + }, + async create(data) { + account = { data: Object.assign({ id: 5, loginCount: 0, nickname: '', avatar: '' }, data) }; + return instance(account.data); + }, + }, + }); + + let registered = null; + app.mockService('auth', 'register', async (payload) => { + registered = payload; + return { id: 42, username: payload.username, nickname: payload.nickname }; + }); + app.mockService('user', 'findById', async () => ({ id: 42, username: registered.username, status: 1, nickname: '微信用户' })); + app.mockService('user', 'touchLogin', async () => null); + app.mockService('agreement', 'requiredVersions', async () => [ agreement ]); + app.mockService('agreement', 'record', async () => [{ code: 'user_agreement', versionId: 11, version: '1.0.0' }]); + + const res = await app.httpRequest() + .post('/api/web/auth/wechat/login') + .send({ code: 'mock:openid-abc', agreements: accepted }) + .expect(200); + + assert(res.body.ok === true, JSON.stringify(res.body)); + assert(res.body.data.firstTime === true, JSON.stringify(res.body.data)); + assert(res.body.data.wechat.userId === 42, JSON.stringify(res.body.data.wechat)); + assert(registered && registered.username.startsWith('wx_'), JSON.stringify(registered)); + assert(res.body.data.agreements[0].versionId === 11, JSON.stringify(res.body.data)); + }); + + it('已绑定账号再登录:复用账号,不重复建用户', async () => { + mock(app, 'redis', createFakeRedis().client); + + const account = { + id: 5, + userId: 7, + status: 1, + loginCount: 3, + nickname: '', + avatar: '', + data: { id: 5, userId: 7, status: 1, loginCount: 3, nickname: '', avatar: '' }, + }; + mock(app, 'model', { + WechatMpAccount: { + async findOne() { + return instance(account.data); + }, + }, + }); + app.mockService('user', 'findById', async () => ({ id: 7, username: 'demo', status: 1 })); + app.mockService('user', 'touchLogin', async () => null); + app.mockService('agreement', 'requiredVersions', async () => [ agreement ]); + app.mockService('agreement', 'record', async () => []); + + const res = await app.httpRequest() + .post('/api/web/auth/wechat/login') + .send({ code: 'mock:openid-abc', agreements: accepted }) + .expect(200); + + assert(res.body.data.firstTime === false, JSON.stringify(res.body.data)); + assert(res.body.data.user.id === 7, JSON.stringify(res.body.data.user)); + assert(res.body.data.wechat.loginCount === 4, JSON.stringify(res.body.data.wechat)); + }); + + it('缺 code → 422;账号被禁用 → 403', async () => { + mock(app, 'redis', createFakeRedis().client); + app.mockService('agreement', 'requiredVersions', async () => [ agreement ]); + + await app.httpRequest().post('/api/web/auth/wechat/login').send({ agreements: accepted }).expect(422); + + mock(app, 'model', { + WechatMpAccount: { + async findOne() { + return instance({ id: 5, userId: 7, status: 1, loginCount: 0, nickname: '', avatar: '' }); + }, + }, + }); + app.mockService('user', 'findById', async () => ({ id: 7, username: 'demo', status: 0 })); + + const res = await app.httpRequest() + .post('/api/web/auth/wechat/login') + .send({ code: 'mock:openid-abc', agreements: accepted }) + .expect(403); + assert(res.body.message.includes('禁用'), JSON.stringify(res.body)); + }); + + it('绑定:openid 已属于别人 → 409', async () => { + mock(app, 'redis', createFakeRedis().client); + + mock(app, 'model', { + // apiAuth 会用 service.user.findById → User.findByPk + User: { + async findByPk() { + return instance({ id: 7, username: 'demo', status: 1 }); + }, + }, + WechatMpAccount: { + async findOne() { + return instance({ id: 5, userId: 99, status: 1 }); + }, + }, + }); + + const token = app.createAnonymousContext().service.jwt.signUser({ id: 7, username: 'demo' }); + const res = await app.httpRequest() + .post('/api/web/auth/wechat/bind') + .set('Authorization', `Bearer ${token}`) + .send({ code: 'mock:openid-other' }) + .expect(409); + assert(res.body.message.includes('已绑定其他账号'), JSON.stringify(res.body)); + }); +});