Files
ws_health/doc/user-multi-app-plan.md
T
lik 762bd0e7da chore: 注册陪诊 Web 后台子模块并补充管理端方案文档
新增 ui/web_escort_admin 子模块;补充陪诊后台实施方案与陪诊师端同步改造清单;用户多应用方案登记 web-escort-admin 应用。
2026-11-06 19:54:17 +08:00

46 KiB
Raw Blame History

用户多应用模型改造方案

项 内容
状态 已实施(P1-P3 完成;P4 未做、P5 部分完成),2026-11-06 按代码回填
日期 2026-11-05
范围 api/user 的用户模型、微信登录、鉴权、用户列表;MongoDB 库 eiot_user
目标 一个平台账号可在多个 app / 网站 / 小程序中拥有独立的身份、角色和授权状态

1. 结论

当前 user.app 是一个 Mixed 字段,一个对象同时承载三件事:

  1. 登录身份:app.{appId}.wxopenid
  2. 授权角色:app.{appId}.role
  3. 应用清单:app 中存在某个 key

这三类数据的生命周期不同,混在一个无 schema 的对象里,导致唯一约束、索引、权限作用域都无法表达。

建议:

  • 数据库层:拆成 user(平台账号)、user_app(应用成员与授权)、user_identity(外部登录身份)三张表;user 不再保存 app。
  • 接口层:不新增 v2 接口。/user/userInfo、登录响应继续返回只读兼容视图 app,并新增只读数组 apps;两者都由新表组装,保证老 app 与 api/health 不改也能工作。app 在所有客户端改读 apps 后的下个发布周期移除。
  • 权限判定:必须带 appId,只认该应用内的 roles,不再遍历所有应用。
  • 授权入口:登录只授予 user;管理员通过 POST /user/grant 或运维脚本授予,登录接口不产生管理员。
  • 实施窗口:现网只有 36 条用户,且 app 数据结构单一,是切换成本最低的时候。

如果明确只维护当前两个微信小程序、且不做应用权限管理,可退而求其次采用第 5.1 节的方案 A(单文档内类型化 Map),但仍然解决不了“登录过不等于已授权”和跨应用身份合并。

2. 现状

2.1 数据结构

api/user/models/schema/user.js:74-77:

// 带wxopenid
app: {
  type: mongoose.Schema.Types.Mixed,
  default: {}
},

整个 Schema 还开启了 strict: false(api/user/models/schema/user.js:86-89),因此 app 完全不受 schema 约束。

现网 36 条数据的实际结构只有:

"app": {
  "wxapp-escort": {
    "role": ["user"],
    "wxopenid": "ocHVo1..."
  },
  "wxapp-escort-admin": {
    "role": ["admin"],
    "wxopenid": "oLvx23..."
  }
}

social.wechat.unionid 虽有唯一稀疏索引(api/user/models/schema/user.js:64),但没有任何非空数据。

2.2 现网数据快照(2026-11-05)

项 实际值
user 文档总数 36
有 app 字段 36(全部非空)
app.wxapp-escort 36
app.wxapp-escort-admin 1
role = ["user"] 36(wxapp-escort)
role = ["admin"] 1(wxapp-escort-admin)
app 条目字段 只有 role、wxopenid
重复 openid 0
role / wxopenid 缺失 0
非空 social.wechat.unionid 0

结论:数据本身干净,但 36/36 用户都有 wxapp-escort,说明 “app 里存在 key” 只能表示“登录过”,不能表示“已授权”。

2.3 代码读写点

行为 位置
定义 app 字段 api/user/models/schema/user.js:74-77
注册时写空 app api/user/handler/users.js:152-153
微信登录按 app.{appId}.wxopenid 查用户 api/user/handler/users.js:366-367
微信登录写入 role / wxopenid api/user/handler/users.js:384-399
鉴权遍历所有 app 的 role api/user/middleware/auth.js:73-79
管理员判定固定读 wxapp-escort-admin api/user/middleware/auth.js:101-115
用户列表按 app.wxapp-escort 存在性过滤 api/user/handler/users.js:300
用户列表角色校验写在 handler 内(isAdmin),路由层无声明 api/user/handler/users.js:293-295
唯一 token 的签发与覆盖 api/user/handler/users.js:96-103
删除用户时按 social.wechat.unionid api/user/models/schema/user.js:195-215
通用更新不允许写 app api/user/models/schema/user.js:141-183

下游读取(过渡期需要兼容):

  • api/health/utils/permissions.js 直接读 user.app["wxapp-escort-admin"].role。
  • ui/web_tcm/src/stores/tcm_organization.js 读 user.app?.tcm?.organization?.id。

3. 问题清单

级别 问题 后果
P0 wxopenid 无唯一索引、无普通索引 登录查询全表扫;并发首次登录或手工改库可产生同 openid 多用户,findOne 命中不确定,可能登录到他人账号
P1 角色校验跨应用 auth({ roles }) 遍历所有 app,A 应用的 admin 能通过 B 应用的校验
P1 “登录过”与“有权限”混淆 无法停用某应用的权限,无法审计授权来源;用户列表口径错误
P2 身份、授权、应用参数混层 openid、role、未来的昵称/机构号放在同一对象,任何代码都可能顺手改到权限
P2 缺平台/登录方式维度 只有 appId;同一应用多端、多 appid、抖音端无法区分身份
P2 unionid 未落地 跨应用“同一个人”只能靠手机号;接第二个小程序或抖音后账号会分叉
P2 单 token 管理端登录会把 C 端踢下线
P2 权限校验写在 handler 内 路由层看不出接口所需角色,新增接口容易漏写校验
P3 strict: false + 对象 key 直接用 appId 脏数据无法约束;appId 含 . 或 $ 会写坏文档

