Files
api_user/models/user_membership.js
lik 946160f3f4 feat: 用户多应用成员关系与微信扫码登录
- 新增 user_app / user_identity 模型、应用注册表与成员关系服务,启动时校验配置覆盖

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

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

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

- 补充多应用、应用配置、注册表测试与迁移/建号脚本
2026-11-06 19:47:51 +08:00

171 lines
4.8 KiB
JavaScript
Raw Permalink 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";
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;
}