feat: 用户多应用成员关系与微信扫码登录

- 新增 user_app / user_identity 模型、应用注册表与成员关系服务,启动时校验配置覆盖

- 新增微信开放平台扫码登录:二维码地址、回调与 ticket 换取 token

- 管理端接口改为路由层声明 appIds + 角色鉴权,新增批量用户信息、锁定、授权与个人配置

- 删除账号同步清理成员关系与外部身份,避免关系被新账号复用

- 补充多应用、应用配置、注册表测试与迁移/建号脚本
This commit is contained in:
lik
2026-11-06 19:47:51 +08:00
parent a429079cd9
commit 946160f3f4
23 changed files with 2638 additions and 99 deletions
+119
View File
@@ -0,0 +1,119 @@
"use strict";
import Joi from "joi";
/**
* 每个应用的用户个人配置白名单
*
* Joi 对象默认拒绝未声明的 key,客户端传 { role: ["admin"] } 会直接 400,
* 无法借配置接口改权限。键默认可选,因此同一份 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"),
}),
};
/**
* 默认值放代码里,数据库只保存用户改过的项。
* 默认值调整后对未覆盖该 key 的用户立即生效,不需要批量回填。
*/
export 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",
},
};
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;
}
export function isPlainObject(value) {
return !!value && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date);
}
/**
* Map(Mongoose / JS Map)与 lean 返回的普通对象都要兼容
*/
export function plainConfig(value) {
if (!value) return {};
if (value instanceof Map) return Object.fromEntries(value);
return value;
}
/**
* 合并默认值与已存配置:已知嵌套对象做一层深合并,
* 库里只存了部分字段时默认值仍能补齐。
*/
export 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;
}
/**
* 展开为叶子路径:{ notifications: { marketing: false } }
* -> { "notifications.marketing": false }
* 数组和标量整体替换,不做逐项合并。
*/
export function flattenLeaves(input, base = "") {
const out = {};
for (const [key, value] of Object.entries(input || {})) {
const path = base ? `${base}.${key}` : key;
if (isPlainObject(value)) {
Object.assign(out, flattenLeaves(value, path));
} else {
out[path] = value;
}
}
return out;
}
+49
View File
@@ -0,0 +1,49 @@
"use strict";
import config from "../conf.json" with { type: "json" };
/**
* appId -> 平台/登录方式 元数据
*
* conf.json 只放 appid / secret;平台与登录方式放代码里,便于评审与测试。
* 未在 conf.json 配置的应用(ttapp-escort / web-escort-admin / tcm)
* 只告警不阻塞启动:它们可能通过密码登录或其他服务写入成员关系。
*/
export const APP_REGISTRY = {
"wxapp-escort": { platform: "weixin", provider: "weixin-mini" },
"wxapp-escort-admin": { platform: "weixin", provider: "weixin-mini" },
"ttapp-escort": { platform: "douyin", provider: "douyin-mini" },
"web-escort-admin": { platform: "weixin", provider: "weixin-web" },
tcm: { platform: "web", provider: "password" },
};
// 管理端应用:任一应用内的 admin 都视为管理端管理员
export const ADMIN_APP_IDS = ["wxapp-escort-admin", "web-escort-admin"];
// 本阶段只做固定角色白名单,不引入自定义 RBAC
export const GRANTABLE_ROLES = ["user", "admin"];
/**
* 启动校验:conf.json 中的 appId 必须有元数据;appId 不能含 . 或 $,
* 否则会被当成 Mongo 路径写坏文档。
*/
export function assertRegistryCoverage() {
const configured = Object.keys(config.app || {});
const invalid = configured.filter((id) => !/^[A-Za-z0-9_-]+$/.test(id));
if (invalid.length) {
throw new Error(`conf.json 中存在非法 appId(只允许字母、数字、_、-): ${invalid.join(", ")}`);
}
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;
}
+6
View File
@@ -2,6 +2,8 @@
import mongoose from 'mongoose';
import { UserSchema } from "./schema/user.js"
import { UserAppSchema } from "./schema/user_app.js"
import { UserIdentitySchema } from "./schema/user_identity.js"
import config from '../conf.json' with { type: 'json' };
import logger from '../utils/logger.js';
@@ -9,6 +11,8 @@ class MongoDBSchema {
constructor() {
this.dbConnection = null;
this.User = null;
this.UserApp = null;
this.UserIdentity = null;
}
init() {
@@ -35,6 +39,8 @@ class MongoDBSchema {
);
this.User = this.dbConnection.model('user', UserSchema)
this.UserApp = this.dbConnection.model('user_app', UserAppSchema)
this.UserIdentity = this.dbConnection.model('user_identity', UserIdentitySchema)
}
}
+13 -1
View File
@@ -208,7 +208,19 @@ UserSchema.statics.delUser = async function (_id, mobile, email, wxunionid, cb)
}
try {
return await this.findOneAndDelete(filter, cb);
const user = await this.findOne(filter);
if (!user) return null;
// 删除账号时同步清理成员关系与外部身份,避免残留关系被新账号复用。
// 用原生命令集合而不是 this.db.model(...):不依赖模型是否已注册。
await Promise.all([
this.db.collection('user_app').deleteMany({ userId: user._id }),
this.db.collection('user_identity').deleteMany({ userId: user._id }),
]);
await this.deleteOne({ _id: user._id });
if (typeof cb === 'function') cb(null, user);
return user;
} catch (error) {
return null;
}
+56
View File
@@ -0,0 +1,56 @@
"use strict";
import mongoose from "mongoose";
/**
* 用户与应用成员关系
*
* 一行代表「某用户在某应用中的授权状态」:
* - roles :应用内角色,首次登录固定为 ["user"],管理员只能由服务端授权
* - status :应用级启停,disabled 时挂 appId 的接口一律 403
* - config :应用内个人偏好,只放展示/偏好参数,禁止放权限与数据范围字段
*
* 注意:config 用 Map 而不是 Mixed,键级 set/delete 才能被 Mongoose 跟踪;
* 同时接口按叶子路径 $set,避免只改一个开关把同对象下其他字段清空。
*/
const UserAppSchema = new mongoose.Schema(
{
userId: { type: mongoose.Schema.Types.ObjectId, required: true, comment: "平台账号ID" },
appId: { type: String, required: true, comment: "应用ID" },
roles: { type: [String], default: ["user"], comment: "应用内角色" },
status: {
type: String,
enum: ["active", "disabled"],
default: "active",
comment: "应用级启停状态",
},
source: {
type: String,
enum: ["weixin-login", "manual", "migrated"],
default: "manual",
comment: "授权来源",
},
config: {
type: Map,
of: mongoose.Schema.Types.Mixed,
default: () => new Map(),
comment: "应用内个人配置",
},
configUpdatedAt: { type: Date, default: null, comment: "配置更新时间" },
grantedBy: { type: mongoose.Schema.Types.ObjectId, default: null, comment: "授权操作人" },
grantedAt: { type: Date, default: null, comment: "授权时间" },
lastLoginAt: { type: Date, default: null, comment: "最后登录时间" },
},
{
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 });
export { UserAppSchema };
+53
View File
@@ -0,0 +1,53 @@
"use strict";
import mongoose from "mongoose";
/**
* 外部登录身份
*
* 一行代表「某个外部账号(openid)对应哪个平台账号」:
* - appId + provider + openid:应用内身份唯一
* - provider + unionid :同一微信开放平台主体的跨应用身份
*
* openid / unionid 为空时必须写 undefined,不能写空字符串:
* partialFilterExpression 只按类型过滤,空字符串仍会被索引,
* 多个 openid: "" 会互相触发唯一冲突。
*/
const UserIdentitySchema = new mongoose.Schema(
{
userId: { type: mongoose.Schema.Types.ObjectId, required: true, comment: "平台账号ID" },
appId: { type: String, required: true, comment: "应用ID" },
platform: {
type: String,
enum: ["weixin", "douyin", "alipay", "web"],
required: true,
comment: "平台",
},
provider: {
type: String,
enum: ["weixin-mini", "weixin-web", "douyin-mini", "password"],
required: true,
comment: "登录方式",
},
openid: { type: String, comment: "应用内唯一身份" },
unionid: { type: String, comment: "跨应用身份" },
},
{
collection: "user_identity",
timestamps: true,
}
);
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 });
export { UserIdentitySchema };
+170
View File
@@ -0,0 +1,170 @@
"use strict";
import { DBModel } from "./index.js";
import { APP_REGISTRY } from "./app_registry.js";
/**
* 兼容旧数据:roles 可能是数组、字符串或缺省
*/
export function normalizeRoles(roles) {
if (Array.isArray(roles)) {
const list = roles.map((role) => String(role || "").trim()).filter(Boolean);
return list.length ? list : ["user"];
}
if (roles) return [String(roles).trim()].filter(Boolean);
return ["user"];
}
export function normalizeString(value) {
return typeof value === "string" && value.trim() ? value.trim() : undefined;
}
/**
* 回填脚本与登录兜底共用:写入一条成员关系,不覆盖已有角色。
*/
export async function upsertMigratedMembership({ userId, appId, roles }) {
await DBModel.UserApp.updateOne(
{ userId, appId },
{
$setOnInsert: {
roles: normalizeRoles(roles),
status: "active",
source: "migrated",
grantedAt: null,
},
},
{ upsert: true }
);
}
/**
* 微信登录:保证成员关系存在并刷新最后登录时间。
* 已存在的角色(例如管理员)不能被登录降级;disabled 状态也不能被登录自动恢复。
*/
export async function upsertLoginMembership({ userId, appId, now = new Date() }) {
await DBModel.UserApp.updateOne(
{ userId, appId },
{
$setOnInsert: {
roles: ["user"],
status: "active",
source: "weixin-login",
grantedAt: now,
},
$set: { lastLoginAt: now },
},
{ upsert: true }
);
}
/**
* 写入外部身份。
*
* filter 带 userId:openid 已绑到其他用户时不会静默命中,
* 而是走 upsert 触发唯一索引 11000,由调用方区分 409。
* unionid 为空时写 undefined(不写 $set),避免空字符串占用唯一键。
*/
export async function upsertIdentity({ userId, appId, platform, provider, openid, unionid }) {
const update = {
$setOnInsert: { userId, platform, provider },
};
if (normalizeString(unionid)) update.$set = { unionid: normalizeString(unionid) };
await DBModel.UserIdentity.updateOne(
{ appId, provider, openid, userId },
update,
{ upsert: true }
);
}
/**
* 登录时新表未命中、旧 app 字段命中的兜底:
* 补写 user_app / user_identity,避免每次登录都回退到全表查旧字段。
*/
export async function backfillOneFromLegacy(user, appId, openid, unionid) {
if (!user) return;
const entry = user.app?.[appId];
const target = entry && typeof entry === "object" ? entry : {};
await upsertMigratedMembership({
userId: user._id,
appId,
roles: target.role,
});
const normalizedOpenid = normalizeString(openid);
if (!normalizedOpenid) return;
const meta = APP_REGISTRY[appId] || { platform: "weixin", provider: "weixin-mini" };
const resolvedUnionid = normalizeString(unionid)
|| normalizeString(target.unionid)
|| normalizeString(user.social?.wechat?.unionid);
await upsertIdentity({
userId: user._id,
appId,
platform: meta.platform,
provider: meta.provider,
openid: normalizedOpenid,
unionid: resolvedUnionid,
});
}
/**
* 过渡期同步旧 user.app 的角色,保证 api/health 等下游仍能读到管理员身份。
* P4 切换完成后删除本函数与所有调用。
*/
export async function syncLegacyRoles({ userId, appId, addRoles = [], removeRoles = [] }) {
const update = {};
if (addRoles.length) {
update.$addToSet = { [`app.${appId}.role`]: { $each: addRoles } };
}
if (removeRoles.length) {
update.$pull = { [`app.${appId}.role`]: { $in: removeRoles } };
}
if (!Object.keys(update).length) return;
await DBModel.User.updateOne({ _id: userId }, update);
}
/**
* 授予角色(新表 + 过渡期旧字段)
*/
export async function grantRoles({ userId, appId, roles, grantedBy = null }) {
const list = [...new Set((roles || []).map((role) => String(role || "").trim()).filter(Boolean))];
if (!list.length) throw new Error("roles 不能为空");
const now = new Date();
await DBModel.UserApp.updateOne(
{ userId, appId },
{
$addToSet: { roles: { $each: list } },
$set: { status: "active", grantedBy, grantedAt: now },
$setOnInsert: { source: "manual" },
},
{ upsert: true }
);
await syncLegacyRoles({ userId, appId, addRoles: list });
return list;
}
/**
* 撤销角色(只撤销角色,不删除成员关系,保留审计信息)
*/
export async function revokeRoles({ userId, appId, roles, grantedBy = null }) {
const list = [...new Set((roles || []).map((role) => String(role || "").trim()).filter(Boolean))];
if (!list.length) return [];
await DBModel.UserApp.updateOne(
{ userId, appId },
{
$pull: { roles: { $in: list } },
$set: { grantedBy, grantedAt: new Date() },
}
);
await syncLegacyRoles({ userId, appId, removeRoles: list });
return list;
}