4. 设计原则

  1. 账号、身份、授权分离:user 是平台账号;user_identity 是“用什么登录”;user_app 是“能访问哪个应用、是什么角色”。
  2. 唯一性由数据库保证:openid 唯一、userId + appId 唯一,不依赖应用层“先查后插”。
  3. 权限必须带应用维度:角色校验接口必须显式传 appId。
  4. 应用参数与权限分离:应用内个人配置放 user_app.config,只允许非权限、非数据范围数据;需要查询/鉴权的字段必须提升为 user_app 顶层字段。
  5. 接口兼容优先:数据库先改,响应形状后改;下游服务可以按自己的节奏迁移。

5. 方案对比

5.1 方案 A:单文档内类型化 Map(最小改动)

保留在 user 文档内,把 Mixed 换成以 appId 为 key 的类型化 Map(字段建议改名 apps,避免和 Koa 的 app 混淆):

const AppMembershipSchema = new mongoose.Schema({
  platform: { type: String, enum: ["weixin", "douyin", "alipay", "web"], required: true },
  provider: { type: String, enum: ["weixin-mini", "douyin-mini", "password"], required: true },
  roles:    { type: [String], default: ["user"] },
  status:   { type: String, enum: ["active", "disabled"], default: "active" },
  identities: {
    openid:  { type: String },
    unionid: { type: String },
  },
  grant: {
    by: { type: mongoose.Schema.Types.ObjectId },
    at: Date,
  },
  lastLoginAt: { type: Date },
}, { _id: false });

// user.js
apps: {
  type: Map,
  of: AppMembershipSchema,
  default: () => new Map(),
},

每个应用单独建 openid 稀疏唯一索引:

for (const appId of Object.keys(config.app)) {
  UserSchema.index(
    { [`apps.${appId}.identities.openid`]: 1 },
    { unique: true, sparse: true, name: `uniq_${appId}_openid` }
  );
}

优点:改动小,只动 schema + 登录/鉴权读法。 缺点:应用数增长要不断增加索引;“已授权/已停用”仍和登录记录混在一个文档;按应用查成员/管理员只能扫文档;Map 仍不是授权管理的理想结构。

5.2 方案 B:成员表 + 身份表(推荐)

user (平台账号)
  │ 1
  ├── N  user_app       (userId + appId 唯一;roles / status / 授权来源)
  └── N  user_identity  (appId + provider + openid 唯一;unionid / platform)

优点:

  • openid 唯一性、userId + appId 唯一性都能直接建索引。
  • 角色查询按应用走索引;可停用、可审计、可按应用列出成员和管理员。
  • 身份与授权解耦;接抖音、Web、支付宝只是新增 identity 行,不改 user 表。
  • 支持 unionid 跨应用合并同一人。

缺点:登录和 userInfo 多 1-2 次查询;需要一次数据回填;响应需要组装。

5.3 选型

维度 方案 A 方案 B
改动量 小 中
openid 唯一 可以(每应用一个索引) 可以
角色按应用隔离 可以 可以
授权吊销 / 审计 需挤进同一文档 原生支持
按应用查成员 需扫描 索引查询
接抖音 / Web / 多端 继续加 key 和索引 新增 identity 行
迁移成本 低 一次性回填 36 条
长期返工 高 低

按“平台级多应用权限”的目标,推荐方案 B。现网数据量只有 36 条,现在切换成本最低。

6. 推荐方案详设

6.1 应用注册表

新增 api/user/models/app_registry.js,集中维护 appId → 平台/登录方式,避免散落在登录代码里:

import config from "../conf.json" with { type: "json" };

export const APP_REGISTRY = {
  "wxapp-escort":       { platform: "weixin", provider: "weixin-mini" },
  "wxapp-escort-admin": { platform: "weixin", provider: "weixin-mini" },
  "web-escort-admin":   { platform: "web",    provider: "password" },
  "ttapp-escort":       { platform: "douyin", provider: "douyin-mini" },
  "tcm":                { platform: "web",    provider: "password" },
};

// conf.json 配置了但注册表没登记 → 启动失败;注册表有但未配置 → 只告警
export function assertRegistryCoverage() {
  const configured = Object.keys(config.app || {});
  const missing = configured.filter((id) => !APP_REGISTRY[id]);
  if (missing.length) {
    throw new Error(`APP_REGISTRY 缺少 appId 元数据: ${missing.join(", ")}`);
  }
  const orphan = Object.keys(APP_REGISTRY).filter((id) => !configured.includes(id));
  if (orphan.length) {
    console.warn(`[user] APP_REGISTRY 中未在 conf.json 配置的 appId: ${orphan.join(", ")}`);
  }
  return configured;
}

export const APP_IDS = Object.keys(config.app || {});

api/user/app.js 启动阶段调用一次 assertRegistryCoverage(),让配置缺失在部署时暴露,而不是等到有人登录该应用才报错。

conf.json 继续只放 appid / secret;app 元数据放代码里,便于评审和测试。

6.2 集合与索引

user(保持平台账号职责)

保留现有 profile / security / location / addresses / social / status / meta,删除 app。

user_app

// api/user/models/schema/user_app.js
const UserAppSchema = new mongoose.Schema({
  userId: { type: mongoose.Schema.Types.ObjectId, required: true },
  appId:  { type: String, required: true },
  roles:  { type: [String], default: ["user"] },
  status: { type: String, enum: ["active", "disabled"], default: "active" },
  source: { type: String, enum: ["weixin-login", "manual", "migrated"], default: "manual" },
  // 应用内个人配置:仅存偏好/展示参数,禁止放 roles/status/orgId 等权限或数据范围字段
  // 用 Map 而不是 Mixed 对象:键级 set 会被 Mongoose 跟踪,也便于按 key / 叶子路径原子更新
  config: {
    type: Map,
    of: mongoose.Schema.Types.Mixed,
    default: () => new Map(),
  },
  configUpdatedAt: { type: Date, default: null },
  grantedBy: { type: mongoose.Schema.Types.ObjectId, default: null },
  grantedAt: { type: Date, default: null },
  lastLoginAt: { type: Date, default: null },
}, { collection: "user_app", minimize: false });

