diff --git a/backend/app/contract/index.js b/backend/app/contract/index.js index 206c995..6f37275 100644 --- a/backend/app/contract/index.js +++ b/backend/app/contract/index.js @@ -158,6 +158,68 @@ module.exports = { password: { type: 'string', required: true, description: '新密码(明文),不少于 6 位且不能与原密码相同' }, }, + // ---------- 微信登录 / 绑定(公众号扫码) ---------- + wechatQrcodeData: { + scene: { type: 'string', description: '场景:login 登录 / bind 绑定' }, + state: { type: 'string', description: '扫码会话标识,轮询状态接口时原样回传' }, + temp_code: { type: 'string', description: '网关临时码(一次性,默认 10 分钟有效)' }, + page_url: { type: 'string', description: '二维码内容(网关扫码页地址),前端据此生成二维码' }, + expires_in: { type: 'integer', description: '二维码有效秒数' }, + }, + wechatQrcodeResponse: { + code: { type: 'integer', description: '业务状态码,0 成功;非 0 时 message 为失败原因' }, + message: { type: 'string', description: '提示信息' }, + data: { type: 'wechatQrcodeData', description: '二维码数据' }, + }, + wechatLoginStatusData: { + status: { type: 'string', description: 'pending 待扫码 / success 登录成功 / unbound 微信未绑定账号 / disabled 账号已禁用' }, + message: { type: 'string', description: '状态说明' }, + token: { type: 'string', description: '登录成功时的 JWT,载荷仅含 user_id' }, + user_id: { type: 'integer', description: '登录成功时的用户ID' }, + expires_in: { type: 'integer', description: 'token 有效秒数' }, + }, + wechatLoginStatusResponse: { + code: { type: 'integer', description: '业务状态码,0 成功' }, + message: { type: 'string', description: '提示信息' }, + data: { type: 'wechatLoginStatusData', description: '登录结果' }, + }, + wechatBindStatusData: { + status: { type: 'string', description: 'pending 待扫码确认 / success 绑定成功 / conflict 该微信已绑定其他账号 / failed 账号异常' }, + message: { type: 'string', description: '状态说明' }, + }, + wechatBindStatusResponse: { + code: { type: 'integer', description: '业务状态码,0 成功' }, + message: { type: 'string', description: '提示信息' }, + data: { type: 'wechatBindStatusData', description: '绑定结果' }, + }, + wechatBindData: { + bound: { type: 'boolean', description: '是否已绑定微信' }, + openid: { type: 'string', description: '脱敏后的 openid' }, + unionid: { type: 'string', description: '脱敏后的 unionid' }, + bind_scene: { type: 'string', description: '绑定来源:bind 主动绑定 / login 扫码登录自动绑定' }, + bound_at: { type: 'string', description: '绑定时间' }, + last_login_at: { type: 'string', description: '最近一次微信登录时间' }, + }, + wechatBindResponse: { + code: { type: 'integer', description: '业务状态码,0 成功' }, + message: { type: 'string', description: '提示信息' }, + data: { type: 'wechatBindData', description: '当前账号的微信绑定信息' }, + }, + wechatNotifyRequest: { + event: { type: 'string', required: true, description: '通知事件:bind 绑定 / login 登录' }, + appKey: { type: 'string', required: true, description: '应用标识(需与服务端配置一致)' }, + scene: { type: 'string', description: '扫码场景,与 event 一致' }, + userId: { type: 'integer', description: '网关用户ID' }, + openid: { type: 'string', required: true, description: '公众号 openid' }, + unionid: { type: 'string', description: '开放平台 unionid' }, + bindCode: { type: 'string', description: '一次性绑定码(可选用 /api/auth/verify 兑换权威信息)' }, + tempCode: { type: 'string', description: '申请二维码时下发的临时码' }, + state: { type: 'string', required: true, description: '申请二维码时传入的业务标识,原样回传' }, + timestamp: { type: 'integer', required: true, description: '通知时间戳(毫秒),超出 5 分钟视为重放' }, + nonce: { type: 'string', required: true, description: '随机串,参与签名' }, + sign: { type: 'string', required: true, description: '签名:HMAC-SHA256(sha256(appSecret), appKey.userId.bindCode.timestamp.nonce)' }, + }, + // ---------- 主体 principals ---------- principalItem: { id: { type: 'integer', description: '主键' }, diff --git a/backend/app/controller/wechatAuth.js b/backend/app/controller/wechatAuth.js new file mode 100644 index 0000000..c7c70a7 --- /dev/null +++ b/backend/app/controller/wechatAuth.js @@ -0,0 +1,398 @@ +'use strict'; + +const { Controller } = require('egg'); +const { + SCENE_BIND, + SCENE_LOGIN, + bindKey, + clearState, + createTempCode, + isEnabled, + isRateLimited, + loginKey, + maskOpenid, + newState, + readState, + requireConfig, + saveState, + takeResult, + verifyNotify, + writeResult, + WechatGatewayError, +} = require('../lib/wechatGateway'); +const { buildLoginData } = require('../lib/authToken'); + +/** + * @controller WechatAuthController 微信登录与绑定(公众号扫码) + * @description 扫码链路:后端申请临时码 → 前端把 pageUrl 渲染成二维码 → 用户手机微信扫码确认 + * → 网关带签名 POST 到 /api/wx/notify → 前端轮询状态接口拿到登录态或绑定结果。 + * 微信相关的密钥只保存在服务端,接口返回给前端的只有临时码与二维码地址。 + */ +class WechatAuthController extends Controller { + /** + * @summary 微信登录是否可用 + * @description 公开接口:返回服务端是否已配置微信网关(appKey / appSecret), + * 未配置时前端隐藏或提示,不影响账号密码、邮箱验证码登录 + * @router get /api/auth/wechat/enabled + * @response 200 baseResponse success + */ + async enabled() { + const { ctx, app } = this; + ctx.body = { code: 0, message: 'success', data: { enabled: isEnabled(app) } }; + } + + /** + * @summary 申请微信登录二维码 + * @description 公开接口:向网关申请临时码(scene=login),返回二维码内容 page_url 与轮询用的 state; + * 临时码与 state 均一次性、默认 10 分钟有效;同一 IP 申请过于频繁时返回 429 + * @router post /api/auth/wechat/login/code + * @response 200 wechatQrcodeResponse success + */ + async createLoginCode() { + const { ctx, app } = this; + + try { + const cfg = requireConfig(app); + if (await isRateLimited(app, SCENE_LOGIN, ctx.ip, cfg.loginLimitPerIp, cfg.loginLimitWindow)) { + this.fail(new WechatGatewayError('请求过于频繁,请稍后再试', 429)); + return; + } + + const state = newState(); + await saveState(app, state, { scene: SCENE_LOGIN, user_id: null }); + const data = await createTempCode(app, { scene: SCENE_LOGIN, state }); + ctx.body = { code: 0, message: 'success', data: this.buildQrcodeData(data, SCENE_LOGIN, state) }; + } catch (err) { + this.fail(err); + } + } + + /** + * @summary 轮询微信登录结果 + * @description 公开接口:pending 待扫码;success 扫码完成并返回登录凭证(结果一次性,取走后即失效); + * unbound 微信尚未绑定系统账号;disabled 账号已禁用 + * @router get /api/auth/wechat/login/status + * @request query string state + * @response 200 wechatLoginStatusResponse success + */ + async loginStatus() { + const { ctx, app } = this; + const state = String(ctx.query.state || ''); + + const record = await readState(app, state); + if (!record || record.scene !== SCENE_LOGIN) { + this.fail(new WechatGatewayError('二维码已失效,请刷新后重试', 400)); + return; + } + + const result = await takeResult(app, loginKey(state)); + if (!result) { + ctx.body = { code: 0, message: 'success', data: { status: 'pending' } }; + return; + } + + await clearState(app, state); + + if (result.status !== 'success') { + ctx.body = { + code: 0, + message: 'success', + data: { + status: result.status, + message: result.status === 'unbound' + ? '该微信尚未绑定系统账号,请先用账号密码或邮箱登录,再到「我的」中绑定微信' + : '账号已禁用,请联系管理员', + }, + }; + return; + } + + const user = await ctx.model.User.findByPk(result.user_id); + if (!user) { + this.fail(new WechatGatewayError('用户不存在或已被删除', 404)); + return; + } + if (Number(user.status) !== 1) { + this.fail(new WechatGatewayError('账号已禁用', 403)); + return; + } + + await user.update({ last_login_at: new Date() }); + await ctx.service.cache.invalidateUser(user.id); + + ctx.body = { code: 0, message: 'success', data: { status: 'success', ...buildLoginData(app, user.id) } }; + } + + /** + * @summary 申请微信绑定二维码 + * @description 需登录:向网关申请临时码(scene=bind),扫码确认后把微信绑定到当前登录账号 + * @router post /api/auth/wechat/bind/code + * @apikey + * @response 200 wechatQrcodeResponse success + */ + async createBindCode() { + const { ctx, app } = this; + const state = newState(); + + try { + await saveState(app, state, { scene: SCENE_BIND, user_id: ctx.userId }); + const data = await createTempCode(app, { scene: SCENE_BIND, state }); + ctx.body = { code: 0, message: 'success', data: this.buildQrcodeData(data, SCENE_BIND, state) }; + } catch (err) { + this.fail(err); + } + } + + /** + * @summary 轮询微信绑定结果 + * @description 需登录:pending 待扫码确认;success 绑定成功; + * conflict 该微信已绑定其他账号;failed 账号不存在或已禁用 + * @router get /api/auth/wechat/bind/status + * @apikey + * @request query string state + * @response 200 wechatBindStatusResponse success + */ + async bindStatus() { + const { ctx, app } = this; + const state = String(ctx.query.state || ''); + + const record = await readState(app, state); + if (!record || record.scene !== SCENE_BIND || Number(record.user_id) !== Number(ctx.userId)) { + this.fail(new WechatGatewayError('二维码已失效,请刷新后重试', 400)); + return; + } + + const result = await takeResult(app, bindKey(state)); + if (!result) { + ctx.body = { code: 0, message: 'success', data: { status: 'pending' } }; + return; + } + + await clearState(app, state); + ctx.body = { code: 0, message: 'success', data: { status: result.status, message: result.message || '' } }; + } + + /** + * @summary 查询当前账号的微信绑定 + * @description 需登录:openid / unionid 只返回脱敏值 + * @router get /api/auth/wechat/bind + * @apikey + * @response 200 wechatBindResponse success + */ + async bindInfo() { + const { ctx } = this; + const bind = await ctx.model.UserWechatBind.findOne({ where: { user_id: ctx.userId } }); + + ctx.body = { + code: 0, + message: 'success', + data: { + bound: Boolean(bind), + openid: bind ? maskOpenid(bind.openid) : '', + unionid: bind && bind.unionid ? maskOpenid(bind.unionid) : '', + bind_scene: bind ? bind.bind_scene : '', + bound_at: bind ? bind.created_at : null, + last_login_at: bind ? bind.last_login_at : null, + }, + }; + } + + /** + * @summary 解绑微信 + * @description 需登录:删除当前账号的微信绑定,解绑后不能再使用微信扫码登录 + * @router delete /api/auth/wechat/bind + * @apikey + * @response 200 baseResponse success + */ + async unbind() { + const { ctx } = this; + const count = await ctx.model.UserWechatBind.destroy({ where: { user_id: ctx.userId } }); + + if (!count) { + ctx.status = 404; + ctx.body = { code: 404, message: '当前账号未绑定微信' }; + return; + } + ctx.body = { code: 0, message: 'success', data: { unbound: true } }; + } + + /** + * @summary 微信网关扫码结果通知 + * @description 网关服务端回调(非浏览器调用):必须校验 X-Gateway-Signature / 报文 sign 与时间戳; + * scene=bind 写入绑定关系,scene=login 记录登录结果供前端轮询取走;返回 2xx 视为处理成功 + * @router post /api/wx/notify + * @request body wechatNotifyRequest *body + * @response 200 baseResponse success + */ + async notify() { + const { ctx, app } = this; + const body = ctx.request.body && typeof ctx.request.body === 'object' ? ctx.request.body : {}; + + let checked; + try { + checked = verifyNotify(app, body, ctx.request.headers); + } catch (err) { + // 未配置网关:直接拒绝,避免任何人伪造绑定 + this.fail(err); + return; + } + if (!checked.ok) { + ctx.status = 401; + ctx.body = { code: 401, message: checked.message }; + return; + } + + const state = String(body.state || ''); + const scene = body.event || body.scene; + const record = await readState(app, state); + if (!record || record.scene !== scene) { + this.fail(new WechatGatewayError('扫码会话已失效,请重新扫码', 400)); + return; + } + + if (scene === SCENE_BIND) { + await this.handleBindNotify(app, body, record, state); + return; + } + if (scene === SCENE_LOGIN) { + await this.handleLoginNotify(app, body, state); + return; + } + + this.fail(new WechatGatewayError(`不支持的通知事件:${scene || '空'}`, 400)); + } + + /** + * 处理绑定通知:写入 user_wechat_binds(同一账号重新绑定则覆盖,同一微信只能绑一个账号) + * @param {Egg.Application} app egg application + * @param {Object} body 通知报文 + * @param {Object} record 扫码会话内容 + * @param {String} state 扫码会话标识 + * @return {Promise} 无返回值 + */ + async handleBindNotify(app, body, record, state) { + const { ctx } = this; + const userId = Number(record.user_id); + const openid = String(body.openid || ''); + + if (!userId || !openid) { + this.fail(new WechatGatewayError('通知缺少用户或 openid', 400)); + return; + } + + const user = await ctx.model.User.findByPk(userId); + if (!user || Number(user.status) !== 1) { + await writeResult(app, bindKey(state), { status: 'failed', message: '账号不存在或已禁用' }); + this.fail(new WechatGatewayError('账号不存在或已禁用', 403)); + return; + } + + const occupied = await ctx.model.UserWechatBind.findOne({ where: { openid } }); + if (occupied && Number(occupied.user_id) !== userId) { + await writeResult(app, bindKey(state), { status: 'conflict', message: '该微信已绑定其他系统账号,请先在对应账号解绑' }); + this.fail(new WechatGatewayError('该微信已绑定其他系统账号', 409)); + return; + } + + const payload = { + user_id: userId, + app_key: body.appKey || app.config.wechatGateway.appKey, + gateway_uid: body.userId || null, + openid, + unionid: body.unionid || null, + bind_scene: SCENE_BIND, + }; + + const mine = await ctx.model.UserWechatBind.findOne({ where: { user_id: userId } }); + try { + if (mine) { + await mine.update(payload); + } else { + await ctx.model.UserWechatBind.create(payload); + } + } catch (err) { + // 并发扫码时唯一索引冲突:仍按「已被占用」反馈,避免前端一直等待 + this.logger.warn(`[wechat] 绑定写入失败:${err.message}`); + await writeResult(app, bindKey(state), { status: 'conflict', message: '该微信已绑定其他系统账号,请先在对应账号解绑' }); + this.fail(new WechatGatewayError('该微信已绑定其他系统账号', 409)); + return; + } + + await writeResult(app, bindKey(state), { status: 'success', message: '绑定成功' }); + ctx.body = { code: 0, message: 'success' }; + } + + /** + * 处理登录通知:按 openid 找到绑定账号,把可签发的用户写入 Redis 供前端轮询取走 + * @param {Egg.Application} app egg application + * @param {Object} body 通知报文 + * @param {String} state 扫码会话标识 + * @return {Promise} 无返回值 + */ + async handleLoginNotify(app, body, state) { + const { ctx } = this; + const openid = String(body.openid || ''); + + if (!openid) { + this.fail(new WechatGatewayError('通知缺少 openid', 400)); + return; + } + + const bind = await ctx.model.UserWechatBind.findOne({ where: { openid } }); + if (!bind) { + // 未绑定:写入结果让前端提示去绑定,同时用 4xx 让扫码页显示失败 + await writeResult(app, loginKey(state), { status: 'unbound' }); + this.fail(new WechatGatewayError('该微信尚未绑定系统账号', 409)); + return; + } + + const user = await ctx.model.User.findByPk(bind.user_id); + if (!user || Number(user.status) !== 1) { + await writeResult(app, loginKey(state), { status: 'disabled' }); + this.fail(new WechatGatewayError('账号不存在或已禁用', 403)); + return; + } + + await bind.update({ + gateway_uid: body.userId || bind.gateway_uid, + unionid: body.unionid || bind.unionid, + last_login_at: new Date(), + }); + await writeResult(app, loginKey(state), { status: 'success', user_id: user.id }); + + ctx.body = { code: 0, message: 'success' }; + } + + /** + * 组装返回给前端的二维码数据(不含任何密钥) + * @param {Object} data 网关返回的临时码数据 + * @param {String} scene 场景 + * @param {String} state 扫码会话标识 + * @return {Object} 二维码数据 + */ + buildQrcodeData(data, scene, state) { + const { stateTtl } = this.app.config.wechatGateway; + return { + scene, + state, + temp_code: data.tempCode, + page_url: data.pageUrl, + expires_in: Number(data.expiresIn) || stateTtl, + }; + } + + /** + * 统一错误响应(网关内部错误按 502,配置/会话类错误按错误自带状态码) + * @param {Error} err 错误对象 + * @return {void} 无返回值 + */ + fail(err) { + const { ctx } = this; + const status = err instanceof WechatGatewayError ? err.status : 502; + if (status >= 500) ctx.logger.error(`[wechat] ${err.message}`); + ctx.status = status; + ctx.body = { code: status, message: err.message || '微信网关调用失败' }; + } +} + +module.exports = WechatAuthController; diff --git a/backend/app/lib/authToken.js b/backend/app/lib/authToken.js new file mode 100644 index 0000000..c2c6541 --- /dev/null +++ b/backend/app/lib/authToken.js @@ -0,0 +1,37 @@ +'use strict'; + +/** + * 登录态签发工具。 + * 所有登录方式(账号密码、邮箱验证码、微信扫码)签发的 JWT 必须完全一致: + * 载荷仅包含 user_id,有效期取 config.jwt.expiresIn。 + */ + +/** + * 将有效期配置转换为秒数(如 2h => 7200) + * @param {String|Number} expiresIn 有效期,如 2h / 7200 + * @return {Number} 有效秒数,无法解析时为 0 + */ +function parseExpiresIn(expiresIn) { + if (typeof expiresIn === 'number') return expiresIn; + const matched = /^(\d+)([smhd])$/.exec(String(expiresIn || '')); + if (!matched) return 0; + const units = { s: 1, m: 60, h: 3600, d: 86400 }; + return Number(matched[1]) * units[matched[2]]; +} + +/** + * 签发登录态 + * @param {Egg.Application} app egg application + * @param {Number} userId 用户ID + * @return {Object} { token, user_id, expires_in } + */ +function buildLoginData(app, userId) { + const expiresIn = app.config.jwt.expiresIn || '2h'; + const token = app.jwt.sign({ user_id: userId }, app.config.jwt.secret, { expiresIn }); + return { token, user_id: userId, expires_in: parseExpiresIn(expiresIn) }; +} + +module.exports = { + parseExpiresIn, + buildLoginData, +}; diff --git a/backend/app/lib/wechatGateway.js b/backend/app/lib/wechatGateway.js new file mode 100644 index 0000000..8eacbd9 --- /dev/null +++ b/backend/app/lib/wechatGateway.js @@ -0,0 +1,347 @@ +'use strict'; + +const crypto = require('crypto'); + +/** + * 微信登录网关(公众号网页静默授权)接入封装。 + * + * 链路:后端申请临时码 → 前端把 pageUrl 渲染成二维码 → 用户用手机微信扫码确认 + * → 网关带着签名 POST 到本系统的通知接口(/api/wx/notify)。 + * 说明: + * 1. appKey / appSecret 只保存在服务端,任何情况下都不下发到前端; + * 2. 临时码一次性、扫码会话与通知结果都存在 Redis,过期即失效; + * 3. 通知必须校验签名与时间戳,签名密钥是 sha256(appSecret)(与网关约定一致)。 + */ + +/** Redis key 前缀(与 oms:email:* / oms:cache:* 区分) */ +const PREFIX = 'oms:wx'; + +/** 扫码场景:登录 / 绑定 */ +const SCENE_LOGIN = 'login'; +const SCENE_BIND = 'bind'; + +/** 网关业务错误码 → 面向用户的提示 */ +const GATEWAY_ERROR_MESSAGES = { + 40005: '二维码或授权会话已失效,请刷新后重试', + 40010: '绑定码不存在、已过期或已被使用', + 40011: '绑定码已被使用', + 40012: '临时码与绑定码不能混用', + 40014: '二维码已失效,请刷新后重试', + 40102: '微信网关未配置应用凭证(appKey / appSecret)', + 40103: '微信网关应用凭证不正确,请检查 WX_GATEWAY_APP_KEY / WX_GATEWAY_APP_SECRET', + 40301: '微信网关应用已停用,请联系管理员', + 40302: '回调地址不在微信网关白名单内,请联系管理员', + 40401: '微信网关应用不存在,请检查 WX_GATEWAY_APP_KEY', +}; + +/** 网关调用异常(status 为建议返回给前端的 HTTP 状态码) */ +class WechatGatewayError extends Error { + /** + * @param {String} message 面向用户的提示 + * @param {Number} status 建议的 HTTP 状态码 + */ + constructor(message, status = 502) { + super(message); + this.name = 'WechatGatewayError'; + this.status = status; + } +} + +/** + * 取微信网关配置 + * @param {Egg.Application} app egg application + * @return {Object} 微信网关配置 + */ +function gatewayConfig(app) { + return app.config.wechatGateway || {}; +} + +/** + * 是否已配置微信网关(未配置时相关接口只提示配置,不影响其它登录方式) + * @param {Egg.Application} app egg application + * @return {Boolean} 是否可用 + */ +function isEnabled(app) { + const cfg = gatewayConfig(app); + return Boolean(cfg.appKey && cfg.appSecret); +} + +/** + * 取配置,未配置时抛出可直接返回给前端的异常 + * @param {Egg.Application} app egg application + * @return {Object} 微信网关配置 + */ +function requireConfig(app) { + const cfg = gatewayConfig(app); + if (!cfg.appKey || !cfg.appSecret) { + throw new WechatGatewayError('未配置微信登录网关,请先在服务端 .env 中填写 WX_GATEWAY_APP_KEY / WX_GATEWAY_APP_SECRET', 400); + } + return cfg; +} + +/** @return {String} 一次性扫码会话标识(回传用,不包含任何业务信息) */ +function newState() { + return crypto.randomBytes(16).toString('hex'); +} + +/** @param {String} state 扫描会话标识 @return {String} redis key */ +function stateKey(state) { + return `${PREFIX}:state:${state}`; +} + +/** @param {String} state 扫描会话标识 @return {String} redis key */ +function loginKey(state) { + return `${PREFIX}:login:${state}`; +} + +/** @param {String} state 扫描会话标识 @return {String} redis key */ +function bindKey(state) { + return `${PREFIX}:bind:${state}`; +} + +/** + * 公共扫码接口的限流 key(按场景 + IP 统计) + * @param {String} scope 场景 + * @param {String} ip 客户端IP + * @return {String} redis key + */ +function rateLimitKey(scope, ip) { + return `${PREFIX}:limit:${scope}:${ip}`; +} + +/** + * 判断是否超出频率限制(固定窗口计数,防止刷接口消耗网关临时码配额) + * @param {Egg.Application} app egg application + * @param {String} scope 场景 + * @param {String} ip 客户端IP + * @param {Number} limit 窗口内允许的次数 + * @param {Number} window 窗口秒数 + * @return {Promise} true 表示已超限 + */ +async function isRateLimited(app, scope, ip, limit, window) { + if (!(limit > 0)) return false; + + const key = rateLimitKey(scope, ip); + const count = await app.redis.incr(key); + if (count === 1) await app.redis.expire(key, window > 0 ? window : 600); + return count > limit; +} + +/** + * 写入扫码会话(scene + 发起人) + * @param {Egg.Application} app egg application + * @param {String} state 会话标识 + * @param {Object} payload { scene, user_id } + * @return {Promise} 无返回值 + */ +async function saveState(app, state, payload) { + const { stateTtl } = gatewayConfig(app); + await app.redis.set(stateKey(state), JSON.stringify(payload), 'EX', stateTtl); +} + +/** + * 读取扫码会话 + * @param {Egg.Application} app egg application + * @param {String} state 会话标识 + * @return {Promise} 会话内容,不存在或已过期返回 null + */ +async function readState(app, state) { + if (!state) return null; + const raw = await app.redis.get(stateKey(state)); + if (!raw) return null; + try { + return JSON.parse(raw); + } catch { + return null; + } +} + +/** + * 删除扫码会话 + * @param {Egg.Application} app egg application + * @param {String} state 会话标识 + * @return {Promise} 无返回值 + */ +async function clearState(app, state) { + await app.redis.del(stateKey(state)); +} + +/** + * 写入通知结果(登录成功 / 未绑定,绑定成功 / 冲突),供前端轮询取走 + * @param {Egg.Application} app egg application + * @param {String} key redis key + * @param {Object} payload 结果内容 + * @return {Promise} 无返回值 + */ +async function writeResult(app, key, payload) { + const { stateTtl } = gatewayConfig(app); + await app.redis.set(key, JSON.stringify(payload), 'EX', stateTtl); +} + +/** + * 读取并清除通知结果(一次性,避免同一结果被重复兑换成登录态) + * @param {Egg.Application} app egg application + * @param {String} key redis key + * @return {Promise} 结果内容 + */ +async function takeResult(app, key) { + const raw = await app.redis.get(key); + if (!raw) return null; + await app.redis.del(key); + try { + return JSON.parse(raw); + } catch { + return null; + } +} + +/** + * 申请临时码(二维码内容由网关返回的 pageUrl 决定) + * @param {Egg.Application} app egg application + * @param {Object} options 申请参数 + * @param {String} options.scene 场景:login 登录 / bind 绑定 + * @param {String} options.state 扫码会话标识,网关会在通知里原样回传 + * @return {Promise} 网关返回的临时码数据(tempCode / pageUrl / expiresIn …) + */ +async function createTempCode(app, { scene, state }) { + const cfg = requireConfig(app); + const url = `${cfg.baseUrl}/api/auth/temp-code`; + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), cfg.timeout); + + let resp; + let text = ''; + try { + resp = await fetch(url, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-App-Key': cfg.appKey, + 'X-App-Secret': cfg.appSecret, + }, + body: JSON.stringify({ scene, state }), + signal: controller.signal, + }); + text = await resp.text(); + } catch (err) { + const message = err.name === 'AbortError' + ? '微信网关响应超时,请稍后重试' + : `微信网关请求失败:${err.message}`; + throw new WechatGatewayError(message); + } finally { + clearTimeout(timer); + } + + let json; + try { + json = JSON.parse(text); + } catch { + throw new WechatGatewayError(`微信网关返回非 JSON 响应(HTTP ${resp.status})`); + } + + if (json.code !== 0) { + const message = GATEWAY_ERROR_MESSAGES[json.code] || json.message || `微信网关返回错误码 ${json.code}`; + // 凭证类错误属于配置问题,按 400 返回,方便前端直接提示管理员检查配置 + throw new WechatGatewayError(message, [ 40102, 40103, 40301, 40401 ].includes(json.code) ? 400 : 502); + } + + const data = json.data || {}; + if (!data.tempCode || !data.pageUrl) { + throw new WechatGatewayError('微信网关未返回可用的二维码地址'); + } + return data; +} + +/** + * 通知签名原文:appKey.userId.bindCode.timestamp.nonce(与网关保持一致,含 join 的隐式空串处理) + * @param {Object} body 通知报文 + * @return {String} 待签名串 + */ +function signMessage(body) { + return [ body.appKey, body.userId, body.bindCode, body.timestamp, body.nonce ].join('.'); +} + +/** + * 计算通知签名 + * @param {String} appSecret 应用密钥 + * @param {Object} body 通知报文 + * @return {String} hex 签名 + */ +function computeSign(appSecret, body) { + const secretHash = crypto.createHash('sha256').update(String(appSecret)).digest('hex'); + return crypto.createHmac('sha256', secretHash).update(signMessage(body)).digest('hex'); +} + +/** + * 定长安全比较,避免签名比较泄露时序信息 + * @param {String} a 字符串A + * @param {String} b 字符串B + * @return {Boolean} 是否相同 + */ +function safeEqual(a, b) { + const bufA = Buffer.from(String(a || '')); + const bufB = Buffer.from(String(b || '')); + if (!bufA.length || bufA.length !== bufB.length) return false; + return crypto.timingSafeEqual(bufA, bufB); +} + +/** + * 校验网关通知:应用标识 + 签名 + 时间戳(防重放) + * @param {Egg.Application} app egg application + * @param {Object} body 通知报文 + * @param {Object} headers 请求头 + * @return {Object} { ok, message } + */ +function verifyNotify(app, body, headers = {}) { + const cfg = requireConfig(app); + + if (body.appKey !== cfg.appKey) return { ok: false, message: '通知的应用标识不匹配' }; + + const timestamp = Number(body.timestamp); + if (!timestamp || Math.abs(Date.now() - timestamp) > cfg.notifyTolerance) { + return { ok: false, message: '通知已过期' }; + } + + const expected = computeSign(cfg.appSecret, body); + if (!safeEqual(expected, body.sign)) return { ok: false, message: '通知签名校验失败' }; + + const headerSign = headers['x-gateway-signature']; + if (headerSign && !safeEqual(expected, headerSign)) return { ok: false, message: '通知签名校验失败' }; + + return { ok: true, message: '' }; +} + +/** + * openid 脱敏展示(只保留首尾,避免完整标识出现在页面与日志中) + * @param {String} openid 微信 openid + * @return {String} 脱敏后的 openid + */ +function maskOpenid(openid) { + const value = String(openid || ''); + if (value.length <= 10) return value ? `${value.slice(0, 2)}****` : ''; + return `${value.slice(0, 6)}****${value.slice(-4)}`; +} + +module.exports = { + SCENE_LOGIN, + SCENE_BIND, + WechatGatewayError, + gatewayConfig, + isEnabled, + requireConfig, + newState, + stateKey, + loginKey, + bindKey, + rateLimitKey, + isRateLimited, + saveState, + readState, + clearState, + writeResult, + takeResult, + createTempCode, + computeSign, + verifyNotify, + maskOpenid, +}; diff --git a/backend/app/middleware/request_log.js b/backend/app/middleware/request_log.js index 83cccdb..b6c0412 100644 --- a/backend/app/middleware/request_log.js +++ b/backend/app/middleware/request_log.js @@ -2,8 +2,8 @@ /** 需要脱敏的请求头 */ const SENSITIVE_HEADERS = [ 'authorization', 'cookie', 'set-cookie' ]; -/** 请求报文需脱敏字段(含邮箱验证码 code) */ -const SENSITIVE_REQUEST_FIELDS = [ 'password', 'token', 'app_secret', 'code', 'salt' ]; +/** 请求报文需脱敏字段(含邮箱验证码 code、微信绑定码与网关签名) */ +const SENSITIVE_REQUEST_FIELDS = [ 'password', 'token', 'app_secret', 'code', 'salt', 'bindcode', 'bind_code', 'sign' ]; /** 响应报文需脱敏字段(业务状态码 code 不脱敏,仅脱敏凭据类) */ const SENSITIVE_RESPONSE_FIELDS = [ 'password', 'token', 'app_secret', 'salt' ]; diff --git a/backend/app/model/userWechatBind.js b/backend/app/model/userWechatBind.js new file mode 100644 index 0000000..b0aee94 --- /dev/null +++ b/backend/app/model/userWechatBind.js @@ -0,0 +1,31 @@ +'use strict'; + +/** + * 微信绑定模型,对应 user_wechat_binds 表。 + * 一个微信身份(openid)只绑定一个系统账号;一个系统账号只保留最近一次绑定的微信。 + * 网关侧的 openid 只在服务端保存,前端只展示脱敏值。 + * @param {Egg.Application} app egg application + * @return {object} user_wechat_bind model + */ +module.exports = app => { + const { BIGINT, STRING, DATE } = app.Sequelize; + + const UserWechatBind = app.model.define('user_wechat_bind', { + id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' }, + user_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '系统用户ID' }, + app_key: { type: STRING(64), comment: '所属网关应用 appKey(区分开发/生产环境)' }, + gateway_uid: { type: BIGINT.UNSIGNED, comment: '网关用户ID(通知里的 userId)' }, + openid: { type: STRING(64), allowNull: false, comment: '公众号 openid,全局唯一' }, + unionid: { type: STRING(64), comment: '开放平台 unionid(公众号已绑定开放平台时才有)' }, + bind_scene: { type: STRING(16), allowNull: false, defaultValue: 'bind', comment: '绑定来源:bind 主动绑定 / login 扫码登录自动绑定' }, + last_login_at: { type: DATE, comment: '最近一次微信登录时间' }, + created_at: { type: DATE, comment: '创建时间' }, + updated_at: { type: DATE, comment: '更新时间' }, + }); + + UserWechatBind.associate = () => { + app.model.UserWechatBind.belongsTo(app.model.User, { foreignKey: 'user_id', as: 'user' }); + }; + + return UserWechatBind; +}; diff --git a/backend/app/router.js b/backend/app/router.js index 8786aa5..7e96d4a 100644 --- a/backend/app/router.js +++ b/backend/app/router.js @@ -26,6 +26,17 @@ module.exports = app => { router.put('/api/auth/profile', jwtAuth, controller.auth.updateProfile); router.put('/api/auth/password', jwtAuth, controller.auth.changePassword); + // 微信网关(公众号扫码):登录无需鉴权,绑定 / 解绑需登录 + router.get('/api/auth/wechat/enabled', controller.wechatAuth.enabled); + router.post('/api/auth/wechat/login/code', controller.wechatAuth.createLoginCode); + router.get('/api/auth/wechat/login/status', controller.wechatAuth.loginStatus); + router.post('/api/auth/wechat/bind/code', jwtAuth, controller.wechatAuth.createBindCode); + router.get('/api/auth/wechat/bind/status', jwtAuth, controller.wechatAuth.bindStatus); + router.get('/api/auth/wechat/bind', jwtAuth, controller.wechatAuth.bindInfo); + router.delete('/api/auth/wechat/bind', jwtAuth, controller.wechatAuth.unbind); + // 微信网关扫码结果通知:由网关服务端回调,按签名校验(不用 JWT) + router.post('/api/wx/notify', controller.wechatAuth.notify); + // 菜单树需在 /api/menus/:id 之前注册,避免 tree 被当作 id 匹配 router.get('/api/menus/tree', jwtAuth, controller.menu.tree); // 订单状态/外部 WMS 状态回写:按订单所属主体做跨主体隔离 diff --git a/backend/config/config.default.js b/backend/config/config.default.js index 6e73196..d1fe0d7 100644 --- a/backend/config/config.default.js +++ b/backend/config/config.default.js @@ -119,6 +119,25 @@ module.exports = appInfo => { baseUrl: 'https://api.deepseek.com', }; + // 微信登录网关(公众号网页静默授权):扫码绑定微信 / 扫码登录 + // 网关地址与接入凭证在网关管理台创建应用后下发;appKey / appSecret 只保存在服务端, + // 禁止下发到前端或写进二维码内容。开发与生产各自独立的一套应用(互不复用密钥)。 + // 未配置 appKey / appSecret 时微信相关接口返回 400 并提示配置,不影响账号密码 / 邮箱验证码登录 + config.wechatGateway = { + baseUrl: (process.env.WX_GATEWAY_BASE_URL || 'https://gateway.gztbyc.com').replace(/\/+$/, ''), + appKey: process.env.WX_GATEWAY_APP_KEY || '', + appSecret: process.env.WX_GATEWAY_APP_SECRET || '', + // 调用网关接口的超时时间(毫秒) + timeout: Number(process.env.WX_GATEWAY_TIMEOUT || 8000), + // 临时码 / 扫码会话在本地 Redis 的有效期(秒),与网关临时码默认 10 分钟保持一致 + stateTtl: Number(process.env.WX_GATEWAY_STATE_TTL || 600), + // 通知签名允许的时间偏差(毫秒),超出视为重放 + notifyTolerance: Number(process.env.WX_GATEWAY_NOTIFY_TOLERANCE || 5 * 60 * 1000), + // 扫码登录二维码申请的频率限制(同一 IP 在窗口内的最大次数),防止刷接口消耗网关临时码配额 + loginLimitPerIp: Number(process.env.WX_GATEWAY_LOGIN_LIMIT || 20), + loginLimitWindow: Number(process.env.WX_GATEWAY_LOGIN_LIMIT_WINDOW || 600), + }; + // Redis 配置:缓存邮箱验证码等数据,敏感信息建议用环境变量覆盖 config.redis = { client: { diff --git a/backend/database/migrations/20261101000000-create-user-wechat-binds.js b/backend/database/migrations/20261101000000-create-user-wechat-binds.js new file mode 100644 index 0000000..6847f5e --- /dev/null +++ b/backend/database/migrations/20261101000000-create-user-wechat-binds.js @@ -0,0 +1,50 @@ +'use strict'; + +/** + * 微信绑定表:记录「系统账号 ↔ 微信 openid」的绑定关系。 + * - openid 唯一:一个微信身份只能绑定一个系统账号; + * - user_id 唯一:一个系统账号只保留最近一次绑定的微信(重新绑定即覆盖); + * - gateway_uid 便于按网关用户 ID 反查; + * - app_key 记录所属网关应用,区分开发 / 生产环境。 + */ +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.createTable( + 'user_wechat_binds', + { + id: { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: false, + autoIncrement: true, + primaryKey: true, + }, + user_id: { type: Sequelize.BIGINT.UNSIGNED, allowNull: false, comment: '系统用户ID' }, + app_key: { type: Sequelize.STRING(64), allowNull: true, comment: '所属网关应用 appKey' }, + gateway_uid: { type: Sequelize.BIGINT.UNSIGNED, allowNull: true, comment: '网关用户ID' }, + openid: { type: Sequelize.STRING(64), allowNull: false, comment: '公众号 openid,全局唯一' }, + unionid: { type: Sequelize.STRING(64), allowNull: true, comment: '开放平台 unionid' }, + bind_scene: { type: Sequelize.STRING(16), allowNull: false, defaultValue: 'bind', comment: '绑定来源:bind / login' }, + last_login_at: { type: Sequelize.DATE, allowNull: true, comment: '最近一次微信登录时间' }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + }, + }, + { charset: 'utf8mb4', collate: 'utf8mb4_unicode_ci', comment: '微信绑定表' } + ); + + await queryInterface.addIndex('user_wechat_binds', { fields: [ 'openid' ], unique: true, name: 'uk_wx_bind_openid' }); + await queryInterface.addIndex('user_wechat_binds', { fields: [ 'user_id' ], unique: true, name: 'uk_wx_bind_user' }); + await queryInterface.addIndex('user_wechat_binds', { fields: [ 'gateway_uid' ], name: 'idx_wx_bind_gateway_uid' }); + }, + + async down(queryInterface) { + await queryInterface.dropTable('user_wechat_binds'); + }, +}; diff --git a/backend/env.development.example b/backend/env.development.example new file mode 100644 index 0000000..9ce5ec6 --- /dev/null +++ b/backend/env.development.example @@ -0,0 +1,42 @@ +# OMS 后端开发环境变量模板(本文件提交 git,供本地开发复制使用;真实 .env 不入库) +# +# cp env.development.example .env +# +# config/config.default.js 通过 dotenv 读取「进程工作目录」下的 .env, +# 即 backend/.env(npm run dev 的工作目录就是 backend)。 + +# ——— MySQL(可选;不配则用 database/config.js 的本地默认值 127.0.0.1:3307)——— +# MYSQL_HOST=127.0.0.1 +# MYSQL_PORT=3307 +# MYSQL_USER=oms +# MYSQL_PASSWORD= +# MYSQL_DATABASE=oms + +# ——— Redis(可选;不配则用本地默认值 127.0.0.1:6379)——— +# REDIS_HOST=127.0.0.1 +# REDIS_PORT=6379 +# REDIS_PASSWORD= + +# ——— JWT(本地可用默认值,生产必须单独设置)——— +# JWT_SECRET= +# JWT_EXPIRES_IN=2h + +# ——— 邮件(可选;不配置 SMTP_HOST 时验证码只写日志、不发信)——— +# SMTP_HOST=smtp.qq.com +# SMTP_PORT=465 +# SMTP_SECURE=true +# SMTP_USER= +# SMTP_PASS= +# SMTP_FROM= + +# ——— AI 收件人智能识别(可选;不配置时该接口返回 400 提示)——— +# DEEPSEEK_API_KEY= + +# ——— 微信登录网关(公众号扫码登录 / 绑定)——— +# 在网关管理台(https://gateway.gztbyc.com)单独创建「开发环境」接入应用,拿到 appKey / appSecret 填入; +# 网关的应用配置里「服务端通知地址」固定填本系统后端接口:{后端对外地址}/api/wx/notify +# 本地开发时网关回连不到 127.0.0.1,可填内网穿透地址,或指向已部署环境的通知地址 +# 开发环境与生产环境必须各自使用不同的 appKey / appSecret,互不复用 +WX_GATEWAY_BASE_URL=https://gateway.gztbyc.com +WX_GATEWAY_APP_KEY=__FILL_DEV_WX_APP_KEY__ +WX_GATEWAY_APP_SECRET=__FILL_DEV_WX_APP_SECRET__ diff --git a/backend/env.production.example b/backend/env.production.example index e5a3726..ca7daf4 100644 --- a/backend/env.production.example +++ b/backend/env.production.example @@ -69,3 +69,11 @@ EGG_PORT=6090 # CACHE_TTL_PRINCIPAL_OPTIONS=600 # EMAIL_CODE_INTERVAL=60 # EMAIL_CODE_DAILY_LIMIT=10 +# —— 微信登录网关(公众号扫码登录 / 扫码绑定,可选;不配置时微信相关接口返回 400 提示)—— +# 在网关管理台(https://gateway.gztbyc.com)单独创建「生产环境」接入应用,拿到 appKey / appSecret 填入; +# 网关的应用配置里「服务端通知地址」固定填 https://{生产域名}/api/wx/notify +# ⚠️ appSecret 只保存在服务端:禁止写入前端代码、文档或二维码内容 +# ⚠️ 生产与开发环境必须各自使用不同的 appKey / appSecret,互不复用 +# WX_GATEWAY_BASE_URL=https://gateway.gztbyc.com +WX_GATEWAY_APP_KEY=__FILL_WX_APP_KEY__ +WX_GATEWAY_APP_SECRET=__FILL_WX_APP_SECRET__ \ No newline at end of file diff --git a/backend/test/app/wechat.test.js b/backend/test/app/wechat.test.js new file mode 100644 index 0000000..d19cf4f --- /dev/null +++ b/backend/test/app/wechat.test.js @@ -0,0 +1,341 @@ +'use strict'; + +const { app, assert } = require('egg-mock/bootstrap'); +const { generateSalt, hashPassword } = require('../../app/lib/password'); +const { + SCENE_BIND, + SCENE_LOGIN, + computeSign, + newState, + saveState, +} = require('../../app/lib/wechatGateway'); + +const APP_KEY = 'gwk_test_oms'; +const APP_SECRET = 'gws_test_secret'; +const USERNAME = 'wx_test_user'; +const OTHER_USERNAME = 'wx_test_other'; +const OPENID = 'oXTestOpenid0000000000000001'; +const OPENID_OTHER = 'oXTestOpenid0000000000000002'; + +/** 原始 fetch:用例里会临时替换成假网关,结束后恢复 */ +const originalFetch = global.fetch; + +describe('test/app/wechat.test.js', () => { + let userId; + let otherUserId; + let token; + + before(async () => { + // 清掉上一次执行留下的限流计数,避免重复运行时被 429 拦住 + const limitKeys = await app.redis.keys('oms:wx:limit:*'); + if (limitKeys.length) await app.redis.del(limitKeys); + + const salt = generateSalt(); + const user = await app.model.User.create({ + username: USERNAME, + password: hashPassword('test123456', salt), + salt, + status: 1, + }); + userId = user.id; + + const other = await app.model.User.create({ + username: OTHER_USERNAME, + password: hashPassword('test123456', salt), + salt, + status: 1, + }); + otherUserId = other.id; + + token = app.jwt.sign({ user_id: userId }, app.config.jwt.secret, { expiresIn: '2h' }); + }); + + after(async () => { + await app.model.UserWechatBind.destroy({ where: { user_id: [ userId, otherUserId ] } }); + await app.model.User.destroy({ where: { username: [ USERNAME, OTHER_USERNAME ] } }); + global.fetch = originalFetch; + }); + + /** + * 组装一条合法的网关通知报文 + * @param {Object} overrides 需要覆盖的字段 + * @return {Object} 带签名的通知报文 + */ + function buildNotify(overrides = {}) { + const body = { + event: SCENE_LOGIN, + appId: 1, + appKey: APP_KEY, + scene: SCENE_LOGIN, + userId: 12, + openid: OPENID, + unionid: null, + bindCode: null, + tempCode: 'temp-code', + state: '', + timestamp: Date.now(), + nonce: 'nonce123', + ...overrides, + }; + body.sign = computeSign(APP_SECRET, body); + return body; + } + + describe('未配置网关', () => { + it('should report disabled when appKey / appSecret missing', async () => { + const res = await app.httpRequest() + .get('/api/auth/wechat/enabled') + .expect(200); + + assert(res.body.data.enabled === false); + }); + + it('should 400 when apply login qrcode without config', async () => { + const res = await app.httpRequest() + .post('/api/auth/wechat/login/code') + .expect(400); + + assert(res.body.code === 400); + assert(/未配置微信登录网关/.test(res.body.message)); + }); + }); + + describe('已配置网关', () => { + let original; + + beforeEach(() => { + original = { ...app.config.wechatGateway }; + Object.assign(app.config.wechatGateway, { + baseUrl: 'https://gateway.test', + appKey: APP_KEY, + appSecret: APP_SECRET, + }); + }); + + afterEach(() => { + Object.assign(app.config.wechatGateway, original); + }); + + it('should 401 when bind qrcode requested without token', async () => { + await app.httpRequest() + .post('/api/auth/wechat/bind/code') + .expect(401); + }); + + it('should apply login qrcode and expose page url only', async () => { + global.fetch = async () => ({ + status: 200, + text: async () => JSON.stringify({ + code: 0, + data: { + appId: 1, + appKey: APP_KEY, + scene: SCENE_LOGIN, + tempCode: 'temp-code-1', + expiresIn: 600, + state: 'ignored', + pageUrl: 'https://gateway.test/#/auth?code=temp-code-1', + }, + }), + }); + + const res = await app.httpRequest() + .post('/api/auth/wechat/login/code') + .expect(200); + + const data = res.body.data; + assert(data.page_url === 'https://gateway.test/#/auth?code=temp-code-1'); + assert(data.temp_code === 'temp-code-1'); + assert(data.scene === SCENE_LOGIN); + assert(data.state && data.state.length === 32); + // 密钥绝不能出现在响应里 + assert(!JSON.stringify(res.body).includes(APP_SECRET)); + }); + + it('should 400 when gateway rejects credentials', async () => { + global.fetch = async () => ({ + status: 401, + text: async () => JSON.stringify({ code: 40103, message: '应用凭证不正确' }), + }); + + const res = await app.httpRequest() + .post('/api/auth/wechat/login/code') + .expect(400); + + assert(/应用凭证/.test(res.body.message)); + }); + + it('should 429 when login qrcode requested too frequently', async () => { + global.fetch = async () => ({ + status: 200, + text: async () => JSON.stringify({ + code: 0, + data: { tempCode: 'temp-code-2', pageUrl: 'https://gateway.test/#/auth?code=temp-code-2', expiresIn: 600 }, + }), + }); + + const keys = await app.redis.keys('oms:wx:limit:*'); + if (keys.length) await app.redis.del(keys); + Object.assign(app.config.wechatGateway, { loginLimitPerIp: 1, loginLimitWindow: 60 }); + + await app.httpRequest() + .post('/api/auth/wechat/login/code') + .expect(200); + + const res = await app.httpRequest() + .post('/api/auth/wechat/login/code') + .expect(429); + + assert(res.body.code === 429); + }); + + it('should 401 when notify signature is invalid', async () => { + const state = newState(); + await saveState(app, state, { scene: SCENE_BIND, user_id: userId }); + + const body = buildNotify({ event: SCENE_BIND, scene: SCENE_BIND, state, openid: OPENID }); + body.sign = 'deadbeef'; + + const res = await app.httpRequest() + .post('/api/wx/notify') + .send(body) + .expect(401); + + assert(res.body.code === 401); + }); + + it('should 401 when notify timestamp is expired', async () => { + const state = newState(); + await saveState(app, state, { scene: SCENE_BIND, user_id: userId }); + + const body = buildNotify({ + event: SCENE_BIND, + scene: SCENE_BIND, + state, + openid: OPENID, + timestamp: Date.now() - 10 * 60 * 1000, + }); + + await app.httpRequest() + .post('/api/wx/notify') + .send(body) + .expect(401); + }); + + it('should bind wechat and reflect it in bind info', async () => { + const state = newState(); + await saveState(app, state, { scene: SCENE_BIND, user_id: userId }); + + await app.httpRequest() + .post('/api/wx/notify') + .send(buildNotify({ event: SCENE_BIND, scene: SCENE_BIND, state, openid: OPENID })) + .expect(200); + + const status = await app.httpRequest() + .get(`/api/auth/wechat/bind/status?state=${state}`) + .set('Authorization', `Bearer ${token}`) + .expect(200); + assert(status.body.data.status === 'success'); + + const info = await app.httpRequest() + .get('/api/auth/wechat/bind') + .set('Authorization', `Bearer ${token}`) + .expect(200); + assert(info.body.data.bound === true); + assert(info.body.data.bind_scene === SCENE_BIND); + // openid 只返回脱敏值 + assert(!info.body.data.openid.includes(OPENID.slice(6, -4))); + + const bind = await app.model.UserWechatBind.findOne({ where: { user_id: userId } }); + assert(bind.openid === OPENID); + assert(bind.gateway_uid === 12); + }); + + it('should 409 when the same openid is bound by another account', async () => { + const state = newState(); + await saveState(app, state, { scene: SCENE_BIND, user_id: otherUserId }); + + await app.httpRequest() + .post('/api/wx/notify') + .send(buildNotify({ event: SCENE_BIND, scene: SCENE_BIND, state, openid: OPENID })) + .expect(409); + + const status = await app.httpRequest() + .get(`/api/auth/wechat/bind/status?state=${state}`) + .set('Authorization', `Bearer ${token}`) + .expect(400); // 会话属于 otherUser,用当前账号查不到 + assert(status.body.code === 400); + + const caused = await app.model.UserWechatBind.findOne({ where: { user_id: otherUserId } }); + assert(!caused); + }); + + it('should 409 when login with unbound openid', async () => { + const state = newState(); + await saveState(app, state, { scene: SCENE_LOGIN, user_id: null }); + + await app.httpRequest() + .post('/api/wx/notify') + .send(buildNotify({ event: SCENE_LOGIN, scene: SCENE_LOGIN, state, openid: OPENID_OTHER })) + .expect(409); + + const res = await app.httpRequest() + .get(`/api/auth/wechat/login/status?state=${state}`) + .expect(200); + assert(res.body.data.status === 'unbound'); + }); + + it('should login by wechat and issue a working token once', async () => { + const state = newState(); + await saveState(app, state, { scene: SCENE_LOGIN, user_id: null }); + + await app.httpRequest() + .post('/api/wx/notify') + .send(buildNotify({ event: SCENE_LOGIN, scene: SCENE_LOGIN, state, openid: OPENID })) + .expect(200); + + const res = await app.httpRequest() + .get(`/api/auth/wechat/login/status?state=${state}`) + .expect(200); + + assert(res.body.data.status === 'success'); + assert(res.body.data.user_id === userId); + assert(res.body.data.expires_in > 0); + + const decoded = app.jwt.verify(res.body.data.token, app.config.jwt.secret); + assert(decoded.user_id === userId); + + await app.httpRequest() + .get('/api/auth/profile') + .set('Authorization', `Bearer ${res.body.data.token}`) + .expect(200); + + // 登录态一次性:同一个 state 再取一次已被消费 + const again = await app.httpRequest() + .get(`/api/auth/wechat/login/status?state=${state}`) + .expect(400); + assert(again.body.code === 400); + }); + + it('should unbind wechat', async () => { + await app.httpRequest() + .delete('/api/auth/wechat/bind') + .set('Authorization', `Bearer ${token}`) + .expect(200); + + const info = await app.httpRequest() + .get('/api/auth/wechat/bind') + .set('Authorization', `Bearer ${token}`) + .expect(200); + assert(info.body.data.bound === false); + + // 解绑后该微信无法再扫码登录 + const state = newState(); + await saveState(app, state, { scene: SCENE_LOGIN, user_id: null }); + await app.httpRequest() + .post('/api/wx/notify') + .send(buildNotify({ event: SCENE_LOGIN, scene: SCENE_LOGIN, state, openid: OPENID })) + .expect(409); + }); + }); +}); diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 11a9459..8d87637 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -13,11 +13,13 @@ "element-china-area-data": "^6.1.0", "element-plus": "^2.9.1", "pinia": "^2.3.1", + "qrcode": "^1.5.4", "vue": "^3.5.13", "vue-router": "^4.5.0" }, "devDependencies": { "@types/node": "^22.10.2", + "@types/qrcode": "^1.5.6", "@vitejs/plugin-vue": "^5.2.1", "typescript": "~5.7.2", "vite": "^6.0.5", @@ -971,6 +973,16 @@ "undici-types": "~6.21.0" } }, + "node_modules/@types/qrcode": { + "version": "1.5.6", + "resolved": "https://registry.npmjs.org/@types/qrcode/-/qrcode-1.5.6.tgz", + "integrity": "sha512-te7NQcV2BOvdj2b1hCAHzAoMNuj65kNBMz0KBaxM6c3VGBOhU0dURQKOtH8CFNI/dsKkwlv32p26qYQTWoB5bw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/web-bluetooth": { "version": "0.0.21", "resolved": "https://registry.npmjs.org/@types/web-bluetooth/-/web-bluetooth-0.0.21.tgz", @@ -1217,6 +1229,30 @@ "dev": true, "license": "MIT" }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, "node_modules/async-validator": { "version": "4.2.5", "resolved": "https://registry.npmjs.org/async-validator/-/async-validator-4.2.5.tgz", @@ -1271,12 +1307,50 @@ "node": ">= 0.4" } }, + "node_modules/camelcase": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/china-division": { "version": "2.7.0", "resolved": "https://registry.npmjs.org/china-division/-/china-division-2.7.0.tgz", "integrity": "sha512-4uUPAT+1WfqDh5jytq7omdCmHNk3j+k76zEG/2IqaGcYB90c2SwcixttcypdsZ3T/9tN1TTpBDoeZn+Yw/qBEA==", "license": "MIT" }, + "node_modules/cliui": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz", + "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^6.2.0" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "license": "MIT" + }, "node_modules/combined-stream": { "version": "1.0.8", "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", @@ -1325,6 +1399,15 @@ } } }, + "node_modules/decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/delayed-stream": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", @@ -1334,6 +1417,12 @@ "node": ">=0.4.0" } }, + "node_modules/dijkstrajs": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/dijkstrajs/-/dijkstrajs-1.0.3.tgz", + "integrity": "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==", + "license": "MIT" + }, "node_modules/dunder-proto": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", @@ -1383,6 +1472,12 @@ "vue": "^3.3.7" } }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, "node_modules/entities": { "version": "7.0.1", "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", @@ -1506,6 +1601,19 @@ } } }, + "node_modules/find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "license": "MIT", + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/follow-redirects": { "version": "1.16.0", "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz", @@ -1566,6 +1674,15 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, "node_modules/get-intrinsic": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", @@ -1677,6 +1794,27 @@ "node": ">= 6" } }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "license": "MIT", + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/lodash": { "version": "4.18.1", "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz", @@ -1798,6 +1936,42 @@ "integrity": "sha512-Wj7+EJQ8mSuXr2iWfnujrimU35R2W4FAErEyTmJoJ7ucwTn2hOUSsRehMb5RSYkxXGTM7Y9QpvPmp++w5ftoJw==", "license": "BSD-3-Clause" }, + "node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "license": "MIT", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "license": "MIT", + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/path-browserify": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-1.0.1.tgz", @@ -1805,6 +1979,15 @@ "dev": true, "license": "MIT" }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -1846,6 +2029,15 @@ } } }, + "node_modules/pngjs": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz", + "integrity": "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==", + "license": "MIT", + "engines": { + "node": ">=10.13.0" + } + }, "node_modules/postcss": { "version": "8.5.28", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz", @@ -1883,6 +2075,38 @@ "node": ">=10" } }, + "node_modules/qrcode": { + "version": "1.5.4", + "resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz", + "integrity": "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==", + "license": "MIT", + "dependencies": { + "dijkstrajs": "^1.0.1", + "pngjs": "^5.0.0", + "yargs": "^15.3.1" + }, + "bin": { + "qrcode": "bin/qrcode" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/require-main-filename": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", + "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", + "license": "ISC" + }, "node_modules/rollup": { "version": "4.63.1", "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.63.1.tgz", @@ -1929,6 +2153,12 @@ "fsevents": "~2.3.2" } }, + "node_modules/set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", + "license": "ISC" + }, "node_modules/source-map-js": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", @@ -1938,6 +2168,32 @@ "node": ">=0.10.0" } }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/tinyglobby": { "version": "0.2.17", "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", @@ -2142,6 +2398,67 @@ "peerDependencies": { "typescript": ">=5.0.0" } + }, + "node_modules/which-module": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz", + "integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==", + "license": "ISC" + }, + "node_modules/wrap-ansi": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", + "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/y18n": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", + "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", + "license": "ISC" + }, + "node_modules/yargs": { + "version": "15.4.1", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz", + "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", + "license": "MIT", + "dependencies": { + "cliui": "^6.0.0", + "decamelize": "^1.2.0", + "find-up": "^4.1.0", + "get-caller-file": "^2.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^4.2.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^18.1.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs-parser": { + "version": "18.1.3", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz", + "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", + "license": "ISC", + "dependencies": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + }, + "engines": { + "node": ">=6" + } } } } diff --git a/frontend/package.json b/frontend/package.json index 786291b..62a3365 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -19,11 +19,13 @@ "element-china-area-data": "^6.1.0", "element-plus": "^2.9.1", "pinia": "^2.3.1", + "qrcode": "^1.5.4", "vue": "^3.5.13", "vue-router": "^4.5.0" }, "devDependencies": { "@types/node": "^22.10.2", + "@types/qrcode": "^1.5.6", "@vitejs/plugin-vue": "^5.2.1", "typescript": "~5.7.2", "vite": "^6.0.5", diff --git a/frontend/src/api/wechat.ts b/frontend/src/api/wechat.ts new file mode 100644 index 0000000..a2de4db --- /dev/null +++ b/frontend/src/api/wechat.ts @@ -0,0 +1,73 @@ +import { get, post, del } from '@/utils/request' + +/** 二维码数据(后端申请临时码后返回,前端据此渲染二维码) */ +export interface WechatQrcode { + scene: 'login' | 'bind' + /** 扫码会话标识,轮询状态时回传 */ + state: string + /** 网关临时码(一次性,不用于展示) */ + temp_code: string + /** 二维码内容:网关扫码页地址 */ + page_url: string + /** 二维码有效秒数 */ + expires_in: number +} + +export interface WechatLoginStatus { + status: 'pending' | 'success' | 'unbound' | 'disabled' + message?: string + token?: string + user_id?: number + expires_in?: number +} + +export interface WechatBindStatus { + status: 'pending' | 'success' | 'conflict' | 'failed' + message?: string +} + +export interface WechatBindInfo { + bound: boolean + /** 脱敏后的 openid */ + openid: string + /** 脱敏后的 unionid */ + unionid: string + bind_scene: string + bound_at: string | null + last_login_at: string | null +} + +/** 微信登录是否可用(服务端是否已配置网关应用) */ +export function getWechatEnabled() { + return get<{ enabled: boolean }>('/auth/wechat/enabled') +} + +/** 申请微信登录二维码(无需登录) */ +export function createWechatLoginCode() { + return post('/auth/wechat/login/code') +} + +/** 轮询微信登录结果(结果一次性,取到即失效) */ +export function getWechatLoginStatus(state: string) { + return get('/auth/wechat/login/status', { state }) +} + +/** 申请微信绑定二维码(需登录) */ +export function createWechatBindCode() { + return post('/auth/wechat/bind/code') +} + +/** 轮询微信绑定结果(需登录) */ +export function getWechatBindStatus(state: string) { + return get('/auth/wechat/bind/status', { state }) +} + +/** 查询当前账号的微信绑定信息 */ +export function getWechatBind() { + return get('/auth/wechat/bind') +} + +/** 解绑当前账号的微信 */ +export function unbindWechat() { + return del<{ unbound: boolean }>('/auth/wechat/bind') +} diff --git a/frontend/src/components/QrCode.vue b/frontend/src/components/QrCode.vue new file mode 100644 index 0000000..5371dfd --- /dev/null +++ b/frontend/src/components/QrCode.vue @@ -0,0 +1,67 @@ + + + + + diff --git a/frontend/src/store/auth.ts b/frontend/src/store/auth.ts index 801b7fe..fbe66c4 100644 --- a/frontend/src/store/auth.ts +++ b/frontend/src/store/auth.ts @@ -55,6 +55,13 @@ export const useAuthStore = defineStore('auth', () => { return res } + /** 微信扫码登录:扫码结果由后端轮询接口换成 token,这里只负责落登录态 */ + async function loginByWechatToken(token: string) { + applyToken(token) + await fetchProfile() + await useMenuStore().fetchMenus() + } + /** 注册账号 */ async function register(payload: RegisterPayload) { const res = await registerApi(payload) @@ -104,6 +111,7 @@ export const useAuthStore = defineStore('auth', () => { hasPrincipal, login, loginByEmailCode, + loginByWechatToken, register, sendEmailCode, sendLoginCode, diff --git a/frontend/src/views/Login.vue b/frontend/src/views/Login.vue index 91ed69f..8d75d7a 100644 --- a/frontend/src/views/Login.vue +++ b/frontend/src/views/Login.vue @@ -1,20 +1,30 @@ @@ -357,6 +471,33 @@ onUnmounted(() => { + + + +
+
+ +
+ + {{ wechatHint || '正在准备二维码…' }} +
+
+

