oms/backend/app/controller/wechatAuth.js
liufumingren 1847e17ba7 feat(auth): 接入微信扫码登录与微信绑定
- 新增网关客户端与通知验签(sha256(appSecret) 派生 HMAC-SHA256,5 分钟防重放),
  扫码会话与一次性结果存 Redis,openid 仅服务端保存
- 新增 user_wechat_binds 表与迁移:openid 唯一(一个微信只绑一个账号)、
  user_id 唯一(重新绑定覆盖旧微信)
- 新增 /api/auth/wechat/* 接口与 /api/wx/notify 网关回调;登录二维码按 IP 限流,
  未配置网关时相关接口返回 400 提示,不影响账号密码 / 邮箱验证码登录
- 前端:「微信登录」tab(二维码 + 倒计时 + 轮询)与「我的」页微信绑定 / 解绑
- 开发与生产各出一份 WX_GATEWAY_* 配置样板,生产权威副本走 shared-config 覆盖
- 同步补充 swagger 契约与请求日志脱敏字段(bind_code / sign)

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-01 23:17:11 +08:00

399 lines
14 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'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<void>} 无返回值
*/
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<void>} 无返回值
*/
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;