UserAppSchema.index({ userId: 1, appId: 1 }, { unique: true });
UserAppSchema.index({ appId: 1, status: 1 });
UserAppSchema.index({ appId: 1, roles: 1 });

user_identity

// api/user/models/schema/user_identity.js
const UserIdentitySchema = new mongoose.Schema({
  userId:   { type: mongoose.Schema.Types.ObjectId, required: true },
  appId:    { type: String, required: true },
  platform: { type: String, enum: ["weixin", "douyin", "alipay", "web"], required: true },
  provider: { type: String, enum: ["weixin-mini", "douyin-mini", "password"], required: true },
  openid:   { type: String },
  unionid:  { type: String },
}, { collection: "user_identity", timestamps: true });

// 注意:这里不能用 sparse。appId/provider 恒存在,
// sparse 复合索引仍会把缺 openid 的文档索引成 null,导致 password 身份互相冲突。
UserIdentitySchema.index(
  { appId: 1, provider: 1, openid: 1 },
  { unique: true, partialFilterExpression: { openid: { $type: "string" } } }
);

UserIdentitySchema.index(
  { provider: 1, unionid: 1 },
  { unique: true, partialFilterExpression: { unionid: { $type: "string" } } }
);

UserIdentitySchema.index({ userId: 1 });

写入前必须把空字符串规范化为 undefined(例如 openid || undefined、unionid || undefined)。partialFilterExpression 只按类型过滤,空字符串仍会被索引,多个 openid: "" 依然会触发唯一冲突。

删除用户时,delUser 需要同时清理该用户的 user_app 与 user_identity,避免残留成员关系被新账号复用。

user_session(可选,第二阶段)

不在本次改造必做范围。它解决“多应用/多端登录互踢”:

{
  userId, appId, tokenHash,
  expiresAt, ip, device
}
// { tokenHash: 1 } unique
// { expiresAt: 1 } expireAfterSeconds: 0

本次先保留 security.token,避免扩大改动面。

6.3 微信登录流程

替换 api/user/handler/users.js 的 wxSignin 核心逻辑(以下为伪代码,错误响应沿用现有 ResponseUtil):

const meta = APP_REGISTRY[appId];
if (!meta) return badRequest(`未配置 appId: ${appId}`);

const { openid, unionid } = sessionData;

// 1. 先按本应用身份查
let identity = await DBModel.UserIdentity.findOne({ appId, provider: meta.provider, openid });
let user = identity ? await DBModel.User.findById(identity.userId) : null;

// 1.5 过渡期兜底:新表未命中时回查旧 app 字段(P4 前旧字段仍在)
//     命中说明回填有遗漏,补写新表,避免把老用户当成新用户建重复账号
if (!user) {
  user = await DBModel.User.findOne({ [`app.${appId}.wxopenid`]: openid });
  if (user) await backfillOneFromLegacy(user, appId, openid, unionid);
}

// 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. 仍不存在则新建平台账号(不写 app)
if (!user) {
  if (!verifiedPhoneNumber && !phoneNumber) return badRequest("缺少手机号");
  // 未验证的 phoneNumber 只允许用于新建账号,不能用于合并到已有账号(见步骤 3)
  user = await DBModel.User.create({
    profile: { name: name || verifiedPhoneNumber || phoneNumber, mobile: verifiedPhoneNumber || phoneNumber },
    status: { account: "normal" },
    social: { wechat: {} },
  });
}

// 5. 绑定身份:唯一索引兜底。user_identity 上有两个唯一索引,
//    11000 可能来自 openid,也可能来自 unionid,必须按 keyPattern 区分
try {
  await DBModel.UserIdentity.updateOne(
    { appId, provider: meta.provider, openid },
    {
      $setOnInsert: { userId: user._id, platform: meta.platform, provider: meta.provider },
      ...(unionid ? { $set: { unionid } } : {}),
    },
    { upsert: true }
  );
} catch (err) {
  if (err.code !== 11000) throw err;

  const pattern = err.keyPattern || {};

  // unionid 冲突:该微信号已属于其他账号
  if ("unionid" in pattern && unionid) {
    const owner = await DBModel.UserIdentity.findOne({ provider: meta.provider, unionid });
    if (!owner || String(owner.userId) !== String(user._id)) {
      return error(ctx, "该微信已绑定其他账号", null, 409);
    }
    // 同一用户的并发绑定:重试一次 upsert,补齐当前 openid 记录
    await DBModel.UserIdentity.updateOne(
      { appId, provider: meta.provider, openid },
      { $setOnInsert: { userId: user._id, platform: meta.platform, provider: meta.provider } },
      { upsert: true }
    );
  } else {
    // openid 冲突:确认是否已绑到当前用户
    const bound = await DBModel.UserIdentity.findOne({ appId, provider: meta.provider, openid });
    if (!bound || String(bound.userId) !== String(user._id)) {
      return error(ctx, "该微信身份已绑定其他账号", null, 409);
    }
  }
}

// 6. 保证成员关系存在,并刷新最后登录时间
await DBModel.UserApp.updateOne(
  { userId: user._id, appId },
  {
    $setOnInsert: { roles: ["user"], status: "active", source: "weixin-login", grantedAt: new Date() },
    $set: { lastLoginAt: new Date() },
  },
  { upsert: true }
);

// 7. 签发 token(保持现有单 token 逻辑)
const { raw } = await this.issueToken(user);

