- 新增 user_app / user_identity 模型、应用注册表与成员关系服务,启动时校验配置覆盖 - 新增微信开放平台扫码登录:二维码地址、回调与 ticket 换取 token - 管理端接口改为路由层声明 appIds + 角色鉴权,新增批量用户信息、锁定、授权与个人配置 - 删除账号同步清理成员关系与外部身份,避免关系被新账号复用 - 补充多应用、应用配置、注册表测试与迁移/建号脚本
1263 lines
45 KiB
JavaScript
1263 lines
45 KiB
JavaScript
import Joi from 'joi';
|
||
import mongoose from 'mongoose';
|
||
import { DBModel } from "../models/index.js";
|
||
import ResponseUtil from "../utils/api_response.js";
|
||
import { hashPassword, verifyPassword, hashToken } from "../utils/crypto.js";
|
||
import { sanitizeUser } from "../middleware/auth.js";
|
||
import { APP_REGISTRY, GRANTABLE_ROLES } from "../models/app_registry.js";
|
||
import {
|
||
hasConfigSchema,
|
||
validateAppConfig,
|
||
resolveConfig,
|
||
flattenLeaves,
|
||
} from "../models/app_config.js";
|
||
import {
|
||
backfillOneFromLegacy,
|
||
upsertIdentity,
|
||
upsertLoginMembership,
|
||
grantRoles,
|
||
revokeRoles,
|
||
} from "../models/user_membership.js";
|
||
import config from "../conf.json" with { type: "json" };
|
||
|
||
// 微信 access_token 进程内缓存(有效期 7200s,提前 5 分钟刷新)
|
||
const wxAccessTokenCache = new Map();
|
||
|
||
// 微信接口超时:微信侧偶发慢响应,不设超时会让请求一直挂起并占用连接
|
||
const WX_REQUEST_TIMEOUT = 8000;
|
||
|
||
// 手机号格式与字段长度上限:格式统一账号体系,长度防止超大字段写满 16MB 文档
|
||
const MOBILE_PATTERN = /^1[3-9]\d{9}$/;
|
||
const NAME_MAX = 50;
|
||
|
||
// ==================== 微信扫码登录(开放平台网站应用) ====================
|
||
|
||
// Web 后台的 appId 与扫码登录 provider,与小程序端完全隔离
|
||
const WEB_ADMIN_APP = "web-escort-admin";
|
||
const WECHAT_WEB_PROVIDER = "weixin-web";
|
||
const QR_STATE_TTL = 5 * 60 * 1000;
|
||
const QR_TICKET_TTL = 60 * 1000;
|
||
const QR_STORE_LIMIT = 2000;
|
||
|
||
// state / ticket 都是一次性短生命周期数据,放进程内即可。
|
||
// 多实例部署时需换 Redis,否则回调可能落到没有对应 state 的实例
|
||
const qrStateStore = new Map();
|
||
const qrTicketStore = new Map();
|
||
|
||
function pruneStore(store, now) {
|
||
for (const [key, value] of store) {
|
||
if (value.expiresAt <= now) store.delete(key);
|
||
}
|
||
// 上限保护:异常刷接口时按插入顺序淘汰最早的
|
||
while (store.size > QR_STORE_LIMIT) {
|
||
store.delete(store.keys().next().value);
|
||
}
|
||
}
|
||
|
||
function wechatWebConfig() {
|
||
// 与小程序共用 config.app:appid/secret 走同一处配置,扫码专用参数挂在同一条目下
|
||
const cfg = config.app?.[WEB_ADMIN_APP] || {};
|
||
return {
|
||
appid: String(cfg.appid || "").trim(),
|
||
secret: String(cfg.secret || "").trim(),
|
||
callbackUri: String(cfg.callbackUri || "").trim(),
|
||
webOrigin: String(cfg.webOrigin || "").trim().replace(/\/+$/, ""),
|
||
};
|
||
}
|
||
|
||
function isWechatWebReady(cfg) {
|
||
return !!(cfg.appid && cfg.secret && cfg.callbackUri && cfg.webOrigin);
|
||
}
|
||
|
||
async function getWxAccessToken(appConfig) {
|
||
const cached = wxAccessTokenCache.get(appConfig.appid);
|
||
if (cached && Date.now() < cached.expiresAt) {
|
||
return cached.token;
|
||
}
|
||
const tokenUrl = `https://api.weixin.qq.com/cgi-bin/token?appid=${appConfig.appid}&secret=${appConfig.secret}&grant_type=client_credential`;
|
||
const response = await fetch(tokenUrl, { signal: AbortSignal.timeout(WX_REQUEST_TIMEOUT) });
|
||
const resp = await response.json();
|
||
if (!resp.access_token) {
|
||
throw new Error(resp.errmsg || "获取微信 access_token 失败");
|
||
}
|
||
wxAccessTokenCache.set(appConfig.appid, {
|
||
token: resp.access_token,
|
||
expiresAt: Date.now() + ((resp.expires_in || 7200) - 300) * 1000,
|
||
});
|
||
return resp.access_token;
|
||
}
|
||
|
||
// 输入校验 schema
|
||
const registerSchema = Joi.object({
|
||
userInfo: Joi.object({
|
||
profile: Joi.object({
|
||
mobile: Joi.string().pattern(MOBILE_PATTERN).required().messages({
|
||
'any.required': '缺少手机号',
|
||
'string.empty': '手机号不能为空',
|
||
'string.pattern.base': '手机号格式不正确',
|
||
}),
|
||
name: Joi.string().allow('').max(NAME_MAX).messages({
|
||
'string.max': `姓名不能超过 ${NAME_MAX} 个字符`,
|
||
}),
|
||
}).required(),
|
||
security: Joi.object({
|
||
passwd: Joi.string().min(6).max(72).required().messages({
|
||
'any.required': '缺少密码',
|
||
'string.min': '密码至少6位',
|
||
'string.max': '密码过长',
|
||
}),
|
||
}).required(),
|
||
location: Joi.object({
|
||
province: Joi.string().allow(''),
|
||
city: Joi.string().allow(''),
|
||
district: Joi.string().allow(''),
|
||
}).optional(),
|
||
addresses: Joi.array().optional(),
|
||
// 不接受客户端 app:app 里的角色决定管理端权限,只能由服务端/库内维护,
|
||
// 否则任何人都能在注册时自封管理员(历史漏洞)。
|
||
}).required(),
|
||
});
|
||
|
||
const signinSchema = Joi.object({
|
||
mobile: Joi.string().required().messages({
|
||
'any.required': '缺少手机号',
|
||
'string.empty': '手机号不能为空'
|
||
}),
|
||
passwd: Joi.string().required().messages({
|
||
'any.required': '缺少密码',
|
||
'string.empty': '密码不能为空'
|
||
}),
|
||
});
|
||
|
||
const wxSigninSchema = Joi.object({
|
||
code: Joi.string().max(128).required().messages({ 'any.required': '缺少微信登录凭证 code' }),
|
||
appId: Joi.string().required().messages({ 'any.required': '缺少 appId' }),
|
||
// 推荐:传微信手机号凭证 code,由服务端换取手机号(可信)
|
||
phoneCode: Joi.string().max(128).allow('', null),
|
||
// 已废弃(不安全):客户端直传手机号,仅允许用于新建账号
|
||
phoneNumber: Joi.string().pattern(MOBILE_PATTERN).allow('', null).messages({
|
||
'string.pattern.base': '手机号格式不正确',
|
||
}),
|
||
name: Joi.string().max(NAME_MAX).allow('', null),
|
||
});
|
||
|
||
const wxGetPhoneSchema = Joi.object({
|
||
code: Joi.string().max(128).required().messages({ 'any.required': '缺少手机号凭证 code' }),
|
||
appId: Joi.string().required().messages({ 'any.required': '缺少 appId' }),
|
||
});
|
||
|
||
const appConfigSchema = Joi.object({
|
||
appId: Joi.string().required().messages({ 'any.required': '缺少 appId' }),
|
||
config: Joi.object().required().messages({ 'any.required': '缺少 config' }),
|
||
});
|
||
|
||
const grantSchema = Joi.object({
|
||
userId: Joi.string().hex().length(24).required().messages({
|
||
'any.required': '缺少用户ID',
|
||
'string.hex': '用户ID不合法',
|
||
'string.length': '用户ID不合法',
|
||
}),
|
||
appId: Joi.string().required().messages({ 'any.required': '缺少 appId' }),
|
||
action: Joi.string().valid('grant', 'revoke').required().messages({
|
||
'any.required': '缺少 action',
|
||
'any.only': 'action 只能是 grant 或 revoke',
|
||
}),
|
||
roles: Joi.array().items(Joi.string()).default(['admin']),
|
||
});
|
||
|
||
const LOCK_AFTER_FAILED_ATTEMPTS = 10;
|
||
|
||
function groupByUserId(list) {
|
||
const map = new Map();
|
||
for (const item of list) {
|
||
const key = String(item.userId);
|
||
if (!map.has(key)) map.set(key, []);
|
||
map.get(key).push(item);
|
||
}
|
||
return map;
|
||
}
|
||
|
||
/**
|
||
* R2 单点适配层:app 与 apps 只能在这里生成。
|
||
*
|
||
* - apps:新表投影,config 合并默认值后返回
|
||
* - app :过渡期兼容视图,以库里旧 app 为基底保留 tcm.organization 等历史字段,
|
||
* 再用新表覆盖 role / wxopenid。这样原应用不改代码也能继续工作,
|
||
* 下个版本下游全部改读 apps 后再移除。
|
||
*/
|
||
async function buildUserViews(users) {
|
||
const list = (users || []).filter(Boolean);
|
||
if (!list.length) return [];
|
||
|
||
const ids = list.map((user) => user._id);
|
||
const [memberships, identities] = await Promise.all([
|
||
DBModel.UserApp.find({ userId: { $in: ids } }).sort({ appId: 1 }).lean(),
|
||
DBModel.UserIdentity.find({ userId: { $in: ids }, openid: { $exists: true } })
|
||
.sort({ appId: 1 })
|
||
.lean(),
|
||
]);
|
||
|
||
const membershipsByUser = groupByUserId(memberships);
|
||
const identitiesByUser = groupByUserId(identities);
|
||
|
||
return list.map((user) => {
|
||
const safe = sanitizeUser(user);
|
||
const key = String(user._id);
|
||
const userMemberships = membershipsByUser.get(key) || [];
|
||
const userIdentities = identitiesByUser.get(key) || [];
|
||
|
||
const apps = userMemberships.map((membership) => ({
|
||
appId: membership.appId,
|
||
roles: membership.roles || [],
|
||
status: membership.status,
|
||
config: resolveConfig(membership.appId, membership.config),
|
||
}));
|
||
|
||
const baseApp = safe.app && typeof safe.app === 'object' && !Array.isArray(safe.app)
|
||
? safe.app
|
||
: {};
|
||
const legacyApp = { ...baseApp };
|
||
|
||
for (const membership of userMemberships) {
|
||
const identity = userIdentities.find(
|
||
(item) => item.appId === membership.appId && item.openid
|
||
);
|
||
const existing = legacyApp[membership.appId]
|
||
&& typeof legacyApp[membership.appId] === 'object'
|
||
? legacyApp[membership.appId]
|
||
: {};
|
||
|
||
legacyApp[membership.appId] = {
|
||
...existing,
|
||
role: membership.roles || [],
|
||
...(identity?.openid ? { wxopenid: identity.openid } : {}),
|
||
};
|
||
}
|
||
|
||
return { ...safe, apps, app: legacyApp };
|
||
});
|
||
}
|
||
|
||
async function buildUserView(user) {
|
||
const [view] = await buildUserViews([user]);
|
||
return view;
|
||
}
|
||
|
||
class HandlerUser {
|
||
// 生成 token(DB 中只存哈希,原始 token 仅在登录响应中返回一次)
|
||
// 必须用 CSPRNG:Math.random 的输出可预测,token 可预测就等于可冒充任意用户
|
||
async genToken() {
|
||
const crypto = await import("crypto");
|
||
return crypto.randomBytes(32).toString("hex");
|
||
}
|
||
|
||
// 签发 token:哈希入库,返回原始值供响应
|
||
async issueToken(user) {
|
||
const raw = await this.genToken();
|
||
user.security.token = await hashToken(raw);
|
||
user.security.tokenExpiry = new Date(Date.now() + 15 * 24 * 60 * 60 * 1000);
|
||
user.security.lastLoginAt = new Date();
|
||
await user.save();
|
||
return { raw, tokenExpiry: user.security.tokenExpiry };
|
||
}
|
||
|
||
// 登录/注册响应:脱敏后单独附加本次签发的原始 token
|
||
async buildLoginResponse(user, raw) {
|
||
const safe = await buildUserView(user);
|
||
safe.security = safe.security || {};
|
||
safe.security.token = raw;
|
||
safe.security.tokenExpiry = user.security.tokenExpiry;
|
||
return safe;
|
||
}
|
||
|
||
// 用户注册
|
||
async register(ctx) {
|
||
const { error, value } = registerSchema.validate(ctx.request.body, { abortEarly: false });
|
||
if (error) {
|
||
return ResponseUtil.badRequest(ctx, error.details[0].message);
|
||
}
|
||
|
||
try {
|
||
const { userInfo } = value;
|
||
const mobile = userInfo.profile.mobile;
|
||
const passwd = userInfo.security.passwd;
|
||
|
||
// 检查手机号是否已注册
|
||
const existingUser = await DBModel.User.findOne({ "profile.mobile": mobile });
|
||
if (existingUser) {
|
||
return ResponseUtil.error(ctx, "手机号已注册", null, 409);
|
||
}
|
||
|
||
// bcrypt 加密密码
|
||
const encryptedPasswd = await hashPassword(passwd);
|
||
|
||
const newUser = {
|
||
profile: userInfo.profile,
|
||
security: {
|
||
passwd: encryptedPasswd,
|
||
},
|
||
location: {
|
||
province: userInfo.location?.province || '',
|
||
city: userInfo.location?.city || '',
|
||
district: userInfo.location?.district || '',
|
||
},
|
||
addresses: userInfo.addresses || [],
|
||
social: {
|
||
wechat: {}
|
||
},
|
||
status: {
|
||
account: "normal",
|
||
},
|
||
// 注册一律不带 app:管理端角色只能由服务端在库内授予
|
||
app: {},
|
||
};
|
||
|
||
// 手机号唯一性由库内唯一索引兜底(先查后插在并发下存在竞态)
|
||
const user = await DBModel.User.create(newUser);
|
||
|
||
// 生成 token(哈希入库,响应附原始 token)
|
||
const { raw } = await this.issueToken(user);
|
||
|
||
return ResponseUtil.success(ctx, { user: await this.buildLoginResponse(user, raw) }, "注册成功");
|
||
} catch (err) {
|
||
if (err?.code === 11000) {
|
||
return ResponseUtil.error(ctx, "手机号已注册", null, 409);
|
||
}
|
||
return ResponseUtil.internalError(ctx, err);
|
||
}
|
||
}
|
||
|
||
// 手机号码登录
|
||
async signin(ctx) {
|
||
const { error, value } = signinSchema.validate(ctx.request.body, { abortEarly: false });
|
||
if (error) {
|
||
return ResponseUtil.badRequest(ctx, error.details[0].message);
|
||
}
|
||
|
||
try {
|
||
const { mobile, passwd } = value;
|
||
|
||
// 查找用户
|
||
let user = await DBModel.User.findOne({ "profile.mobile": mobile });
|
||
// 不区分「用户不存在」与「密码错误」:避免被用来枚举已注册手机号
|
||
if (!user) {
|
||
return ResponseUtil.unauthorized(ctx, "账号或密码错误");
|
||
}
|
||
|
||
// 锁定账户拒绝登录
|
||
if (user.status.account === "lock") {
|
||
return ResponseUtil.forbidden(ctx, "账户已被锁定,请联系管理员");
|
||
}
|
||
|
||
// 校验密码(支持 bcrypt 和 MD5 渐进式迁移)
|
||
const { valid, needsUpgrade } = await verifyPassword(
|
||
passwd, user.security.passwd, user.security.passwdSalt
|
||
);
|
||
|
||
if (!valid) {
|
||
// 记录失败登录次数,达到阈值锁定账户
|
||
const updated = await DBModel.User.incrementFailedLoginAttempts(user._id);
|
||
if (updated && updated.security.failedLoginAttempts >= LOCK_AFTER_FAILED_ATTEMPTS) {
|
||
updated.status.account = "lock";
|
||
await updated.save();
|
||
return ResponseUtil.forbidden(ctx, "失败次数过多,账户已锁定,请联系管理员");
|
||
}
|
||
return ResponseUtil.unauthorized(ctx, "账号或密码错误");
|
||
}
|
||
|
||
// 渐进式迁移:如果是旧 MD5 密码,登录时升级为 bcrypt
|
||
if (needsUpgrade) {
|
||
user.security.passwd = await hashPassword(passwd);
|
||
user.security.passwdSalt = undefined;
|
||
}
|
||
|
||
// 重置失败登录次数
|
||
if (user.security.failedLoginAttempts > 0) {
|
||
await DBModel.User.resetFailedLoginAttempts(user._id);
|
||
}
|
||
|
||
// 生成/更新 token(哈希入库)
|
||
user.security.lastLoginIp = ctx.ip || ctx.request.ip;
|
||
const { raw } = await this.issueToken(user);
|
||
|
||
return ResponseUtil.success(ctx, { user: await this.buildLoginResponse(user, raw) }, "登录成功");
|
||
} catch (err) {
|
||
return ResponseUtil.internalError(ctx, err);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 生成微信扫码登录地址
|
||
*
|
||
* mode=login:未登录可调用,扫码后登录后台
|
||
* mode=bind :需要已登录,扫码后把该微信绑定到当前账号(不改变任何角色)
|
||
*/
|
||
async wechatQrUrl(ctx) {
|
||
const cfg = wechatWebConfig();
|
||
if (!isWechatWebReady(cfg)) {
|
||
return ResponseUtil.error(ctx, "未配置微信扫码登录,请联系管理员", null, 503);
|
||
}
|
||
|
||
const mode = ctx.request.query.mode === "bind" ? "bind" : "login";
|
||
const current = ctx.state.user;
|
||
if (mode === "bind" && !current) {
|
||
return ResponseUtil.unauthorized(ctx, "绑定微信需要先登录");
|
||
}
|
||
|
||
const now = Date.now();
|
||
pruneStore(qrStateStore, now);
|
||
|
||
const crypto = await import("crypto");
|
||
const state = crypto.randomBytes(16).toString("hex");
|
||
qrStateStore.set(state, {
|
||
mode,
|
||
userId: current?._id ? String(current._id) : null,
|
||
expiresAt: now + QR_STATE_TTL,
|
||
});
|
||
|
||
const url = "https://open.weixin.qq.com/connect/qrconnect"
|
||
+ `?appid=${encodeURIComponent(cfg.appid)}`
|
||
+ `&redirect_uri=${encodeURIComponent(cfg.callbackUri)}`
|
||
+ "&response_type=code&scope=snsapi_login"
|
||
+ `&state=${state}#wechat_redirect`;
|
||
|
||
return ResponseUtil.success(ctx, {
|
||
url,
|
||
state,
|
||
mode,
|
||
expiresIn: Math.floor(QR_STATE_TTL / 1000),
|
||
}, "获取成功");
|
||
}
|
||
|
||
/**
|
||
* 微信扫码回调(浏览器 302 跳转,不走 JSON)
|
||
*
|
||
* 安全红线:扫码只解决「你是谁」,不解决「你能不能进后台」。
|
||
* 没有 web-escort-admin 的 admin 成员关系一律拒绝,绝不自动创建账号或授权。
|
||
*/
|
||
async wechatQrCallback(ctx) {
|
||
const cfg = wechatWebConfig();
|
||
if (!isWechatWebReady(cfg)) {
|
||
return ResponseUtil.error(ctx, "未配置微信扫码登录", null, 503);
|
||
}
|
||
|
||
const redirectError = (code) => {
|
||
ctx.redirect(`${cfg.webOrigin}/auth/wechat-callback?error=${encodeURIComponent(code)}`);
|
||
};
|
||
|
||
const state = ctx.request.query.state ? String(ctx.request.query.state) : "";
|
||
const record = state ? qrStateStore.get(state) : null;
|
||
// state 一次性:无论后续成功失败都不能复用
|
||
if (state) qrStateStore.delete(state);
|
||
|
||
if (!record || record.expiresAt <= Date.now()) {
|
||
return redirectError("state_invalid");
|
||
}
|
||
|
||
const code = ctx.request.query.code ? String(ctx.request.query.code) : "";
|
||
// 用户取消授权时微信只回 state,不回 code
|
||
if (!code) return redirectError("cancelled");
|
||
|
||
try {
|
||
const tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token"
|
||
+ `?appid=${encodeURIComponent(cfg.appid)}`
|
||
+ `&secret=${encodeURIComponent(cfg.secret)}`
|
||
+ `&code=${encodeURIComponent(code)}`
|
||
+ "&grant_type=authorization_code";
|
||
const resp = await fetch(tokenUrl, { signal: AbortSignal.timeout(WX_REQUEST_TIMEOUT) });
|
||
const data = await resp.json();
|
||
|
||
if (!data?.openid) {
|
||
return redirectError("wechat_failed");
|
||
}
|
||
|
||
// 绑定模式:只写身份,不碰角色和成员状态
|
||
if (record.mode === "bind") {
|
||
if (!record.userId) return redirectError("bind_user_missing");
|
||
|
||
// openid 已属于其他账号时给出明确冲突提示,而不是兜底成 server_error
|
||
try {
|
||
await upsertIdentity({
|
||
userId: record.userId,
|
||
appId: WEB_ADMIN_APP,
|
||
platform: "weixin",
|
||
provider: WECHAT_WEB_PROVIDER,
|
||
openid: data.openid,
|
||
unionid: data.unionid,
|
||
});
|
||
} catch (err) {
|
||
if (err?.code === 11000) return redirectError("identity_conflict");
|
||
throw err;
|
||
}
|
||
|
||
return ctx.redirect(`${cfg.webOrigin}/auth/wechat-callback?bound=1`);
|
||
}
|
||
|
||
// 登录模式:本应用 openid → unionid 跨应用 → 旧字段兜底
|
||
const identity = await DBModel.UserIdentity.findOne({
|
||
appId: WEB_ADMIN_APP,
|
||
provider: WECHAT_WEB_PROVIDER,
|
||
openid: data.openid,
|
||
});
|
||
let user = identity ? await DBModel.User.findById(identity.userId) : null;
|
||
|
||
if (!user && data.unionid) {
|
||
const samePerson = await DBModel.UserIdentity.findOne({
|
||
provider: WECHAT_WEB_PROVIDER,
|
||
unionid: data.unionid,
|
||
});
|
||
if (samePerson) user = await DBModel.User.findById(samePerson.userId);
|
||
}
|
||
if (!user) {
|
||
user = await DBModel.User.findOne({ [`app.${WEB_ADMIN_APP}.wxopenid`]: data.openid });
|
||
}
|
||
|
||
if (!user) return redirectError("not_bound");
|
||
if (user.status?.account === "lock") return redirectError("locked");
|
||
|
||
const membership = await DBModel.UserApp.findOne({
|
||
userId: user._id,
|
||
appId: WEB_ADMIN_APP,
|
||
status: "active",
|
||
roles: "admin",
|
||
});
|
||
if (!membership) return redirectError("forbidden");
|
||
|
||
// openid 已绑到其他账号时触发唯一索引,按冲突处理,不做静默改绑
|
||
try {
|
||
await upsertIdentity({
|
||
userId: user._id,
|
||
appId: WEB_ADMIN_APP,
|
||
platform: "weixin",
|
||
provider: WECHAT_WEB_PROVIDER,
|
||
openid: data.openid,
|
||
unionid: data.unionid,
|
||
});
|
||
} catch (err) {
|
||
if (err?.code === 11000) return redirectError("identity_conflict");
|
||
throw err;
|
||
}
|
||
|
||
await DBModel.UserApp.updateOne(
|
||
{ _id: membership._id },
|
||
{ $set: { lastLoginAt: new Date() } }
|
||
);
|
||
|
||
// 回调地址在前端,token 不能放 URL(会进浏览器历史和 nginx 日志),
|
||
// 只带一个 60 秒有效、一次性的 ticket,由前端换取 token
|
||
const now = Date.now();
|
||
pruneStore(qrTicketStore, now);
|
||
const crypto = await import("crypto");
|
||
const ticket = crypto.randomBytes(24).toString("hex");
|
||
qrTicketStore.set(ticket, { userId: String(user._id), expiresAt: now + QR_TICKET_TTL });
|
||
|
||
return ctx.redirect(`${cfg.webOrigin}/auth/wechat-callback?ticket=${ticket}`);
|
||
} catch (err) {
|
||
console.error("[wechat-qr] 回调处理失败:", err.message);
|
||
return redirectError("server_error");
|
||
}
|
||
}
|
||
|
||
// 用一次性 ticket 换取 token
|
||
async wechatQrExchange(ctx) {
|
||
const ticket = ctx.request.body?.ticket ? String(ctx.request.body.ticket) : "";
|
||
if (!ticket) return ResponseUtil.badRequest(ctx, "缺少 ticket");
|
||
|
||
const record = qrTicketStore.get(ticket);
|
||
if (record) qrTicketStore.delete(ticket);
|
||
|
||
if (!record || record.expiresAt <= Date.now()) {
|
||
return ResponseUtil.unauthorized(ctx, "登录凭证已失效,请重新扫码");
|
||
}
|
||
|
||
try {
|
||
const user = await DBModel.User.findById(record.userId);
|
||
if (!user) return ResponseUtil.unauthorized(ctx, "账号不存在");
|
||
if (user.status?.account === "lock") return ResponseUtil.forbidden(ctx, "账户已被锁定");
|
||
|
||
const membership = await DBModel.UserApp.findOne({
|
||
userId: user._id,
|
||
appId: WEB_ADMIN_APP,
|
||
status: "active",
|
||
roles: "admin",
|
||
});
|
||
if (!membership) return ResponseUtil.forbidden(ctx, "无后台管理权限");
|
||
|
||
const { raw } = await this.issueToken(user);
|
||
return ResponseUtil.success(ctx, { user: await this.buildLoginResponse(user, raw) }, "登录成功");
|
||
} catch (err) {
|
||
return ResponseUtil.internalError(ctx, err);
|
||
}
|
||
}
|
||
|
||
// 退出登录
|
||
async signout(ctx) {
|
||
// auth({required:false}) 中间件已验证登录态
|
||
const user = ctx.state.user;
|
||
if (user) {
|
||
user.security.token = null;
|
||
user.security.tokenExpiry = null;
|
||
await user.save();
|
||
}
|
||
|
||
return ResponseUtil.success(ctx, null, "退出登录成功");
|
||
}
|
||
|
||
// 获取用户信息
|
||
async userInfo(ctx) {
|
||
// 已通过 auth 中间件验证的登录用户
|
||
if (ctx.state.user) {
|
||
const user = await buildUserView(ctx.state.user);
|
||
return ResponseUtil.success(ctx, { user }, "获取用户信息成功");
|
||
}
|
||
|
||
// 不再支持「凭 userId 明文查询」:用户ID不是凭证,
|
||
// 任何人都可能通过日志/链接拿到他人 userId,若可据此读取资料即构成越权。
|
||
// 一律要求携带有效 token,身份以 token 为准。
|
||
return ResponseUtil.badRequest(ctx, "缺少 token");
|
||
}
|
||
|
||
// 更新用户信息
|
||
async updateUser(ctx) {
|
||
// auth() 中间件已验证登录态
|
||
const user = ctx.state.user;
|
||
if (!user) {
|
||
return ResponseUtil.unauthorized(ctx, "用户未登录或 token 无效");
|
||
}
|
||
|
||
try {
|
||
const userInfo = ctx.request.body;
|
||
if (!userInfo) {
|
||
return ResponseUtil.badRequest(ctx, "缺少用户信息");
|
||
}
|
||
|
||
// updateFromUserInfo 是白名单取字段,这里只补最小防护:
|
||
// 手机号格式统一,addresses 限数组且限长(防止超大文档写入)
|
||
if (userInfo.profile?.mobile !== undefined
|
||
&& !MOBILE_PATTERN.test(String(userInfo.profile.mobile))) {
|
||
return ResponseUtil.badRequest(ctx, "手机号格式不正确");
|
||
}
|
||
if (userInfo.addresses !== undefined
|
||
&& (!Array.isArray(userInfo.addresses) || userInfo.addresses.length > 50)) {
|
||
return ResponseUtil.badRequest(ctx, "地址列表不合法");
|
||
}
|
||
|
||
const updatedUser = await DBModel.User.updateFromUserInfo(user._id, userInfo);
|
||
if (!updatedUser) {
|
||
return ResponseUtil.internalError(ctx, "更新用户失败");
|
||
}
|
||
|
||
return ResponseUtil.success(ctx, { user: await buildUserView(updatedUser) }, "更新成功");
|
||
} catch (err) {
|
||
// 字段校验失败(如 sex 非法枚举)应返回 400 而不是 500
|
||
if (err?.name === "ValidationError") {
|
||
return ResponseUtil.badRequest(ctx, err.message);
|
||
}
|
||
// 手机号允许用户自助修改,但必须是全局唯一的:撞号时给出明确提示而不是通用错误
|
||
if (err?.code === 11000) {
|
||
return ResponseUtil.error(ctx, "该手机号已被使用", null, 409);
|
||
}
|
||
return ResponseUtil.internalError(ctx, err);
|
||
}
|
||
}
|
||
|
||
// 获取用户列表
|
||
async userList(ctx) {
|
||
// 鉴权已由路由层 auth({ appIds, roles }) 完成
|
||
if (!ctx.state.user) {
|
||
return ResponseUtil.unauthorized(ctx, "用户未登录或 token 无效");
|
||
}
|
||
|
||
try {
|
||
const page = Math.max(1, parseInt(ctx.request.body?.page) || 1);
|
||
const pageSize = Math.min(200, Math.max(1, parseInt(ctx.request.body?.pageSize) || 100));
|
||
const { keyword, accountStatus, startDate, endDate } = ctx.request.body || {};
|
||
|
||
// total 现在是「该应用的有效成员数」,不再是「登录过该小程序的人数」
|
||
const membershipMatch = { appId: "wxapp-escort", status: "active" };
|
||
const userMatch = {};
|
||
|
||
if (keyword && String(keyword).trim()) {
|
||
// 关键词转义,避免用户输入的括号等字符被当成正则元字符
|
||
const safe = String(keyword).trim().replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||
const reg = new RegExp(safe, "i");
|
||
userMatch.$or = [
|
||
{ "userDoc.profile.name": reg },
|
||
{ "userDoc.profile.mobile": reg },
|
||
{ "userDoc.profile.email": reg },
|
||
{ "userDoc.profile.pinyin": reg },
|
||
];
|
||
}
|
||
|
||
if (accountStatus) {
|
||
if (!["normal", "lock"].includes(accountStatus)) {
|
||
return ResponseUtil.badRequest(ctx, "账号状态筛选值不正确");
|
||
}
|
||
userMatch["userDoc.status.account"] = accountStatus;
|
||
}
|
||
|
||
// 注册时间范围:meta.createtime 存的是 Date,按 UTC 日界换算
|
||
const parseDay = (value) => {
|
||
if (!value || !/^\d{4}-\d{2}-\d{2}$/.test(String(value))) return null;
|
||
const date = new Date(`${value}T00:00:00.000Z`);
|
||
return Number.isNaN(date.getTime()) ? null : date;
|
||
};
|
||
const from = parseDay(startDate);
|
||
const to = parseDay(endDate);
|
||
if (from || to) {
|
||
userMatch["userDoc.meta.createtime"] = {};
|
||
if (from) userMatch["userDoc.meta.createtime"].$gte = from;
|
||
if (to) {
|
||
to.setUTCDate(to.getUTCDate() + 1); // 含结束日当天
|
||
userMatch["userDoc.meta.createtime"].$lt = to;
|
||
}
|
||
}
|
||
|
||
// 以 user_app 为分页主体,$lookup 用户表后再应用搜索/状态/时间筛选,
|
||
// 这样权限口径是「有效成员」,同时保留原管理端的筛选与创建时间倒序。
|
||
const basePipeline = [
|
||
{ $match: membershipMatch },
|
||
{
|
||
$lookup: {
|
||
from: "user",
|
||
localField: "userId",
|
||
foreignField: "_id",
|
||
as: "userDoc",
|
||
},
|
||
},
|
||
{ $unwind: "$userDoc" },
|
||
];
|
||
if (Object.keys(userMatch).length) basePipeline.push({ $match: userMatch });
|
||
|
||
const [rows, totalRows] = await Promise.all([
|
||
DBModel.UserApp.aggregate([
|
||
...basePipeline,
|
||
{ $sort: { "userDoc.meta.createtime": -1, "userDoc._id": -1 } },
|
||
{ $skip: (page - 1) * pageSize },
|
||
{ $limit: pageSize },
|
||
]).exec(),
|
||
DBModel.UserApp.aggregate([...basePipeline, { $count: "total" }]).exec(),
|
||
]);
|
||
|
||
const users = rows.map((row) => row.userDoc);
|
||
const total = totalRows[0]?.total || 0;
|
||
const safeUsers = await buildUserViews(users);
|
||
|
||
return ResponseUtil.success(ctx, { users: safeUsers, total, page, pageSize }, "获取用户列表成功");
|
||
} catch (err) {
|
||
return ResponseUtil.internalError(ctx, err);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 管理端批量取用户基础信息
|
||
*
|
||
* 用途:就诊人列表/订单列表只存 userId,前端需要展示归属用户昵称与手机号。
|
||
* 走批量而不是让前端逐行查,避免 N+1;ids 上限 100 与列表分页量级对齐
|
||
*/
|
||
async batchUserInfo(ctx) {
|
||
const current = ctx.state.user;
|
||
if (!current) {
|
||
return ResponseUtil.unauthorized(ctx, "用户未登录或 token 无效");
|
||
}
|
||
|
||
try {
|
||
const rawIds = ctx.request.body?.userIds;
|
||
if (!Array.isArray(rawIds) || rawIds.length === 0) {
|
||
return ResponseUtil.badRequest(ctx, "缺少用户ID列表");
|
||
}
|
||
|
||
const ids = [...new Set(rawIds.map((id) => String(id || "").trim()))]
|
||
.filter((id) => /^[0-9a-fA-F]{24}$/.test(id));
|
||
|
||
if (!ids.length) {
|
||
return ResponseUtil.badRequest(ctx, "用户ID列表不合法");
|
||
}
|
||
if (ids.length > 100) {
|
||
return ResponseUtil.badRequest(ctx, "单次最多查询 100 个用户");
|
||
}
|
||
|
||
const users = await DBModel.User.find({ _id: { $in: ids } });
|
||
const safeUsers = await buildUserViews(users);
|
||
return ResponseUtil.success(ctx, { users: safeUsers }, "查询成功");
|
||
} catch (err) {
|
||
return ResponseUtil.internalError(ctx, err);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 锁定 / 解锁账号
|
||
*
|
||
* 只改 status.account(枚举只有 normal / lock),并在解锁时清零失败登录次数,
|
||
* 与 doc/backend-architecture.md 里「解锁需手动改库」的遗留事项对应。
|
||
* 锁定会同时作废 token:否则已登录会话在 health 侧最多还能用 5 分钟
|
||
*/
|
||
async lockUser(ctx) {
|
||
const current = ctx.state.user;
|
||
if (!current) {
|
||
return ResponseUtil.unauthorized(ctx, "用户未登录或 token 无效");
|
||
}
|
||
|
||
try {
|
||
const { userId, locked } = ctx.request.body || {};
|
||
if (!userId || !/^[0-9a-fA-F]{24}$/.test(String(userId))) {
|
||
return ResponseUtil.badRequest(ctx, "用户ID不合法");
|
||
}
|
||
if (typeof locked !== "boolean") {
|
||
return ResponseUtil.badRequest(ctx, "缺少 locked 参数");
|
||
}
|
||
// 防止管理员把自己锁在门外
|
||
if (String(userId) === String(current._id)) {
|
||
return ResponseUtil.badRequest(ctx, "不能修改当前登录账号的锁定状态");
|
||
}
|
||
|
||
const set = {
|
||
"status.account": locked ? "lock" : "normal",
|
||
"meta.updatetime": Date.now(),
|
||
};
|
||
if (locked) {
|
||
// 作废已有会话,避免锁定了却还能继续用旧 token
|
||
set["security.token"] = null;
|
||
set["security.tokenExpiry"] = null;
|
||
} else {
|
||
set["security.failedLoginAttempts"] = 0;
|
||
}
|
||
|
||
const user = await DBModel.User.findByIdAndUpdate(userId, { $set: set }, { new: true });
|
||
if (!user) {
|
||
return ResponseUtil.notFound(ctx, "用户不存在");
|
||
}
|
||
|
||
return ResponseUtil.success(ctx, { user: await buildUserView(user) }, locked ? "账号已锁定" : "账号已解锁");
|
||
} catch (err) {
|
||
return ResponseUtil.internalError(ctx, err);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 更新当前用户在某应用内的个人配置
|
||
* body: { appId, config }
|
||
*/
|
||
async appConfig(ctx) {
|
||
const { error, value } = appConfigSchema.validate(ctx.request.body, { abortEarly: false });
|
||
if (error) {
|
||
return ResponseUtil.badRequest(ctx, error.details[0].message);
|
||
}
|
||
|
||
const user = ctx.state.user;
|
||
if (!user) {
|
||
return ResponseUtil.unauthorized(ctx, "用户未登录或 token 无效");
|
||
}
|
||
|
||
const { appId, config } = value;
|
||
|
||
if (!APP_REGISTRY[appId]) {
|
||
return ResponseUtil.badRequest(ctx, `未配置 appId: ${appId}`);
|
||
}
|
||
if (!hasConfigSchema(appId)) {
|
||
return ResponseUtil.badRequest(ctx, `该应用暂不支持配置: ${appId}`);
|
||
}
|
||
|
||
try {
|
||
const membership = await DBModel.UserApp.findOne({
|
||
userId: user._id,
|
||
appId,
|
||
status: "active",
|
||
});
|
||
if (!membership) {
|
||
return ResponseUtil.forbidden(ctx, "无权访问该应用");
|
||
}
|
||
|
||
let patch;
|
||
try {
|
||
patch = validateAppConfig(appId, config);
|
||
} catch (err) {
|
||
return ResponseUtil.badRequest(ctx, err.message);
|
||
}
|
||
|
||
// 只更新传入的叶子路径;未传的兄弟字段保持不变
|
||
const flat = flattenLeaves(patch);
|
||
if (Object.keys(flat).length === 0) {
|
||
return ResponseUtil.badRequest(ctx, "没有可更新的配置项");
|
||
}
|
||
|
||
const set = { configUpdatedAt: new Date() };
|
||
for (const [path, item] of Object.entries(flat)) {
|
||
set[`config.${path}`] = item;
|
||
}
|
||
|
||
await DBModel.UserApp.updateOne({ _id: membership._id }, { $set: set });
|
||
|
||
const updated = await DBModel.UserApp.findById(membership._id).lean();
|
||
return ResponseUtil.success(
|
||
ctx,
|
||
{ appId, config: resolveConfig(appId, updated?.config) },
|
||
"配置更新成功"
|
||
);
|
||
} catch (err) {
|
||
return ResponseUtil.internalError(ctx, err);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 授予 / 撤销应用角色
|
||
* body: { userId, appId, action: "grant" | "revoke", roles: ["admin"] }
|
||
*/
|
||
async grant(ctx) {
|
||
const { error, value } = grantSchema.validate(ctx.request.body, { abortEarly: false });
|
||
if (error) {
|
||
return ResponseUtil.badRequest(ctx, error.details[0].message);
|
||
}
|
||
|
||
const operator = ctx.state.user;
|
||
if (!operator) {
|
||
return ResponseUtil.unauthorized(ctx, "用户未登录或 token 无效");
|
||
}
|
||
|
||
const { userId, appId, action } = value;
|
||
const targetRoles = [...new Set(
|
||
(value.roles || ["admin"]).map((role) => String(role || "").trim()).filter(Boolean)
|
||
)];
|
||
|
||
if (!APP_REGISTRY[appId]) {
|
||
return ResponseUtil.badRequest(ctx, `未配置 appId: ${appId}`);
|
||
}
|
||
if (!targetRoles.length) {
|
||
return ResponseUtil.badRequest(ctx, "角色不能为空");
|
||
}
|
||
if (!targetRoles.every((role) => GRANTABLE_ROLES.includes(role))) {
|
||
return ResponseUtil.badRequest(ctx, "不支持的角色");
|
||
}
|
||
if (!mongoose.isValidObjectId(userId)) {
|
||
return ResponseUtil.badRequest(ctx, "用户ID不合法");
|
||
}
|
||
|
||
try {
|
||
// 操作者必须持有目标应用的 admin 角色才能授权/撤销(与方案文档 6.8 一致,
|
||
// 避免 Web 后台管理员改动小程序管理端的角色)
|
||
const operatorMembership = await DBModel.UserApp.findOne({
|
||
userId: operator._id,
|
||
appId,
|
||
status: "active",
|
||
roles: "admin",
|
||
}).select("_id");
|
||
if (!operatorMembership) {
|
||
return ResponseUtil.forbidden(ctx, "无权管理该应用的角色");
|
||
}
|
||
|
||
const targetUser = await DBModel.User.findById(userId).select("_id");
|
||
if (!targetUser) {
|
||
return ResponseUtil.notFound(ctx, "用户不存在");
|
||
}
|
||
|
||
if (action === "grant") {
|
||
const granted = await grantRoles({
|
||
userId,
|
||
appId,
|
||
roles: targetRoles,
|
||
grantedBy: operator._id,
|
||
});
|
||
return ResponseUtil.success(ctx, { userId, appId, roles: granted }, "授权成功");
|
||
}
|
||
|
||
// 撤销前确认目标用户确实持有要撤销的角色
|
||
const current = await DBModel.UserApp.findOne({ userId, appId }).lean();
|
||
if (!current) {
|
||
return ResponseUtil.notFound(ctx, "该用户在该应用没有成员关系");
|
||
}
|
||
const removable = targetRoles.filter(
|
||
(role) => Array.isArray(current.roles) && current.roles.includes(role)
|
||
);
|
||
if (!removable.length) {
|
||
return ResponseUtil.badRequest(ctx, "该用户不持有要撤销的角色");
|
||
}
|
||
|
||
const removesAdmin = removable.includes("admin");
|
||
|
||
if (removesAdmin) {
|
||
// 撤销前先友好拒绝最常见情况
|
||
const remainingBefore = await DBModel.UserApp.countDocuments({
|
||
appId,
|
||
status: "active",
|
||
roles: "admin",
|
||
userId: { $ne: userId },
|
||
});
|
||
if (remainingBefore === 0) {
|
||
return ResponseUtil.badRequest(ctx, "不能撤销最后一个管理员");
|
||
}
|
||
}
|
||
|
||
const revoked = await revokeRoles({
|
||
userId,
|
||
appId,
|
||
roles: removable,
|
||
grantedBy: operator._id,
|
||
});
|
||
|
||
if (removesAdmin) {
|
||
// 并发补偿:check-then-act 存在竞态(两个管理员同时互撤都可能通过预检),
|
||
// 撤销后复核,若已无启用管理员则立即回滚本次撤销,保证任何时刻至少一个管理员
|
||
const remainingAfter = await DBModel.UserApp.countDocuments({
|
||
appId,
|
||
status: "active",
|
||
roles: "admin",
|
||
});
|
||
if (remainingAfter === 0) {
|
||
await grantRoles({
|
||
userId,
|
||
appId,
|
||
roles: ["admin"],
|
||
grantedBy: operator._id,
|
||
});
|
||
return ResponseUtil.badRequest(ctx, "不能撤销最后一个管理员");
|
||
}
|
||
}
|
||
|
||
return ResponseUtil.success(ctx, { userId, appId, roles: revoked }, "撤销成功");
|
||
} catch (err) {
|
||
return ResponseUtil.internalError(ctx, err);
|
||
}
|
||
}
|
||
|
||
// 微信登录
|
||
async wxSignin(ctx) {
|
||
const { error, value } = wxSigninSchema.validate(ctx.request.body, { abortEarly: false });
|
||
if (error) {
|
||
return ResponseUtil.badRequest(ctx, error.details[0].message);
|
||
}
|
||
|
||
try {
|
||
const { code, phoneNumber, name, appId } = value;
|
||
|
||
const app = config.app[appId];
|
||
if (!app) {
|
||
return ResponseUtil.badRequest(ctx, `未配置 appId: ${appId}`);
|
||
}
|
||
const meta = APP_REGISTRY[appId];
|
||
if (!meta) {
|
||
return ResponseUtil.badRequest(ctx, `未登记 appId: ${appId}`);
|
||
}
|
||
|
||
// 手机号获取:
|
||
// 1) 优先用 phoneCode 由服务端向微信换取(可信,可绑定已有账号)
|
||
// 2) body 直传 phoneNumber 不可信,仅允许用于新建账号
|
||
let verifiedPhoneNumber = null;
|
||
if (value.phoneCode) {
|
||
try {
|
||
const accessToken = await getWxAccessToken(app);
|
||
const phoneUrl = `https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=${accessToken}`;
|
||
const phoneRes = await fetch(phoneUrl, {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ code: value.phoneCode }),
|
||
signal: AbortSignal.timeout(WX_REQUEST_TIMEOUT),
|
||
});
|
||
const phoneData = await phoneRes.json();
|
||
if (phoneData.errcode) {
|
||
return ResponseUtil.error(ctx, `获取手机号失败: ${phoneData.errmsg}`, null, 400);
|
||
}
|
||
verifiedPhoneNumber = phoneData.phone_info?.phoneNumber || null;
|
||
} catch (err) {
|
||
return ResponseUtil.internalError(ctx, err);
|
||
}
|
||
}
|
||
|
||
// 通过 code 换取 openid/session_key
|
||
const sessionUrl = `https://api.weixin.qq.com/sns/jscode2session?appid=${app.appid}&secret=${app.secret}&js_code=${code}&grant_type=authorization_code`;
|
||
const wxSessionRes = await fetch(sessionUrl, { signal: AbortSignal.timeout(WX_REQUEST_TIMEOUT) });
|
||
const sessionData = await wxSessionRes.json();
|
||
if (sessionData.errcode) {
|
||
return ResponseUtil.error(ctx, `微信接口错误: ${sessionData.errmsg}`, null, 400);
|
||
}
|
||
|
||
const openid = String(sessionData.openid || "").trim();
|
||
if (!openid) {
|
||
return ResponseUtil.error(ctx, "微信登录失败,未获取到 openid", null, 400);
|
||
}
|
||
const unionid = String(sessionData.unionid || "").trim() || undefined;
|
||
|
||
// 1. 先按本应用身份查
|
||
const identity = await DBModel.UserIdentity.findOne({
|
||
appId,
|
||
provider: meta.provider,
|
||
openid,
|
||
});
|
||
let user = identity ? await DBModel.User.findById(identity.userId) : null;
|
||
|
||
// 1.5 过渡期兜底:新表未命中时回查旧 app 字段,命中则补写新表。
|
||
// 回填有遗漏时不会把老用户当成新用户建重复账号。
|
||
if (!user) {
|
||
user = await DBModel.User.findOne({ [`app.${appId}.wxopenid`]: openid });
|
||
if (user) {
|
||
try {
|
||
await backfillOneFromLegacy(user, appId, openid, unionid);
|
||
} catch (err) {
|
||
console.warn(`[wxSignin] 旧数据补写失败 user=${user._id} app=${appId}:`, err.message);
|
||
}
|
||
}
|
||
}
|
||
|
||
// 2. 跨应用:unionid 优先(微信开放平台已绑定时才有值)
|
||
if (!user && unionid) {
|
||
const samePerson = await DBModel.UserIdentity.findOne({
|
||
provider: meta.provider,
|
||
unionid,
|
||
});
|
||
if (samePerson) user = await DBModel.User.findById(samePerson.userId);
|
||
}
|
||
|
||
// 3. 手机号兜底:只允许服务端验证过的手机号绑定已有账号
|
||
if (!user && verifiedPhoneNumber) {
|
||
user = await DBModel.User.findOne({ "profile.mobile": verifiedPhoneNumber });
|
||
}
|
||
|
||
// 4. 仍不存在则新建平台账号(成员关系在步骤 6 写入)
|
||
if (!user) {
|
||
const mobile = String(verifiedPhoneNumber || phoneNumber || "").trim();
|
||
if (!mobile) {
|
||
return ResponseUtil.badRequest(ctx, "缺少手机号");
|
||
}
|
||
|
||
// 未验证的手机号只允许用于新建账号,不能合并到已有账号
|
||
if (!verifiedPhoneNumber) {
|
||
const existing = await DBModel.User.findOne({ "profile.mobile": mobile });
|
||
if (existing) {
|
||
return ResponseUtil.error(ctx, "该手机号已注册,请先使用手机号登录后再绑定微信", null, 409);
|
||
}
|
||
}
|
||
|
||
try {
|
||
user = await DBModel.User.create({
|
||
profile: { name: name || mobile, mobile },
|
||
status: { account: "normal" },
|
||
social: { wechat: {} },
|
||
app: {},
|
||
});
|
||
} catch (err) {
|
||
if (err?.code === 11000) {
|
||
return ResponseUtil.error(ctx, "该手机号已注册,请先使用手机号登录后再绑定微信", null, 409);
|
||
}
|
||
throw err;
|
||
}
|
||
}
|
||
|
||
// 5. 绑定身份:唯一索引兜底。
|
||
// 11000 可能来自 unionid(该微信已绑定其他账号)或 openid(并发绑定),
|
||
// 必须按 keyPattern / message 区分,不能一律报同一种错误。
|
||
try {
|
||
await upsertIdentity({
|
||
userId: user._id,
|
||
appId,
|
||
platform: meta.platform,
|
||
provider: meta.provider,
|
||
openid,
|
||
unionid,
|
||
});
|
||
} catch (err) {
|
||
if (err?.code !== 11000) throw err;
|
||
|
||
const pattern = err.keyPattern || err.cause?.keyPattern || {};
|
||
const unionidConflict = unionid
|
||
&& ("unionid" in pattern || /unionid/i.test(err.message || ""));
|
||
|
||
if (unionidConflict) {
|
||
const owner = await DBModel.UserIdentity.findOne({
|
||
provider: meta.provider,
|
||
unionid,
|
||
});
|
||
if (!owner || String(owner.userId) !== String(user._id)) {
|
||
return ResponseUtil.error(ctx, "该微信已绑定其他账号", null, 409);
|
||
}
|
||
|
||
// 同一用户在其他应用已占用 unionid:本应用身份不写 unionid,重试一次
|
||
try {
|
||
await upsertIdentity({
|
||
userId: user._id,
|
||
appId,
|
||
platform: meta.platform,
|
||
provider: meta.provider,
|
||
openid,
|
||
});
|
||
} catch (retryErr) {
|
||
if (retryErr?.code === 11000) {
|
||
return ResponseUtil.error(ctx, "该微信身份已绑定其他账号", null, 409);
|
||
}
|
||
throw retryErr;
|
||
}
|
||
} else {
|
||
const bound = await DBModel.UserIdentity.findOne({
|
||
appId,
|
||
provider: meta.provider,
|
||
openid,
|
||
});
|
||
if (!bound || String(bound.userId) !== String(user._id)) {
|
||
return ResponseUtil.error(ctx, "该微信身份已绑定其他账号", null, 409);
|
||
}
|
||
}
|
||
}
|
||
|
||
// 6. 保证成员关系存在,并刷新最后登录时间(已有管理员角色不会被降级)
|
||
await upsertLoginMembership({ userId: user._id, appId });
|
||
|
||
// 7. 过渡期双写旧 app 字段,供 api/health 等未迁移的下游继续读取。
|
||
// 下个版本下游改读 user_app 后再删除。
|
||
await DBModel.User.updateOne(
|
||
{ _id: user._id, [`app.${appId}.role`]: { $exists: false } },
|
||
{ $set: { [`app.${appId}.role`]: ["user"] } }
|
||
);
|
||
await DBModel.User.updateOne(
|
||
{ _id: user._id },
|
||
{ $set: { [`app.${appId}.wxopenid`]: openid } }
|
||
);
|
||
|
||
// 8. 更新Token(哈希入库)
|
||
user.security.lastLoginIp = ctx.ip || ctx.request.ip;
|
||
const { raw } = await this.issueToken(user);
|
||
|
||
return ResponseUtil.success(ctx, { user: await this.buildLoginResponse(user, raw) }, "登录成功");
|
||
} catch (err) {
|
||
return ResponseUtil.internalError(ctx, err);
|
||
}
|
||
}
|
||
|
||
// 获取微信的手机号码
|
||
async wxGetPhoneNumber(ctx) {
|
||
const { error, value } = wxGetPhoneSchema.validate(ctx.request.body, { abortEarly: false });
|
||
if (error) {
|
||
return ResponseUtil.badRequest(ctx, error.details[0].message);
|
||
}
|
||
|
||
try {
|
||
const { code, appId } = value;
|
||
|
||
let app = config.app[appId];
|
||
if (!app) {
|
||
return ResponseUtil.badRequest(ctx, `未配置 appId: ${appId}`);
|
||
}
|
||
|
||
// 获取access_token(带缓存的封装,避免耗尽微信每日配额)
|
||
const accessToken = await getWxAccessToken(app);
|
||
|
||
// 获取phoneNumber
|
||
const phoneUrl = `https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=${accessToken}`;
|
||
const phoneRes = await fetch(phoneUrl, {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ code: code }),
|
||
signal: AbortSignal.timeout(WX_REQUEST_TIMEOUT),
|
||
});
|
||
const phoneData = await phoneRes.json();
|
||
if (phoneData.errcode) {
|
||
return ResponseUtil.error(ctx, `获取手机号失败: ${phoneData.errmsg}`, null, 400);
|
||
}
|
||
|
||
const phoneNumber = phoneData.phone_info?.phoneNumber;
|
||
return ResponseUtil.success(ctx, { phoneNumber }, "获取手机号成功");
|
||
} catch (err) {
|
||
return ResponseUtil.internalError(ctx, err);
|
||
}
|
||
}
|
||
}
|
||
|
||
export { HandlerUser };
|