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
+122
View File
@@ -0,0 +1,122 @@
"use strict";
/**
* 创建 / 重置 Web 后台管理员账号
*
* 用途:Web 后台(ui/web_escort_admin)还没有任何管理账号时的初始化入口。
* 之所以用脚本而不是接口:登录只会授予普通成员身份,管理员角色必须有服务端授权入口,
* 由脚本直接写库是首个管理员最稳妥的来源(与 doc/user-multi-app-plan.md 6.8 一致)。
*
* 用法:
* node scripts/create_web_admin.js [手机号] [密码] [姓名]
*
* 默认值:13800000000 / Escort@2026 / 系统管理员
*
* 行为:
* - 手机号不存在 → 新建账号并写入密码
* - 手机号已存在 → 重置密码与失败次数(幂等,可重复执行)
* - 两种情况下都把 app["web-escort-admin"].role 置为 ["admin"]
*
* 注意:这里同时写旧字段 app 和新表 user_app:
* - app 供 api/health 等未迁移的下游继续读取
* - user_app 供重构后的登录/鉴权读取
* 下个版本下游全部迁移后再删除旧字段写入。
*/
import mongoose from "mongoose";
import config from "../conf.json" with { type: "json" };
import { UserSchema } from "../models/schema/user.js";
import { UserAppSchema } from "../models/schema/user_app.js";
import { hashPassword } from "../utils/crypto.js";
const WEB_ADMIN_APP = "web-escort-admin";
const DEFAULT_MOBILE = "13800000000";
const DEFAULT_PASSWORD = "Escort@2026";
const DEFAULT_NAME = "系统管理员";
const mobile = String(process.argv[2] || DEFAULT_MOBILE).trim();
const password = String(process.argv[3] || DEFAULT_PASSWORD);
const name = String(process.argv[4] || DEFAULT_NAME).trim();
async function main() {
if (!/^1[3-9]\d{9}$/.test(mobile)) {
throw new Error("手机号格式不正确");
}
if (password.length < 6) {
throw new Error("密码至少 6 位");
}
const connection = mongoose.createConnection(config.mongodb.str, config.mongodb.option);
await connection.asPromise();
const User = connection.model("user", UserSchema);
// 注册 UserApp 模型:autoIndex 由此确保 userId+appId 唯一索引存在,
// 全新环境先跑本脚本(先于 migrate / 服务启动)也不会缺索引
const UserApp = connection.model("user_app", UserAppSchema);
const passwd = await hashPassword(password);
let user = await User.findOne({ "profile.mobile": mobile });
let created = false;
if (!user) {
user = new User({
profile: { name, mobile },
security: { passwd, passwdSalt: undefined },
status: { account: "normal" },
app: {},
meta: { createtime: Date.now(), updatetime: Date.now() },
});
created = true;
} else {
// 已存在则重置凭证:脚本是唯一的管理员恢复手段,不做「已存在就跳过」
user.security.passwd = passwd;
user.security.passwdSalt = undefined;
user.security.failedLoginAttempts = 0;
user.status.account = "normal";
if (!user.profile?.name) user.profile.name = name;
user.meta = { ...(user.meta || {}), updatetime: Date.now() };
}
// 只授予 Web 后台这一个应用的 admin,不动小程序端(wxapp-escort-admin)的身份
user.app = user.app || {};
user.app[WEB_ADMIN_APP] = {
...(user.app[WEB_ADMIN_APP] || {}),
role: ["admin"],
};
await user.save();
// 新模型(doc/user-multi-app-plan.md 方案 B)的授权主体是 user_app,
// isAdmin / auth({ appIds }) 只认这张表;旧 app 字段仅为下游过渡期兼容
await UserApp.updateOne(
{ userId: user._id, appId: WEB_ADMIN_APP },
{
$addToSet: { roles: "admin" },
$set: { status: "active", grantedAt: new Date() },
$setOnInsert: { source: "manual" },
},
{ upsert: true }
);
const membership = await UserApp.findOne({ userId: user._id, appId: WEB_ADMIN_APP });
if (!membership) {
throw new Error("写入 user_app 成员关系失败");
}
console.log("---------------------------------------------");
console.log(created ? "已创建 Web 后台管理员账号" : "已重置现有账号为 Web 后台管理员");
console.log(` 用户ID : ${user._id}`);
console.log(` 姓名 : ${user.profile?.name || name}`);
console.log(` 手机号 : ${mobile}`);
console.log(` 密码 : ${password}`);
console.log(` 应用 : ${WEB_ADMIN_APP} / role=admin`);
console.log("---------------------------------------------");
console.log("请登录后尽快修改默认密码。");
await connection.close();
}
main().catch(async (err) => {
console.error("[create_web_admin] 失败:", err.message);
process.exitCode = 1;
});