"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 };