oms/backend/app/controller/wechatAuth.js
liufumingren 463b7cd1bc feat(employee): 新增员工邮箱改为选填,支持临时账号与微信扫码绑定已有账号
- 新增员工不填邮箱时创建临时账号:自动生成 tmp_ 前缀登录名、邮箱留空、返回初始密码(temporary 标记)
- 员工档案绑定微信:该微信已绑定过账号则把员工切换到该账号(同主体已存在则冲突提示),
  原临时账号无任何主体关联时自动禁用;该微信未绑定账号时直接绑定到员工当前(临时)账号
- 员工编辑支持为临时账号补填邮箱(已绑定邮箱的账号需员工自行在个人设置维护)
- 列表邮箱列对临时账号显示「临时账号」标记;新增结果弹窗提示扫码绑定/补填邮箱
- 接口契约与前端类型同步更新

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

469 lines
17 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(同一账号重新绑定则覆盖,同一微信只能绑一个账号)
*
* 员工档案发起的绑定(state 带 principal_user_id)额外处理「微信已有账号」的情况:
* - 该微信已绑定账号 A 且 A 不是该员工当前账号 → 把员工切换到 A(同一主体下已存在则提示冲突)
* - 该微信未绑定任何账号 → 直接绑定到员工当前账号(临时账号即在此完成「账号 + 绑定」)
* @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 relationId = Number(record.principal_user_id) || 0;
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) {
// 员工档案绑定:该微信已有账号 → 把员工关联到已有账号,而不是报冲突
if (relationId) {
const switched = await this.switchEmployeeAccount(relationId, Number(occupied.user_id));
if (switched.ok) {
await writeResult(app, bindKey(state), {
status: 'success',
message: switched.same ? '绑定成功' : '该微信已有账号,已绑定到该账号',
});
ctx.body = { code: 0, message: 'success' };
return;
}
await writeResult(app, bindKey(state), { status: 'conflict', message: switched.message });
this.fail(new WechatGatewayError(switched.message, 409));
return;
}
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' };
}
/**
* 把员工的系统账号切换为「微信已绑定的账号」
*
* 用于员工档案绑定微信时,扫码的微信此前已绑定过系统账号 A:把员工关联到 A,
* 原临时账号(邮箱为空且不再有任何主体关联)置为禁用,避免遗留可登录的孤儿账号。
* @param {Number} relationId 员工(主体账号关联)ID
* @param {Number} newUserId 微信已绑定的账号ID
* @return {Promise<{ok: Boolean, same?: Boolean, message?: String}>} 切换结果
*/
async switchEmployeeAccount(relationId, newUserId) {
const { ctx } = this;
const relation = await ctx.model.PrincipalUser.findByPk(relationId);
if (!relation) return { ok: false, message: '员工不存在或已被移除' };
const oldUserId = Number(relation.user_id);
if (oldUserId === Number(newUserId)) return { ok: true, same: true };
const target = await ctx.model.User.findByPk(newUserId);
if (!target || Number(target.status) !== 1) {
return { ok: false, message: '该微信绑定的账号不存在或已禁用,请联系管理员' };
}
const dup = await ctx.model.PrincipalUser.findOne({
where: { principal_id: relation.principal_id, user_id: Number(newUserId) },
attributes: [ 'id' ],
});
if (dup) return { ok: false, message: '该微信对应的账号已在当前主体中,无需重复绑定' };
const transaction = await ctx.model.transaction();
try {
await relation.update({ user_id: Number(newUserId) }, { transaction });
await transaction.commit();
} catch (err) {
await transaction.rollback();
ctx.logger.warn(`[wechat] 员工 ${relationId} 切换账号失败:${err.message}`);
return { ok: false, message: '切换账号失败,请稍后重试' };
}
// 原账号是临时账号(无邮箱)且已无任何主体关联 → 禁用,避免遗留可登录的孤儿账号
const oldUser = await ctx.model.User.findByPk(oldUserId);
if (oldUser && !oldUser.email) {
const linked = await ctx.model.PrincipalUser.count({ where: { user_id: oldUserId } });
if (!linked) await oldUser.update({ status: 0 });
}
await ctx.service.cache.invalidateUserPrincipals(oldUserId);
await ctx.service.cache.invalidateUserPrincipals(Number(newUserId));
ctx.logger.info(`[wechat] 员工 ${relationId} 已切换到微信账号 ${newUserId}(原账号 ${oldUserId})`);
return { ok: true };
}
/**
* 处理登录通知:按 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;