请使用微信扫描二维码,并在手机上确认登录

+

+ 二维码 {{ wechatCountdown }} 秒后失效 +

+ + {{ wechatQr ? '刷新二维码' : '重新获取二维码' }} + +
+
@@ -493,4 +634,48 @@ onUnmounted(() => { gap: 8px; margin-top: 14px; } + +.wechat-panel { + display: flex; + flex-direction: column; + align-items: center; + gap: 8px; + padding-top: 4px; +} + +.wechat-qr { + display: flex; + align-items: center; + justify-content: center; + width: 196px; + height: 196px; + border: 1px solid var(--el-border-color-lighter); + border-radius: 6px; + background: #fff; +} + +.wechat-qr-empty { + display: flex; + align-items: center; + justify-content: center; + width: 100%; + height: 100%; + padding: 0 12px; + text-align: center; + font-size: 13px; + line-height: 1.6; + color: var(--el-text-color-secondary); +} + +.wechat-hint { + margin: 0; + font-size: 13px; + color: var(--el-text-color-regular); +} + +.wechat-countdown { + margin: 0; + font-size: 12px; + color: var(--el-text-color-secondary); +} diff --git a/frontend/src/views/User/Profile.vue b/frontend/src/views/User/Profile.vue index 8b58d6f..9f105ed 100644 --- a/frontend/src/views/User/Profile.vue +++ b/frontend/src/views/User/Profile.vue @@ -1,9 +1,20 @@