关键规则:

  • unionid 有值时才参与跨应用合并;没有时退化为手机号。
  • openid 已绑定其他用户时拒绝,不做静默改绑。
  • roles 首次写入固定为 ["user"];管理员角色只能由内部授权写(见 6.8)。
  • 所有写入都是 upsert + 唯一索引,不依赖“先查后插”,因此不要求 MongoDB 事务。
  • profile.mobile 已有单字段 unique + sparse 索引(api/user/models/schema/user.js:20),本次不需要重复建设。但 sparse 不排除空字符串,mobile: "" 仍会占用唯一键,写入前必须保证非空。
  • 未验证的 phoneNumber 只用于新建账号,不得用于合并到已有账号;合并只认 verifiedPhoneNumber。
  • 步骤 1.5 的 backfillOneFromLegacy 与 7.2 的回填脚本共用同一段 upsert 逻辑,不能各写一份;兜底命中时必须补写新表,否则每次登录都会回退到全表查旧字段。

6.4 鉴权

auth() 增加 appId 参数,角色只在该应用内判定:

function auth({ required = true, appId, roles } = {}) {
  return async (ctx, next) => {
    // ... token -> user、锁定、过期校验保持不变

    // 只要声明了 appId,就必须存在有效成员关系:停用 / 未授权统一 403
    if (appId) {
      const membership = await DBModel.UserApp.findOne({
        userId: user._id,
        appId,
        status: "active",
      });
      if (!membership) return ResponseUtil.forbidden(ctx, "无权访问该应用");
      if (roles && roles.length > 0 && !roles.some((r) => membership.roles.includes(r))) {
        return ResponseUtil.forbidden(ctx, "权限不足");
      }
      ctx.state.membership = membership;
    } else if (roles && roles.length > 0) {
      // 角色校验必须带应用维度,缺 appId 视为路由配置错误
      return ResponseUtil.internalError(ctx, "角色校验缺少 appId");
    }

    ctx.state.user = user;
    await next();
  };
}

路由按应用绑定,不再靠“app 里有没有 key”猜:

// api/user/routes/index.js
const ADMIN_APP = "wxapp-escort-admin";

userRouter.post(
  "/list",
  auth({ appId: ADMIN_APP, roles: ["admin"] }),
  this.handler.userList.bind(this.handler)
);

停用语义:status: "disabled" 只会在挂了 appId 的接口生效。凡是依赖“某应用可用”的接口(/user/update、/user/app-config、后续 C 端业务接口)都必须显式传 appId;未传 appId 的接口只校验平台级登录态,无法表达应用级停用。这一点必须在路由评审时逐条确认。

isAdmin() 改为只认应用内成员关系,不再提供“缺 role 即管理员”的历史兼容分支:

function isAdmin(membership) {
  return !!membership
    && membership.status === "active"
    && membership.roles.includes("admin");
}

userList 的鉴权已由路由完成,handler 内不再单独调用 isAdmin。

如果后续出现非管理端应用也要校验角色的接口,appId 从请求头 X-App-Id 取,并先用 APP_REGISTRY 校验,不能直接信任 body。

6.5 接口响应

保留 user 主体结构,新增 apps,同时输出过渡期兼容视图 app:

{
  "user": {
    "profile": { "name": "...", "mobile": "..." },
    "apps": [
      {
        "appId": "wxapp-escort",
        "roles": ["user"],
        "status": "active",
        "config": { "theme": "dark", "notifications": { "orderStatus": true, "marketing": false } }
      },
      { "appId": "wxapp-escort-admin", "roles": ["admin"], "status": "active", "config": {} }
    ],
    "app": {
      "wxapp-escort": { "role": ["user"], "wxopenid": "ocHVo1..." },
      "wxapp-escort-admin": { "role": ["admin"], "wxopenid": "oLvx23..." }
    }
  }
}
  • app 标记为 deprecated,仅由 user_app + user_identity 组装,不再从数据库读取。
  • safe.security 仍在 buildLoginResponse 中单独附原始 token。
  • wxopenid 在兼容视图中保留,待 api/health 和前端确认不再使用后移除。

组装逻辑放在 sanitizeUser 之外,避免脱敏函数依赖数据库:

// Mongoose Map 与 lean 返回的普通对象都要兼容
function plainConfig(value) {
  if (!value) return {};
  return value instanceof Map ? Object.fromEntries(value) : value;
}

async function buildUserView(user) {
  const [memberships, identities] = await Promise.all([
    DBModel.UserApp.find({ userId: user._id }).lean(),
    DBModel.UserIdentity.find({ userId: user._id, openid: { $exists: true } }).lean(),
  ]);

  const apps = memberships.map((m) => ({
    appId: m.appId,
    roles: m.roles,
    status: m.status,
    config: resolveConfig(m.appId, m.config), // 合并默认值后再返回
  }));

  const legacyApp = {};
  for (const m of memberships) {
    const identity = identities.find((i) => i.appId === m.appId);
    legacyApp[m.appId] = {
      role: m.roles,
      ...(identity?.openid ? { wxopenid: identity.openid } : {}),
    };
  }

  return { ...sanitizeUser(user), apps, app: legacyApp };
}

6.6 用户列表

不再用 {"app.wxapp-escort": {$exists: true}}:

const filter = { appId: "wxapp-escort", status: "active" };
const [memberships, total] = await Promise.all([
  DBModel.UserApp.find(filter).sort({ _id: 1 }).skip((page - 1) * pageSize).limit(pageSize).lean(),
  DBModel.UserApp.countDocuments(filter),
]);

const userIds = memberships.map((m) => m.userId);
const users = await DBModel.User.find({ _id: { $in: userIds } });

total 现在是“该应用的有效成员数”,不再是“登录过该小程序的人数”。

这是本次唯一主动接受的 v1 语义变更:现网 36 人全部回填为 active,上线当天列表结果与现在完全一致;差异只会在引入停用之后出现。

6.7 应用内配置参数

user_app.config 保存“这个用户在这个应用里的个人配置/偏好”,例如:

应用 可能的配置
C 端小程序 theme、language、订单通知开关、列表默认筛选
管理端小程序 每页条数、默认筛选、提示音开关
tcm Web theme、language、默认机构(仅展示用途时)

明确不放进 config 的内容:

  • roles / status / 授权来源:属于权限,已有独立字段。
  • orgId、tenantId 等数据范围字段:如果参与查询或越权判断,必须是 user_app 顶层字段并建索引,不能埋在 config 里。
  • openid / unionid / 密码:属于 user_identity。
  • 图片、附件:只存 URL,不存二进制。

存储结构

config: {
  type: Map,
  of: mongoose.Schema.Types.Mixed,
  default: () => new Map(),
},
configUpdatedAt: { type: Date, default: null },

选择 Map<String, Mixed> 的原因:

  • 每个应用的配置项不同,用统一子 schema 会把所有应用的字段堆在一起。
  • Map 能跟踪 key 级 set/delete;换成普通 Mixed 对象后,嵌套属性修改不会被 Mongoose 自动保存。
  • 值允许嵌套对象(如 notifications),同时 key 由白名单约束,不接受客户端任意新增。

每个应用声明自己的白名单

新增 api/user/models/app_config.js:

import Joi from "joi";

// 键默认可选,因此同一份 schema 既能校验全量,也能校验部分更新
export const APP_CONFIG_SCHEMAS = {
  "wxapp-escort": Joi.object({
    theme: Joi.string().valid("light", "dark", "system"),
    language: Joi.string().valid("zh-CN", "en-US"),
    notifications: Joi.object({
      orderStatus: Joi.boolean(),
      marketing: Joi.boolean(),
    }),
  }),

  "wxapp-escort-admin": Joi.object({
    pageSize: Joi.number().integer().min(10).max(200),
    defaultFilter: Joi.string().valid("all", "pending", "done"),
    soundAlert: Joi.boolean(),
  }),

  tcm: Joi.object({
    theme: Joi.string().valid("light", "dark", "system"),
    language: Joi.string().valid("zh-CN", "en-US"),
  }),
};

export function hasConfigSchema(appId) {
  return !!APP_CONFIG_SCHEMAS[appId];
}

export function validateAppConfig(appId, input) {
  const schema = APP_CONFIG_SCHEMAS[appId];
  if (!schema) throw new Error(`未配置 ${appId} 的 config schema`);

  const { error, value } = schema.validate(input, { abortEarly: false });
  if (error) throw new Error(error.details[0].message);

  // 单个用户的单应用配置限制 8KB,防止被当成任意存储
  if (Buffer.byteLength(JSON.stringify(value)) > 8192) {
    throw new Error("应用配置过大");
  }
  return value;
}

Joi 对象默认拒绝未声明 key,客户端传 { role: ["admin"] } 会直接 400,无法借此改权限。

写入接口

新增 POST /user/app-config,挂 auth(),只允许登录用户修改自己的配置:

// body: { appId, config: { theme: "dark", notifications: { marketing: false } } }
const { appId, config } = ctx.request.body;
if (!APP_REGISTRY[appId]) return ResponseUtil.badRequest(ctx, `未配置 appId: ${appId}`);
if (!hasConfigSchema(appId)) return ResponseUtil.badRequest(ctx, `该应用暂不支持配置: ${appId}`);

const membership = await DBModel.UserApp.findOne({
  userId: user._id,
  appId,
  status: "active",
});
if (!membership) return ResponseUtil.forbidden(ctx, "无权访问该应用");

const patch = validateAppConfig(appId, config);

function isPlainObject(v) {
  return !!v && typeof v === "object" && !Array.isArray(v) && !(v instanceof Date);
}

// 展开为叶子路径:{ notifications: { marketing: false } } → { "notifications.marketing": false }
// 数组和标量整体替换,不做逐项合并
function flattenLeaves(input, base = "") {
  const out = {};
  for (const [k, v] of Object.entries(input)) {
    const path = base ? `${base}.${k}` : k;
    if (isPlainObject(v)) {
      Object.assign(out, flattenLeaves(v, path));
    } else {
      out[path] = v;
    }
  }
  return out;
}

const flat = flattenLeaves(patch);
if (Object.keys(flat).length === 0) {
  return ResponseUtil.badRequest(ctx, "没有可更新的配置项");
}

const set = { configUpdatedAt: new Date() };
for (const [path, value] of Object.entries(flat)) {
  set[`config.${path}`] = value; // 叶子级 $set:同一对象下未传的兄弟字段保持不变
}
await DBModel.UserApp.updateOne({ _id: membership._id }, { $set: set });

规则:

  • 一次请求只更新传入的叶子路径,未传的叶子字段保持不变。
  • 嵌套对象按叶子级合并(config.notifications.marketing 单独写入),不做整对象替换——否则只改一个开关会把同对象下其他字段清掉。
  • 数组和标量整体替换。
  • 传空对象 {} 视为无操作,直接 400,避免写入无意义的 configUpdatedAt。
  • 管理员/服务端才能改的配置项不放进这个接口的 schema,另走内部授权接口。
  • 配置 key 由 Joi 白名单固定,不含 . 或 $,不会写坏文档路径。

读取与默认值

默认值放代码里,数据库只保存用户改过的项:

const APP_CONFIG_DEFAULTS = {
  "wxapp-escort": { theme: "system", language: "zh-CN", notifications: { orderStatus: true, marketing: false } },
  "wxapp-escort-admin": { pageSize: 100, defaultFilter: "all", soundAlert: true },
  tcm: { theme: "system", language: "zh-CN" },
};

function resolveConfig(appId, stored) {
  const defaults = APP_CONFIG_DEFAULTS[appId] || {};
  const current = plainConfig(stored);
  const out = { ...defaults };
  for (const [key, value] of Object.entries(current)) {
    // 已知嵌套对象做一层深合并:库里只存了部分字段时,默认值仍能补齐
    out[key] = isPlainObject(defaults[key]) && isPlainObject(value)
      ? { ...defaults[key], ...value }
      : value;
  }
  return out;
}

plainConfig、isPlainObject 放在 api/user/models/app_config.js,由写入 handler 和 buildUserView 共用,避免两处各写一份导致行为分叉。

apps[].config 返回合并后的结果。默认值调整后对未覆盖该 key 的用户立即生效,不用批量回填。

写入注意事项

// 正确:整值替换,Map 会标记修改
membership.config.set("notifications", { orderStatus: true, marketing: false });
await membership.save();

// 错误:Map 内 Mixed 值的嵌套属性修改不会被自动保存
membership.config.get("notifications").marketing = true;

如果使用 updateOne,按 6.7 的叶子路径写法($set: { "config.notifications.marketing": false }),既绕开 Map 的变更跟踪,也不会覆盖同一对象下的兄弟字段。不要用 $set: { "config.notifications": {...} } 整对象写入,除非确实要重置该对象。

与 orgId 的边界

web_tcm 现在读 user.app?.tcm?.organization?.id:

  • 如果机构号只用于展示默认机构,放 config.defaultOrgId。
  • 如果机构号参与数据过滤/权限判断,新增 user_app.orgId 顶层字段,并建索引 { appId: 1, orgId: 1 },不要放 config。

过渡期兼容视图可以把 config.defaultOrgId 或顶层 orgId 映射回 app.tcm.organization.id;长期让前端改读 apps[].config / apps[].orgId。

6.8 授权入口

登录只会写入 roles: ["user"],管理员角色必须有服务端授权入口,否则“下一个管理员”无法产生。最小实现是一个内部接口 + 一个运维脚本,不建管理后台。

POST /user/grant,挂 auth({ appId: "wxapp-escort-admin", roles: ["admin"] }):

// body: { userId, appId, action: "grant" | "revoke", roles: ["admin"] }
const { userId, appId, action } = ctx.request.body;
const targetRoles = ctx.request.body.roles || ["admin"];

if (!APP_REGISTRY[appId]) return ResponseUtil.badRequest(ctx, `未配置 appId: ${appId}`);
if (!targetRoles.every((r) => GRANTABLE_ROLES.includes(r))) {
  return ResponseUtil.badRequest(ctx, "不支持的角色");
}

const operator = ctx.state.user;

if (action === "grant") {
  await DBModel.UserApp.updateOne(
    { userId, appId },
    {
      $addToSet: { roles: { $each: targetRoles } },
      $set: { status: "active", grantedBy: operator._id, grantedAt: new Date() },
      $setOnInsert: { source: "manual", config: {} },
    },
    { upsert: true }
  );
} else if (action === "revoke") {
  // 先确认撤销后该应用仍有启用的管理员
  const remaining = await DBModel.UserApp.countDocuments({
    appId,
    status: "active",
    roles: "admin",
    userId: { $ne: userId },
  });
  if (remaining === 0) return ResponseUtil.badRequest(ctx, "不能撤销最后一个管理员");

  await DBModel.UserApp.updateOne(
    { userId, appId },
    {
      $pull: { roles: { $in: targetRoles } },
      $set: { grantedBy: operator._id, grantedAt: new Date() },
    }
  );
} else {
  return ResponseUtil.badRequest(ctx, "action 只能是 grant 或 revoke");
}

约定:

  • GRANTABLE_ROLES = ["user", "admin"],白名单固定;本阶段不做自定义角色/RBAC。
  • 撤销的是角色,不删除成员记录;status 保持原值,便于审计。要彻底停用该应用,另走 status: "disabled"。
  • 撤销前校验“至少保留一个启用管理员”,避免把管理端锁死。
  • 首个管理员和紧急恢复用 scripts/grant_admin.js(直接写库,参数为 userId + appId),不走 HTTP。

7. 实施步骤

7.1 阶段划分

阶段 内容 可回滚
P0 备份 user 集合;确认无重复 openid;把 userList 的 isAdmin 校验从 handler 上移到路由层(行为等价,便于后续换成 membership 判定) 不需要
P1 新增两张表的 schema、模型注册、索引;不改变任何行为 删除集合即可
P2 wxSignin 双写:新表 + 旧 app 字段;跑历史回填 旧代码仍可读旧字段
P3 读路径切到新表:auth、userList、userInfo 响应;兼容 app 视图。无开关,直接切;发布前必须完成第 12 节 R3 的全量 diff 重新部署旧代码
P4 停止写旧 app;数据库删除 app 字段;strict: true 需要备份恢复
P5 下游(api/health、web_tcm)改用 apps;移除兼容 app 可回退响应字段

P1-P3 期间旧 app 字段保持可读,是回滚窗口。

7.2 回填脚本

一次性脚本,按 _id 分批(cursor.batchSize(100)),幂等:

// scripts/migrate_user_app.js
for (const user of cursor) {
  for (const [appId, entry] of Object.entries(user.app || {})) {
    const roles = Array.isArray(entry.role)
      ? entry.role
      : entry.role
        ? [entry.role]
        : ["user"];

    // 未登记的 appId 不能丢弃:成员关系照常写入;
    // 有 openid 时按微信小程序兜底,并告警要求补登 APP_REGISTRY
    const meta = APP_REGISTRY[appId];
    const platform = meta?.platform || "weixin";
    const provider = meta?.provider || "weixin-mini";
    if (!meta) {
      console.warn(`[migrate] 未知 appId=${appId},请补登 APP_REGISTRY`);
    }

    await db.collection("user_app").updateOne(
      { userId: user._id, appId },
      {
        $setOnInsert: {
          roles,
          status: "active",
          source: "migrated",
          grantedAt: null,
        },
      },
      { upsert: true }
    );

    if (entry.wxopenid) {
      const unionid = entry.unionid || user.social?.wechat?.unionid || null;
      const insert = {
        userId: user._id,
        platform,
        provider,
      };
      // unionid 只在有值且首次写入时设置:
      // 重跑脚本不能把库里已有的 unionid 覆盖成 null
      if (unionid) insert.unionid = unionid;

      await db.collection("user_identity").updateOne(
        { appId, provider, openid: entry.wxopenid },
        { $setOnInsert: insert },
        { upsert: true }
      );
    }
  }
}

回填前后各跑一次校验:

// 每个 user.app 条目都能在 user_app 找到
// 每个 wxopenid 都能在 user_identity 找到
// 没有 userId + appId 重复
// 没有 appId + provider + openid 重复

7.3 索引建立顺序

  1. 先跑重复检查。
  2. 建 user_app、user_identity 索引。
  3. 再回填数据。
  4. 回填完成后再次校验唯一性。

如果先回填后建索引,历史脏数据会让建索引失败,且报错只给出冲突键,不利于定位。

8. 测试与验收

8.1 自动化测试

在 api/user/test/ 增加:

用例 预期
新用户微信登录 user、user_identity、user_app 各一条
同 openid 再次登录 不新增用户;lastLoginAt 更新
两个用户绑定同一 openid 后者 409,前者身份不变
同一用户登录第二个应用 新增 user_app,不新增 user
A 应用 admin 访问 B 应用 admin 接口 403
成员 status = disabled 调用挂 appId 的接口(含未传 roles 的) 403
普通用户调用 /user/list 401/403(现实现已在 handler 内校验,切换后保持)
无 membership 的登录用户访问应用接口 403
相同 unionid、不同 openid 合并到同一 user
/user/userInfo 同时返回 apps(含 config)和兼容 app
写入未声明的 config key(如 role) 400,权限字段不变
只传部分 config key 只更新传入项,其余保持不变
config 超过 8KB 400
部分更新嵌套 config(只传 notifications.marketing) notifications.orderStatus 保持原值/默认值,不被清空
更新未配置 config schema 的 appId(如 ttapp-escort) 400,不是 500
不同 openid 绑定已属于他人的 unionid 409,不做静默改绑
撤销最后一个 admin 400
撤销后该用户调用管理接口 403
回填脚本执行两次 结果一致,无重复

现有 test/api.test.js 中的注册、登录、更新、退出用例必须保持通过。

8.2 上线验收

  1. 用现网管理员账号登录管理端,/user/list 正常且只返回 wxapp-escort 的有效成员。
  2. 用一个普通账号登录 C 端,响应中 apps 只有 wxapp-escort。
  3. 同一账号登录管理端后,user_app 新增管理员应用成员;C 端仍可正常鉴权。
  4. 人工制造重复 openid(测试库)验证唯一索引拦截。
  5. api/health 在过渡期读兼容 app 仍判定管理员正确。

9. 回滚

  • P1:删除新建集合和模型注册,无影响。
  • P2:旧 app 字段仍在写入,直接回退代码即可。
  • P3:回退到旧 auth / userList / userInfo 实现;旧字段因 P2 双写仍然完整。
  • P4 之后:需要从备份恢复 user 集合。执行 P4 前必须确认 P3 已稳定运行至少一个发布周期,且下游不再依赖旧字段。

10. 风险与待确认

风险 处理
MongoDB 不是副本集,无法使用多文档事务 全流程使用 upsert + 唯一索引,允许失败后重试;不依赖事务
jscode2session 不返回 unionid 代码必须允许 unionid 为空;跨应用合并退化为手机号
api/health 直接读 user.app 过渡期保留兼容视图;后续单独改造 permissions.js
web_tcm 读 app.tcm.organization.id 过渡期映射 config.defaultOrgId 或顶层 orgId;长期改读 apps[].config
conf.json 不在版本库 新增 app 时需要运维同步配置;APP_REGISTRY 启动时校验覆盖
历史账号角色缺失(原 isAdmin 兼容放行) 回填时默认 roles: ["user"];管理员账号必须显式 ["admin"],不再保留“缺 role 即管理员”
客户端仍读 user.app 兼容视图保留一个发布周期,前端逐步改读 apps
未来接入多个微信开放平台主体 unionid 唯一键需追加 openPlatformId;单主体阶段可先按 provider + unionid
config 里混入需要索引/鉴权的字段 明确禁止;需要查询或数据范围的字段提升为 user_app 顶层字段并建索引
Map 内 Mixed 值的嵌套属性被就地修改 文档级写入用 config.set(key, value) 整值替换;updateOne 用叶子路径 $set: { "config.<a>.<b>": value }
只改嵌套 config 的单个字段导致兄弟字段被清空 接口按叶子路径写入;读取时 resolveConfig 对已知嵌套对象做一层深合并
客户端借 config 写权限字段 key 由 Joi 白名单固定,未知 key 直接 400;config 接口只改当前用户自己的成员记录
11000 可能来自 unionid 唯一索引 catch 中按 err.keyPattern 区分 openid / unionid,回查归属后再决定 409
未传 appId 的接口无法表达应用级停用 依赖应用可用性的接口必须挂 appId,路由评审逐条确认
应用没有 config schema(如 ttapp-escort) 写入接口先判 hasConfigSchema,返回 400 而不是抛 500

待确认:

  1. 应用级停用/开通是只做 POST /user/grant + 运维脚本,还是需要管理后台?本次按“接口 + 脚本”实现。
  2. tcm Web 应用是否要纳入本次成员模型?
  3. 抖音端 appId 是否确定为 ttapp-escort?该应用暂无 config schema,写入接口会返回 400。
  4. 跨应用合并是否只认 unionid,还是继续保留手机号合并(仅限服务端验证过的手机号)?
  5. 多应用同时登录(不互踢)是否要在本阶段解决?

11. 涉及文件清单

文件 改动
api/user/models/schema/user.js 删除 app;收紧 strict;delUser 级联清理 user_app / user_identity
api/user/models/schema/user_app.js 新增
api/user/models/schema/user_identity.js 新增
api/user/models/app_registry.js 新增 appId → platform/provider 映射;assertRegistryCoverage() 启动校验
api/user/models/app_config.js 新增各应用的 config 白名单 schema、默认值、校验函数、hasConfigSchema、plainConfig、isPlainObject
api/user/models/index.js 注册 UserApp、UserIdentity 模型
api/user/handler/users.js 重写 wxSignin;userList 改查成员表;新增 buildUserView、appConfig、grant handler
api/user/middleware/auth.js auth 增加 appId + 应用内角色判定(传 appId 即校验 membership);改造 isAdmin
api/user/routes/index.js /user/list 绑定管理端 appId 与角色;新增 POST /user/app-config、POST /user/grant
api/user/app.js 启动阶段调用 assertRegistryCoverage()
api/user/scripts/grant_admin.js 新增:首个管理员授权与紧急恢复脚本
api/user/scripts/diff_legacy_vs_new.js 新增:切读前全量 diff,逐用户/逐 appId/逐 openid 比对
api/user/test/*.test.js 补充身份、成员、权限隔离、config 部分更新、授权、回填用例
doc/wechatpay-plan.md 过渡期仍引用 app,需在 P5 一并更新
api/health/utils/permissions.js 过渡期不改;P5 改读 user_app
ui/web_tcm/src/stores/tcm_organization.js P5 改读 apps[].config 或 apps[].orgId
api/user/scripts/create_web_admin.js Web 后台管理员初始化脚本:P2 前写旧 app,P4 后改写入 user_app(appId=web-escort-admin)

12. 重构规则(v1 契约冻结)

本次重构在不改动现有 API 契约的前提下替换数据模型。以下规则是实施硬约束,违反任意一条视为回归。

编号 规则 落地方式
R1 只增不改不删:v1 八个接口的 path、method、入参、响应字段名与语义不变;仅允许新增只读字段 apps 不改路由签名;响应在 sanitizeUser 之后追加 apps
R2 适配层单点:app 与 apps 只能由 buildLegacyUserView() 生成 禁止 handler 各自拼装;禁止把 user_app 原始文档直接返回
R3 登录等价 + 兜底:切读前必须做 openid 全量 diff;新表未命中时必须回查旧 app 字段,命中则补写新表;仍无才按新用户创建 见 6.3 步骤 1.5;发布前跑全量 diff,0 差异才允许上线
R4 token 单一凭证:不新增 token 类型;v1 增强不改变签发与校验逻辑 issueToken / findUserByToken 保持不变
R5 回填无损:旧 app 的每个 key 都必须进入 user_app;未在 APP_REGISTRY 登记的 appId 不能丢弃 未知 appId 走兜底 platform/provider 并告警,日志列出清单
R6 语义冻结,唯一例外是 /user/list 只返回 status = active 已确认:现网 36 人全为 active,上线当天结果不变
R7 直接切读,无开关,回滚靠重新部署 因此 R3 的全量 diff 是唯一发布卡点,必须完成
R8 不新增 v2 接口;app 在“所有客户端改读 apps 后的下个发布周期”移除 移除前标注 deprecated,响应中保留

12.1 属于“新增”、不受 R1 限制的内容

  • POST /user/app-config、POST /user/grant:新路径,不影响任何 v1 接口。
  • apps[] 及其 config:只读投影字段。
  • user_app、user_identity 集合与索引。

12.2 发布前检查清单

  1. 全量 diff 脚本输出 0 差异:逐用户、逐 appId、逐 openid 比对 userId。
  2. 用现网 36 个 openid 各跑一次 v1 wxsignin(预发环境),全部命中已有 userId,无新建账号。
  3. 用管理员账号的 token 调 api/health 管理端接口,管理员判定不变。
  4. web_tcm 登录后 app.tcm.role 仍可读(若该 app 有数据)。
  5. 普通账号调 /user/list,仍返回 401/403。

12.3 明确不做的

  • 不新增 v2 路径、不做请求头版本协商。
  • 不在本次引入 user_session,单 token 互踢行为保持现状。
  • 不改 security.token 的存储方式与有效期。
  • 不要求 api/health 或前端在本次发布同步改动。

13. 与陪诊业务(管理员代客下单)的联动决策

doc/escort-admin-sync-plan.md 的 B3(管理员代客下单)已定案采用「档案锚定」归属,与本方案的安全约束互洽,记录如下,避免实施时重新讨论:

  1. health 侧不新增按 userId 查询用户的接口。 管理员建单时订单归属取所选健康档案的 profile.userId,不传、也不信任管理员传入的 userId。这与 api/health/utils/user_service.js 中「user 服务不接受按 userId 明文查询」的既有约束一致。
  2. 档案无归属时订单 userId 留空,后期补。 escort_record.userId 非必填;补归属由管理员在 health 侧订单编辑完成(RECORD_FIELDS 已含 userId),不依赖 user 服务。留空订单对 C 端不可见(按 userId 查询不命中),补齐后客户才可见。
  3. 补归属不依赖账号合并,也不新增接口。 管理端通过 POST /user/list(已实现为「wxapp-escort 有效成员」口径,支持 keyword 且返回 total)人工核对客户,确认后把 userId 写入档案或订单;unionid / 手机号合并只影响账号归并,与补归属无关。
  4. web-escort-admin(Web 后台)如后续支持代客下单,沿用同一规则:档案锚定、不传 userId、无归属留空。
  5. 本节为业务层约定,不改动 R1-R8 任何契约。

附:本方案只改 api/user 的模型与接口,不包含会话表、权限管理后台、细粒度 RBAC。user_session 作为独立事项另行评估。