Compare commits
5
Commits
a429079cd9
...
ff262de194
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ff262de194 | ||
|
|
efd4e4444c | ||
|
|
5fabb6ba86 | ||
|
|
d7d12bb19a | ||
|
|
946160f3f4 |
@@ -1,3 +1,4 @@
|
||||
/node_modules/
|
||||
/logs/
|
||||
/backup/
|
||||
.env
|
||||
|
||||
@@ -3,11 +3,14 @@ import bodyParser from 'koa-bodyparser';
|
||||
import cors from '@koa/cors';
|
||||
import http from 'http';
|
||||
import { DBModel } from './models/index.js';
|
||||
import { assertRegistryCoverage } from './models/app_registry.js';
|
||||
import registerRoutes from './routes/index.js';
|
||||
import ResponseUtil from './utils/api_response.js';
|
||||
|
||||
class APP {
|
||||
constructor() {
|
||||
// 配置缺失在启动阶段暴露,而不是等某个应用首次登录才报错
|
||||
assertRegistryCoverage();
|
||||
this.app = new Koa();
|
||||
this.setupDB();
|
||||
this.setupMiddleware();
|
||||
|
||||
@@ -5,9 +5,15 @@
|
||||
"appid": "wxf73c79e16837af07",
|
||||
"secret": "5a061d65f4d35d19e62e83b98f6c63cf"
|
||||
},
|
||||
"wxapp-escort-admin": {
|
||||
"wxapp_companion": {
|
||||
"appid": "wxf94dd97b91af09a2",
|
||||
"secret": "79ba226684740830af0029763d3045f0"
|
||||
},
|
||||
"web-escort-admin": {
|
||||
"appid": "",
|
||||
"secret": "",
|
||||
"callbackUri": "https://api.huashengtec.com/user/wechat/qr/callback",
|
||||
"webOrigin": "http://escort.huashengtec.com/admin"
|
||||
}
|
||||
},
|
||||
"mongodb": {
|
||||
|
||||
+962
-72
File diff suppressed because it is too large
Load Diff
+66
-42
@@ -21,10 +21,16 @@ function extractToken(ctx) {
|
||||
/**
|
||||
* 按 token 查找用户
|
||||
* DB 中存储的是 token 的 sha256 哈希;兼容旧明文 token,命中后自动迁移为哈希
|
||||
* 多端会话:命中 security.tokens 中任意一条即可,同时兼容旧的单 token 字段
|
||||
*/
|
||||
async function findUserByToken(rawToken) {
|
||||
const hashed = await hashToken(rawToken);
|
||||
let user = await DBModel.User.findOne({ 'security.token': hashed });
|
||||
let user = await DBModel.User.findOne({
|
||||
$or: [
|
||||
{ 'security.tokens.hash': hashed },
|
||||
{ 'security.token': hashed },
|
||||
],
|
||||
});
|
||||
if (!user) {
|
||||
// 兼容旧明文 token
|
||||
user = await DBModel.User.findOne({ 'security.token': rawToken });
|
||||
@@ -36,14 +42,40 @@ async function findUserByToken(rawToken) {
|
||||
return user;
|
||||
}
|
||||
|
||||
/**
|
||||
* 取 token 命中会话的过期时间
|
||||
* @returns {Date|null|undefined} null=不过期;undefined=未命中任何会话
|
||||
*/
|
||||
function resolveTokenExpiry(user, hashedToken) {
|
||||
if (!user?.security) return undefined;
|
||||
const sessions = Array.isArray(user.security.tokens) ? user.security.tokens : [];
|
||||
const session = sessions.find((item) => item?.hash === hashedToken);
|
||||
if (session) {
|
||||
return session.expiry ? new Date(session.expiry) : null;
|
||||
}
|
||||
if (user.security.token === hashedToken) {
|
||||
return user.security.tokenExpiry ? new Date(user.security.tokenExpiry) : null;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 认证中间件 - 验证 token 并挂载用户信息到 ctx
|
||||
* 可选参数:
|
||||
* - required: 是否必须登录(默认 true)
|
||||
* - roles: 允许的角色列表(可选)
|
||||
* - appId / appIds: 允许访问的应用(任一即可),声明后必须存在有效成员关系
|
||||
* - roles: 允许的角色列表(必须与 appId / appIds 一起使用)
|
||||
*
|
||||
* 角色只在该应用内判定,不再遍历用户的所有应用;
|
||||
* 传 appIds 是为了同时支持小程序管理端与 Web 管理端。
|
||||
*/
|
||||
function auth(options = {}) {
|
||||
const { required = true, roles } = options;
|
||||
const { required = true, appId, appIds, roles } = options;
|
||||
const allowedAppIds = Array.isArray(appIds) && appIds.length
|
||||
? appIds
|
||||
: appId
|
||||
? [appId]
|
||||
: [];
|
||||
|
||||
return async (ctx, next) => {
|
||||
const token = extractToken(ctx);
|
||||
@@ -61,7 +93,10 @@ function auth(options = {}) {
|
||||
return ResponseUtil.unauthorized(ctx, '用户未登录或 token 无效');
|
||||
}
|
||||
|
||||
if (user.security.tokenExpiry && new Date() > user.security.tokenExpiry) {
|
||||
// 按本次 token 命中的会话判断过期,不能只看 legacy tokenExpiry:
|
||||
// 多端会话下其它端新登录不会影响本端
|
||||
const expiry = resolveTokenExpiry(user, await hashToken(token));
|
||||
if (expiry && new Date() > expiry) {
|
||||
return ResponseUtil.unauthorized(ctx, '登录已过期,请重新登录');
|
||||
}
|
||||
|
||||
@@ -69,17 +104,32 @@ function auth(options = {}) {
|
||||
return ResponseUtil.forbidden(ctx, '账户已被锁定');
|
||||
}
|
||||
|
||||
// 角色检查
|
||||
if (roles && roles.length > 0) {
|
||||
const hasRole = roles.some(role => {
|
||||
// 检查 app 字段中的角色
|
||||
return Object.values(user.app || {}).some(appData =>
|
||||
appData && Array.isArray(appData.role) && appData.role.includes(role)
|
||||
);
|
||||
});
|
||||
if (!hasRole) {
|
||||
return ResponseUtil.forbidden(ctx, '权限不足');
|
||||
if (allowedAppIds.length > 0) {
|
||||
// 一次取出所有允许应用的启用成员关系:用户可能同时是多个管理端成员,
|
||||
// 角色判定必须逐条看,不能只取排序第一条(否则 A 应用的 user 会挡住 B 应用的 admin)
|
||||
const memberships = await DBModel.UserApp.find({
|
||||
userId: user._id,
|
||||
appId: { $in: allowedAppIds },
|
||||
status: 'active',
|
||||
}).sort({ appId: 1 });
|
||||
|
||||
if (!memberships.length) {
|
||||
return ResponseUtil.forbidden(ctx, '无权访问该应用');
|
||||
}
|
||||
|
||||
let membership = memberships[0];
|
||||
if (roles && roles.length > 0) {
|
||||
membership = memberships.find((m) => roles.some((r) => m.roles?.includes(r)));
|
||||
if (!membership) {
|
||||
return ResponseUtil.forbidden(ctx, '权限不足');
|
||||
}
|
||||
}
|
||||
|
||||
ctx.state.membership = membership;
|
||||
ctx.state.appId = membership.appId;
|
||||
} else if (roles && roles.length > 0) {
|
||||
// 角色校验必须带应用维度,缺 appId 视为路由配置错误
|
||||
return ResponseUtil.internalError(ctx, '角色校验缺少 appId');
|
||||
}
|
||||
|
||||
ctx.state.user = user;
|
||||
@@ -87,33 +137,6 @@ function auth(options = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理端身份判定(与 health 服务 utils/permissions.js 同一口径)
|
||||
*
|
||||
* 不再用「app 里存在 wxapp-escort-admin 键」:该键历史上可由 /user/register 的
|
||||
* 客户端入参写入,任何人都能据此自封管理员。现在注册侧拒绝写 app,
|
||||
* 但库里可能残留历史账号,因此要求显式 role === 'admin';
|
||||
* role 缺失的历史账号暂按管理员放行并打告警,待库中补齐 role 后收紧。
|
||||
*
|
||||
* @param {Object} user 用户文档或脱敏后的用户对象
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function isAdmin(user) {
|
||||
const entry = user?.app?.['wxapp-escort-admin'];
|
||||
if (!entry) return false;
|
||||
|
||||
const roles = Array.isArray(entry.role) ? entry.role : [entry.role].filter(Boolean);
|
||||
if (roles.includes('admin')) return true;
|
||||
|
||||
if (entry.role === undefined) {
|
||||
console.warn(
|
||||
"[auth] 管理员账号缺少 role 字段,请补齐 app.wxapp-escort-admin.role = ['admin']"
|
||||
);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回用户安全对象(去除密码、token 等敏感字段)
|
||||
* 注意:登录/注册响应中的 token 由 handler 单独附加
|
||||
@@ -123,10 +146,11 @@ function sanitizeUser(user) {
|
||||
delete obj.security?.passwd;
|
||||
delete obj.security?.passwdSalt;
|
||||
delete obj.security?.token;
|
||||
delete obj.security?.tokens;
|
||||
delete obj.security?.tokenExpiry;
|
||||
delete obj.security?.passwordResetToken;
|
||||
delete obj.security?.passwordResetExpiry;
|
||||
return obj;
|
||||
}
|
||||
|
||||
export { auth, extractToken, sanitizeUser, findUserByToken, isAdmin };
|
||||
export { auth, extractToken, sanitizeUser, findUserByToken };
|
||||
|
||||
@@ -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_companion": 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_companion": {
|
||||
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;
|
||||
}
|
||||
@@ -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_companion": { 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_companion", "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;
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+24
-1
@@ -31,6 +31,17 @@ const UserSchema = mongoose.Schema(
|
||||
passwdSalt: { type: String, comment: '密码盐值' },
|
||||
token: { type: String, index: true, sparse: true, comment: '认证令牌' },
|
||||
tokenExpiry: { type: Date, comment: '令牌过期时间' },
|
||||
// 多端会话:每次登录追加一条(只存哈希),各端互不覆盖;
|
||||
// token/tokenExpiry 保留为最新会话的镜像,兼容仍读旧字段的客户端
|
||||
tokens: [
|
||||
{
|
||||
_id: false,
|
||||
hash: { type: String, index: true, sparse: true, comment: '令牌哈希' },
|
||||
expiry: { type: Date, comment: '过期时间' },
|
||||
appId: { type: String, default: '', comment: '登录来源应用' },
|
||||
createdAt: { type: Date, default: Date.now, comment: '签发时间' },
|
||||
},
|
||||
],
|
||||
failedLoginAttempts: { type: Number, default: 0, comment: '失败登录尝试次数' },
|
||||
lastLoginAt: { type: Date, comment: '最后登录时间' },
|
||||
lastLoginIp: { type: String, comment: '最后登录IP' },
|
||||
@@ -208,7 +219,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;
|
||||
}
|
||||
|
||||
@@ -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 };
|
||||
@@ -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 };
|
||||
@@ -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;
|
||||
}
|
||||
+17
-1
@@ -2,6 +2,9 @@ import Router from 'koa-router';
|
||||
import { HandlerUser } from '../handler/users.js';
|
||||
import { rateLimit } from '../middleware/ratelimit.js';
|
||||
import { auth } from '../middleware/auth.js';
|
||||
import { ADMIN_APP_IDS } from '../models/app_registry.js';
|
||||
|
||||
const adminAuth = auth({ appIds: ADMIN_APP_IDS, roles: ['admin'] });
|
||||
|
||||
class ApiRouter {
|
||||
constructor() {
|
||||
@@ -18,10 +21,23 @@ class ApiRouter {
|
||||
userRouter.post('/signin', rateLimit(10, 60_000), this.handler.signin.bind(this.handler));
|
||||
userRouter.post('/wxsignin', rateLimit(10, 60_000), this.handler.wxSignin.bind(this.handler));
|
||||
|
||||
// 微信扫码登录(开放平台网站应用):生成二维码地址 / 微信回调 / ticket 换 token
|
||||
userRouter.get('/wechat/qr/url', auth({ required: false }), rateLimit(20, 60_000), this.handler.wechatQrUrl.bind(this.handler));
|
||||
userRouter.get('/wechat/qr/callback', rateLimit(20, 60_000), this.handler.wechatQrCallback.bind(this.handler));
|
||||
userRouter.post('/wechat/qr/exchange', rateLimit(20, 60_000), this.handler.wechatQrExchange.bind(this.handler));
|
||||
|
||||
userRouter.post('/signout', auth({ required: false }), this.handler.signout.bind(this.handler));
|
||||
userRouter.post('/userInfo', auth({ required: false }), this.handler.userInfo.bind(this.handler));
|
||||
userRouter.post('/update', auth(), this.handler.updateUser.bind(this.handler));
|
||||
userRouter.post('/list', auth(), this.handler.userList.bind(this.handler));
|
||||
// 管理端接口统一在路由层声明应用与角色,handler 内不再重复鉴权
|
||||
userRouter.post('/list', adminAuth, this.handler.userList.bind(this.handler));
|
||||
// 管理端:批量取用户信息(就诊人/订单展示归属用户)、锁定/解锁
|
||||
userRouter.post('/info/batch', adminAuth, this.handler.batchUserInfo.bind(this.handler));
|
||||
userRouter.post('/lock', adminAuth, this.handler.lockUser.bind(this.handler));
|
||||
// 应用内个人配置:登录用户只能改自己的配置,成员关系在 handler 内按 appId 校验
|
||||
userRouter.post('/app-config', auth(), this.handler.appConfig.bind(this.handler));
|
||||
// 授权入口:管理员授予/撤销应用角色
|
||||
userRouter.post('/grant', adminAuth, this.handler.grant.bind(this.handler));
|
||||
userRouter.post('/wxgetphonenumber', rateLimit(10, 60_000), this.handler.wxGetPhoneNumber.bind(this.handler));
|
||||
|
||||
this.router.use(userRouter.routes());
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
"use strict";
|
||||
|
||||
/**
|
||||
* 备份 user 集合(P0)
|
||||
*
|
||||
* 用法:node scripts/backup_user_collection.js
|
||||
*
|
||||
* 输出到 api/user/backup/user-<时间戳>.json(已在 .gitignore 中排除)。
|
||||
* 备份文件包含密码哈希与 token 哈希,禁止提交到版本库。
|
||||
*/
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { DBModel } from "../models/index.js";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
async function main() {
|
||||
DBModel.init();
|
||||
await DBModel.dbConnection.asPromise();
|
||||
|
||||
try {
|
||||
const users = await DBModel.User.find({}).lean();
|
||||
const dir = path.join(__dirname, "..", "backup");
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
|
||||
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
|
||||
const file = path.join(dir, `user-${stamp}.json`);
|
||||
fs.writeFileSync(file, JSON.stringify(users, null, 2), "utf8");
|
||||
|
||||
console.log(`[backup] 已导出 ${users.length} 条 user 文档`);
|
||||
console.log(`[backup] ${file}`);
|
||||
} finally {
|
||||
await DBModel.dbConnection.close();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error("[backup] 失败:", err.message);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -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_companion)的身份
|
||||
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;
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
"use strict";
|
||||
|
||||
/**
|
||||
* 切读前全量 diff(R3)
|
||||
*
|
||||
* 用法:node scripts/diff_legacy_vs_new.js
|
||||
*
|
||||
* 逐用户 / 逐 appId / 逐 openid 比对旧 app 字段与新表:
|
||||
* - 旧 app 的每个 key 必须能在 user_app 命中
|
||||
* - 旧 app 的每个 wxopenid 必须能在 user_identity 命中且 userId 一致
|
||||
* - source=migrated 的成员关系必须有对应的旧 app 条目
|
||||
*
|
||||
* 输出 0 差异才允许发布;有差异时退出码为 1。
|
||||
*/
|
||||
|
||||
import { DBModel } from "../models/index.js";
|
||||
import { APP_REGISTRY } from "../models/app_registry.js";
|
||||
import { normalizeString } from "../models/user_membership.js";
|
||||
|
||||
async function main() {
|
||||
DBModel.init();
|
||||
await DBModel.dbConnection.asPromise();
|
||||
|
||||
const diffs = [];
|
||||
const stats = { users: 0, apps: 0, openids: 0, migrated: 0 };
|
||||
|
||||
try {
|
||||
const userCursor = DBModel.User.find({ app: { $type: "object" } })
|
||||
.batchSize(100)
|
||||
.lean()
|
||||
.cursor();
|
||||
|
||||
for await (const user of userCursor) {
|
||||
stats.users++;
|
||||
|
||||
for (const [appId, entry] of Object.entries(user.app || {})) {
|
||||
stats.apps++;
|
||||
|
||||
const membership = await DBModel.UserApp.findOne({
|
||||
userId: user._id,
|
||||
appId,
|
||||
}).lean();
|
||||
|
||||
if (!membership) {
|
||||
diffs.push({ type: "missing_membership", userId: String(user._id), appId });
|
||||
continue;
|
||||
}
|
||||
|
||||
const openid = normalizeString(entry?.wxopenid);
|
||||
if (!openid) continue;
|
||||
|
||||
stats.openids++;
|
||||
const meta = APP_REGISTRY[appId] || { provider: "weixin-mini" };
|
||||
const identity = await DBModel.UserIdentity.findOne({
|
||||
appId,
|
||||
provider: meta.provider,
|
||||
openid,
|
||||
}).lean();
|
||||
|
||||
if (!identity) {
|
||||
diffs.push({ type: "missing_identity", userId: String(user._id), appId, openid });
|
||||
continue;
|
||||
}
|
||||
|
||||
if (String(identity.userId) !== String(user._id)) {
|
||||
diffs.push({
|
||||
type: "identity_user_mismatch",
|
||||
userId: String(user._id),
|
||||
appId,
|
||||
openid,
|
||||
actualUserId: String(identity.userId),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 迁移来源的成员关系不能凭空多出来
|
||||
const migratedCursor = DBModel.UserApp.find({ source: "migrated" })
|
||||
.batchSize(100)
|
||||
.lean()
|
||||
.cursor();
|
||||
|
||||
for await (const membership of migratedCursor) {
|
||||
stats.migrated++;
|
||||
const user = await DBModel.User.findById(membership.userId)
|
||||
.select("app")
|
||||
.lean();
|
||||
|
||||
if (!user?.app?.[membership.appId]) {
|
||||
diffs.push({
|
||||
type: "extra_migrated_membership",
|
||||
userId: String(membership.userId),
|
||||
appId: membership.appId,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
console.log("---------------------------------------------");
|
||||
console.log(
|
||||
`[diff] 用户 ${stats.users},旧 app 条目 ${stats.apps},openid ${stats.openids},迁移成员 ${stats.migrated}`
|
||||
);
|
||||
console.log(`[diff] 差异 ${diffs.length}`);
|
||||
|
||||
diffs.slice(0, 50).forEach((item) => console.error(" 差异:", JSON.stringify(item)));
|
||||
|
||||
if (diffs.length) {
|
||||
process.exitCode = 1;
|
||||
} else {
|
||||
console.log("[diff] 0 差异,可以切读");
|
||||
}
|
||||
} finally {
|
||||
await DBModel.dbConnection.close();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error("[diff] 失败:", err.message);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
"use strict";
|
||||
|
||||
/**
|
||||
* 授权管理员 / 紧急恢复(不走 HTTP)
|
||||
*
|
||||
* 用法:
|
||||
* node scripts/grant_admin.js <userId> <appId> [roles]
|
||||
*
|
||||
* 示例:
|
||||
* node scripts/grant_admin.js 66f0... wxapp_companion admin
|
||||
* node scripts/grant_admin.js 66f0... wxapp_companion admin,user
|
||||
*
|
||||
* 同时写 user_app 与旧 app 字段,保证重构后的鉴权和 api/health 都能识别。
|
||||
*/
|
||||
|
||||
import mongoose from "mongoose";
|
||||
import { DBModel } from "../models/index.js";
|
||||
import { APP_REGISTRY, GRANTABLE_ROLES } from "../models/app_registry.js";
|
||||
import { grantRoles } from "../models/user_membership.js";
|
||||
|
||||
async function main() {
|
||||
const [userId, appId, rolesArg] = process.argv.slice(2);
|
||||
|
||||
if (!userId || !appId) {
|
||||
throw new Error("用法: node scripts/grant_admin.js <userId> <appId> [roles]");
|
||||
}
|
||||
if (!mongoose.isValidObjectId(userId)) {
|
||||
throw new Error("userId 不合法");
|
||||
}
|
||||
if (!APP_REGISTRY[appId]) {
|
||||
throw new Error(`未登记 appId: ${appId}`);
|
||||
}
|
||||
|
||||
const roles = (rolesArg ? rolesArg.split(",") : ["admin"])
|
||||
.map((role) => role.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
if (!roles.length || !roles.every((role) => GRANTABLE_ROLES.includes(role))) {
|
||||
throw new Error(`roles 只能是 ${GRANTABLE_ROLES.join(" / ")}`);
|
||||
}
|
||||
|
||||
DBModel.init();
|
||||
await DBModel.dbConnection.asPromise();
|
||||
|
||||
try {
|
||||
const user = await DBModel.User.findById(userId).select("_id profile.mobile");
|
||||
if (!user) throw new Error("用户不存在");
|
||||
|
||||
const granted = await grantRoles({ userId: user._id, appId, roles });
|
||||
|
||||
console.log("---------------------------------------------");
|
||||
console.log(`[grant_admin] 已授权 user=${user._id} app=${appId} roles=${granted.join(",")}`);
|
||||
console.log(`[grant_admin] 手机号: ${user.profile?.mobile || "-"}`);
|
||||
console.log("---------------------------------------------");
|
||||
} finally {
|
||||
await DBModel.dbConnection.close();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error("[grant_admin] 失败:", err.message);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,202 @@
|
||||
"use strict";
|
||||
|
||||
/**
|
||||
* 回填 user_app / user_identity(P2)
|
||||
*
|
||||
* 用法:node scripts/migrate_user_app.js
|
||||
*
|
||||
* 顺序(与 doc/user-multi-app-plan.md 7.3 一致):
|
||||
* 1. 检查旧数据重复 openid / unionid
|
||||
* 2. 建 user_app、user_identity 索引
|
||||
* 3. 按 _id 分批回填,幂等
|
||||
* 4. 回填后校验每个旧 app 条目都能在新表命中
|
||||
*
|
||||
* 未在 APP_REGISTRY 登记的 appId 不能丢弃:按微信小程序兜底并告警。
|
||||
*/
|
||||
|
||||
import { DBModel } from "../models/index.js";
|
||||
import { APP_REGISTRY } from "../models/app_registry.js";
|
||||
import {
|
||||
upsertIdentity,
|
||||
upsertMigratedMembership,
|
||||
normalizeRoles,
|
||||
normalizeString,
|
||||
} from "../models/user_membership.js";
|
||||
|
||||
async function checkDuplicates() {
|
||||
const duplicateOpenids = await DBModel.User.aggregate([
|
||||
{ $match: { app: { $type: "object" } } },
|
||||
{ $project: { appEntries: { $objectToArray: "$app" } } },
|
||||
{ $unwind: "$appEntries" },
|
||||
{ $match: { "appEntries.v.wxopenid": { $type: "string", $ne: "" } } },
|
||||
{ $addFields: { userId: "$_id" } },
|
||||
{
|
||||
$group: {
|
||||
_id: { appId: "$appEntries.k", openid: "$appEntries.v.wxopenid" },
|
||||
count: { $sum: 1 },
|
||||
userIds: { $push: "$userId" },
|
||||
},
|
||||
},
|
||||
{ $match: { count: { $gt: 1 } } },
|
||||
]).exec();
|
||||
|
||||
const duplicateUnionids = await DBModel.User.aggregate([
|
||||
{ $match: { app: { $type: "object" } } },
|
||||
{
|
||||
$project: {
|
||||
appEntries: { $objectToArray: "$app" },
|
||||
socialUnionid: "$social.wechat.unionid",
|
||||
},
|
||||
},
|
||||
{ $unwind: "$appEntries" },
|
||||
{
|
||||
$addFields: {
|
||||
unionid: { $ifNull: ["$appEntries.v.unionid", "$socialUnionid"] },
|
||||
},
|
||||
},
|
||||
{ $match: { unionid: { $type: "string", $ne: "" } } },
|
||||
{
|
||||
$group: {
|
||||
_id: "$unionid",
|
||||
// 同一用户的多个 app 条目会解析出同一个 unionid,必须按 userId 去重后判重,
|
||||
// 否则单个用户就会触发误报中止
|
||||
userIds: { $addToSet: "$_id" },
|
||||
},
|
||||
},
|
||||
{ $match: { $expr: { $gt: [{ $size: "$userIds" }, 1] } } },
|
||||
]).exec();
|
||||
|
||||
return { duplicateOpenids, duplicateUnionids };
|
||||
}
|
||||
|
||||
async function backfill() {
|
||||
const cursor = DBModel.User.find({ app: { $type: "object" } })
|
||||
.batchSize(100)
|
||||
.lean()
|
||||
.cursor();
|
||||
|
||||
const stats = { users: 0, memberships: 0, identities: 0, errors: 0, unknownApps: new Set() };
|
||||
|
||||
for await (const user of cursor) {
|
||||
stats.users++;
|
||||
|
||||
for (const [appId, entry] of Object.entries(user.app || {})) {
|
||||
const meta = APP_REGISTRY[appId];
|
||||
if (!meta) {
|
||||
stats.unknownApps.add(appId);
|
||||
console.warn(`[migrate] 未知 appId=${appId}(user=${user._id}),按微信小程序兜底,请补登 APP_REGISTRY`);
|
||||
}
|
||||
|
||||
const roles = normalizeRoles(entry?.role);
|
||||
|
||||
try {
|
||||
await upsertMigratedMembership({ userId: user._id, appId, roles });
|
||||
stats.memberships++;
|
||||
|
||||
const openid = normalizeString(entry?.wxopenid);
|
||||
if (openid) {
|
||||
const unionid = normalizeString(entry?.unionid)
|
||||
|| normalizeString(user.social?.wechat?.unionid);
|
||||
|
||||
await upsertIdentity({
|
||||
userId: user._id,
|
||||
appId,
|
||||
platform: meta?.platform || "weixin",
|
||||
provider: meta?.provider || "weixin-mini",
|
||||
openid,
|
||||
unionid,
|
||||
});
|
||||
stats.identities++;
|
||||
}
|
||||
} catch (err) {
|
||||
stats.errors++;
|
||||
console.error(`[migrate] 回填失败 user=${user._id} app=${appId}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return stats;
|
||||
}
|
||||
|
||||
async function verify() {
|
||||
const missing = [];
|
||||
|
||||
const cursor = DBModel.User.find({ app: { $type: "object" } })
|
||||
.batchSize(100)
|
||||
.lean()
|
||||
.cursor();
|
||||
|
||||
for await (const user of cursor) {
|
||||
for (const [appId, entry] of Object.entries(user.app || {})) {
|
||||
const membership = await DBModel.UserApp.exists({ userId: user._id, appId });
|
||||
if (!membership) {
|
||||
missing.push({ type: "membership", userId: String(user._id), appId });
|
||||
}
|
||||
|
||||
const openid = normalizeString(entry?.wxopenid);
|
||||
if (!openid) continue;
|
||||
|
||||
const meta = APP_REGISTRY[appId] || { provider: "weixin-mini" };
|
||||
const identity = await DBModel.UserIdentity.exists({
|
||||
appId,
|
||||
provider: meta.provider,
|
||||
openid,
|
||||
userId: user._id,
|
||||
});
|
||||
if (!identity) {
|
||||
missing.push({ type: "identity", userId: String(user._id), appId, openid });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return missing;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
DBModel.init();
|
||||
await DBModel.dbConnection.asPromise();
|
||||
|
||||
try {
|
||||
console.log("[migrate] 1/4 检查旧数据重复项...");
|
||||
const { duplicateOpenids, duplicateUnionids } = await checkDuplicates();
|
||||
if (duplicateOpenids.length || duplicateUnionids.length) {
|
||||
console.error("[migrate] 旧数据存在重复身份,已中止:");
|
||||
duplicateOpenids.forEach((item) => console.error(" openid:", JSON.stringify(item)));
|
||||
duplicateUnionids.forEach((item) => console.error(" unionid:", JSON.stringify(item)));
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
console.log("[migrate] 2/4 建立索引...");
|
||||
await Promise.all([
|
||||
DBModel.UserApp.createIndexes(),
|
||||
DBModel.UserIdentity.createIndexes(),
|
||||
]);
|
||||
|
||||
console.log("[migrate] 3/4 回填 user_app / user_identity...");
|
||||
const stats = await backfill();
|
||||
|
||||
console.log("[migrate] 4/4 校验回填结果...");
|
||||
const missing = await verify();
|
||||
|
||||
console.log("---------------------------------------------");
|
||||
console.log(`[migrate] 用户 ${stats.users},成员关系 ${stats.memberships},身份 ${stats.identities}`);
|
||||
console.log(`[migrate] 回填错误 ${stats.errors},未知 appId ${stats.unknownApps.size},校验缺失 ${missing.length}`);
|
||||
|
||||
if (stats.unknownApps.size) {
|
||||
console.log(`[migrate] 待补登 APP_REGISTRY: ${[...stats.unknownApps].join(", ")}`);
|
||||
}
|
||||
missing.slice(0, 20).forEach((item) => console.error(" 缺失:", JSON.stringify(item)));
|
||||
|
||||
if (stats.errors || missing.length) {
|
||||
process.exitCode = 1;
|
||||
}
|
||||
} finally {
|
||||
await DBModel.dbConnection.close();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error("[migrate] 失败:", err.message);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
+84
-2
@@ -24,6 +24,10 @@ describe('用户接口集成测试', () => {
|
||||
await DBModel.User.delUser(userId);
|
||||
}
|
||||
app.stop();
|
||||
// 关闭数据库连接,否则 node --test 进程不会退出
|
||||
if (DBModel.dbConnection) {
|
||||
await DBModel.dbConnection.close();
|
||||
}
|
||||
});
|
||||
|
||||
describe('POST /user/register', () => {
|
||||
@@ -125,6 +129,84 @@ describe('用户接口集成测试', () => {
|
||||
assert.equal(res.body.code, 401);
|
||||
});
|
||||
|
||||
it('多端登录互不踢下线,登出只失效当前端', async () => {
|
||||
// 模拟另一端登录:新 token 不应让已有 token 失效
|
||||
const second = await agent
|
||||
.post('/user/signin')
|
||||
.send({ mobile: testMobile, passwd: testPasswd });
|
||||
|
||||
assert.equal(second.body.code, 0, second.body.msg);
|
||||
const secondToken = second.body.data.user.security.token;
|
||||
assert.notEqual(secondToken, token);
|
||||
|
||||
const firstInfo = await agent
|
||||
.post('/user/userInfo')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({});
|
||||
assert.equal(firstInfo.body.code, 0, '另一端登录后,原 token 不应失效');
|
||||
|
||||
const secondInfo = await agent
|
||||
.post('/user/userInfo')
|
||||
.set('Authorization', `Bearer ${secondToken}`)
|
||||
.send({});
|
||||
assert.equal(secondInfo.body.code, 0, secondInfo.body.msg);
|
||||
|
||||
// 登出第二端,第一端保持在线
|
||||
const out = await agent
|
||||
.post('/user/signout')
|
||||
.set('Authorization', `Bearer ${secondToken}`)
|
||||
.send({});
|
||||
assert.equal(out.body.code, 0, out.body.msg);
|
||||
|
||||
const stillOnline = await agent
|
||||
.post('/user/userInfo')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({});
|
||||
assert.equal(stillOnline.body.code, 0, '登出另一端不应影响本端');
|
||||
|
||||
const revoked = await agent
|
||||
.post('/user/userInfo')
|
||||
.set('Authorization', `Bearer ${secondToken}`)
|
||||
.send({});
|
||||
assert.equal(revoked.body.code, 401);
|
||||
});
|
||||
|
||||
it('同一应用重复登录替换旧会话,不同应用各自保留', async () => {
|
||||
const login = (appId) => agent
|
||||
.post('/user/signin')
|
||||
.send({ mobile: testMobile, passwd: testPasswd, appId });
|
||||
|
||||
const admin1 = await login('web-escort-admin');
|
||||
const wx = await login('wxapp_companion');
|
||||
assert.equal(admin1.body.code, 0, admin1.body.msg);
|
||||
assert.equal(wx.body.code, 0, wx.body.msg);
|
||||
const admin1Token = admin1.body.data.user.security.token;
|
||||
const wxToken = wx.body.data.user.security.token;
|
||||
|
||||
// 管理端再次登录:只替换管理端自己的会话
|
||||
const admin2 = await login('web-escort-admin');
|
||||
assert.equal(admin2.body.code, 0, admin2.body.msg);
|
||||
const admin2Token = admin2.body.data.user.security.token;
|
||||
|
||||
const oldAdmin = await agent
|
||||
.post('/user/userInfo')
|
||||
.set('Authorization', `Bearer ${admin1Token}`)
|
||||
.send({});
|
||||
assert.equal(oldAdmin.body.code, 401, '同一应用旧会话应被替换');
|
||||
|
||||
const newAdmin = await agent
|
||||
.post('/user/userInfo')
|
||||
.set('Authorization', `Bearer ${admin2Token}`)
|
||||
.send({});
|
||||
assert.equal(newAdmin.body.code, 0, newAdmin.body.msg);
|
||||
|
||||
const wxStill = await agent
|
||||
.post('/user/userInfo')
|
||||
.set('Authorization', `Bearer ${wxToken}`)
|
||||
.send({});
|
||||
assert.equal(wxStill.body.code, 0, '管理端重新登录不应踢掉小程序端');
|
||||
});
|
||||
|
||||
it('不存在的用户应返回 401', async () => {
|
||||
const res = await agent
|
||||
.post('/user/signin')
|
||||
@@ -194,12 +276,12 @@ describe('用户接口集成测试', () => {
|
||||
assert.equal(res.body.data.user.profile.name, '更新后的名字');
|
||||
});
|
||||
|
||||
it('无 token 更新应返回 400', async () => {
|
||||
it('无 token 更新应返回 401', async () => {
|
||||
const res = await agent
|
||||
.post('/user/update')
|
||||
.send({ profile: { name: 'test' } });
|
||||
|
||||
assert.equal(res.body.code, 400);
|
||||
assert.equal(res.body.code, 401);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
hasConfigSchema,
|
||||
validateAppConfig,
|
||||
resolveConfig,
|
||||
flattenLeaves,
|
||||
plainConfig,
|
||||
} from '../models/app_config.js';
|
||||
|
||||
describe('validateAppConfig', () => {
|
||||
it('接受已声明字段', () => {
|
||||
const value = validateAppConfig('wxapp-escort', {
|
||||
theme: 'dark',
|
||||
notifications: { marketing: false },
|
||||
});
|
||||
assert.equal(value.theme, 'dark');
|
||||
assert.equal(value.notifications.marketing, false);
|
||||
});
|
||||
|
||||
it('拒绝未声明 key(不能借 config 改权限)', () => {
|
||||
assert.throws(
|
||||
() => validateAppConfig('wxapp-escort', { role: ['admin'] }),
|
||||
/not allowed/
|
||||
);
|
||||
});
|
||||
|
||||
it('拒绝非法枚举值', () => {
|
||||
assert.throws(() => validateAppConfig('wxapp-escort', { theme: 'blue' }));
|
||||
});
|
||||
|
||||
it('未配置 schema 的应用抛错', () => {
|
||||
assert.equal(hasConfigSchema('ttapp-escort'), false);
|
||||
assert.throws(() => validateAppConfig('ttapp-escort', { theme: 'dark' }));
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveConfig', () => {
|
||||
it('空配置返回默认值', () => {
|
||||
assert.deepEqual(resolveConfig('wxapp-escort', {}), {
|
||||
theme: 'system',
|
||||
language: 'zh-CN',
|
||||
notifications: { orderStatus: true, marketing: false },
|
||||
});
|
||||
});
|
||||
|
||||
it('嵌套对象做一层深合并', () => {
|
||||
const config = resolveConfig('wxapp-escort', {
|
||||
notifications: { marketing: true },
|
||||
});
|
||||
assert.equal(config.notifications.marketing, true);
|
||||
assert.equal(config.notifications.orderStatus, true);
|
||||
});
|
||||
|
||||
it('兼容 Map 存储', () => {
|
||||
const config = resolveConfig('wxapp_companion', new Map([['pageSize', 50]]));
|
||||
assert.equal(config.pageSize, 50);
|
||||
assert.equal(config.soundAlert, true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('flattenLeaves', () => {
|
||||
it('展开嵌套对象为叶子路径', () => {
|
||||
assert.deepEqual(flattenLeaves({ notifications: { marketing: false } }), {
|
||||
'notifications.marketing': false,
|
||||
});
|
||||
});
|
||||
|
||||
it('数组和标量整体替换', () => {
|
||||
assert.deepEqual(flattenLeaves({ list: [1, 2], theme: 'dark' }), {
|
||||
list: [1, 2],
|
||||
theme: 'dark',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('plainConfig', () => {
|
||||
it('Map 与普通对象都返回普通对象', () => {
|
||||
assert.deepEqual(plainConfig(new Map([['a', 1]])), { a: 1 });
|
||||
assert.deepEqual(plainConfig({ a: 1 }), { a: 1 });
|
||||
assert.deepEqual(plainConfig(null), {});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import config from '../conf.json' with { type: 'json' };
|
||||
import {
|
||||
APP_REGISTRY,
|
||||
ADMIN_APP_IDS,
|
||||
GRANTABLE_ROLES,
|
||||
assertRegistryCoverage,
|
||||
} from '../models/app_registry.js';
|
||||
|
||||
describe('APP_REGISTRY', () => {
|
||||
it('覆盖 conf.json 中所有 appId', () => {
|
||||
const configured = Object.keys(config.app || {});
|
||||
for (const appId of configured) {
|
||||
assert.ok(APP_REGISTRY[appId], `缺少 ${appId}`);
|
||||
assert.ok(APP_REGISTRY[appId].platform);
|
||||
assert.ok(APP_REGISTRY[appId].provider);
|
||||
}
|
||||
});
|
||||
|
||||
it('启动校验不抛错', () => {
|
||||
assert.doesNotThrow(() => assertRegistryCoverage());
|
||||
});
|
||||
|
||||
it('管理端应用与可授权角色配置正确', () => {
|
||||
assert.ok(ADMIN_APP_IDS.includes('wxapp_companion'));
|
||||
assert.ok(ADMIN_APP_IDS.includes('web-escort-admin'));
|
||||
assert.deepEqual(GRANTABLE_ROLES, ['user', 'admin']);
|
||||
});
|
||||
});
|
||||
+1
-1
@@ -68,7 +68,7 @@ describe('sanitizeUser', () => {
|
||||
assert.equal(safe.security.passwdSalt, undefined);
|
||||
assert.equal(safe.security.passwordResetToken, undefined);
|
||||
assert.equal(safe.security.passwordResetExpiry, undefined);
|
||||
assert.equal(safe.security.token, 'valid_token');
|
||||
assert.equal(safe.security.token, undefined);
|
||||
assert.equal(safe.profile.mobile, '13800138000');
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,637 @@
|
||||
import { describe, it, before, after } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import crypto from 'node:crypto';
|
||||
import supertest from 'supertest';
|
||||
import { APP } from '../app.js';
|
||||
import { DBModel } from '../models/index.js';
|
||||
import { hashToken } from '../utils/crypto.js';
|
||||
|
||||
const ADMIN_APP = 'wxapp_companion';
|
||||
const WEB_ADMIN_APP = 'web-escort-admin';
|
||||
const CONSUMER_APP = 'wxapp-escort';
|
||||
|
||||
// 使用不会与真实用户冲突的号段:1399999 + 4 位序号
|
||||
const TEST_PREFIX = '1399999';
|
||||
let mobileSeq = 1000;
|
||||
function nextMobile() {
|
||||
mobileSeq += 1;
|
||||
return `${TEST_PREFIX}${mobileSeq}`;
|
||||
}
|
||||
|
||||
let app;
|
||||
let agent;
|
||||
let originalFetch;
|
||||
|
||||
async function cleanup() {
|
||||
const users = await DBModel.User.find({
|
||||
'profile.mobile': { $regex: `^${TEST_PREFIX}` },
|
||||
}).select('_id');
|
||||
|
||||
for (const user of users) {
|
||||
await DBModel.User.delUser(user._id);
|
||||
}
|
||||
}
|
||||
|
||||
async function createUser(mobile, name) {
|
||||
const rawToken = crypto.randomBytes(32).toString('hex');
|
||||
const user = await DBModel.User.create({
|
||||
profile: { name, mobile },
|
||||
security: {
|
||||
token: await hashToken(rawToken),
|
||||
tokenExpiry: new Date(Date.now() + 60 * 60 * 1000),
|
||||
},
|
||||
status: { account: 'normal' },
|
||||
social: { wechat: {} },
|
||||
app: {},
|
||||
});
|
||||
|
||||
return { user, token: rawToken };
|
||||
}
|
||||
|
||||
async function addMembership(userId, appId, roles, extra = {}) {
|
||||
return DBModel.UserApp.create({
|
||||
userId,
|
||||
appId,
|
||||
roles,
|
||||
status: 'active',
|
||||
source: 'manual',
|
||||
...extra,
|
||||
});
|
||||
}
|
||||
|
||||
before(async () => {
|
||||
app = new APP();
|
||||
agent = supertest(app.app.callback());
|
||||
await DBModel.dbConnection.asPromise();
|
||||
await cleanup();
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
if (originalFetch) globalThis.fetch = originalFetch;
|
||||
await cleanup();
|
||||
app.stop();
|
||||
await DBModel.dbConnection.close();
|
||||
});
|
||||
|
||||
describe('管理端权限', () => {
|
||||
it('管理端成员可访问 /user/list,普通成员 403', async () => {
|
||||
const admin = await createUser(nextMobile(), '测试管理员');
|
||||
await addMembership(admin.user._id, ADMIN_APP, ['admin']);
|
||||
|
||||
const normal = await createUser(nextMobile(), '普通成员');
|
||||
await addMembership(normal.user._id, CONSUMER_APP, ['user']);
|
||||
|
||||
const ok = await agent
|
||||
.post('/user/list')
|
||||
.set('Authorization', `Bearer ${admin.token}`)
|
||||
.send({ pageSize: 200 });
|
||||
|
||||
assert.equal(ok.body.code, 0, ok.body.msg);
|
||||
assert.ok(Array.isArray(ok.body.data.users));
|
||||
|
||||
const denied = await agent
|
||||
.post('/user/list')
|
||||
.set('Authorization', `Bearer ${normal.token}`)
|
||||
.send({});
|
||||
|
||||
assert.equal(denied.body.code, 403);
|
||||
});
|
||||
|
||||
it('A 应用 admin 不能访问管理端接口', async () => {
|
||||
const user = await createUser(nextMobile(), 'C端管理员');
|
||||
await addMembership(user.user._id, CONSUMER_APP, ['admin']);
|
||||
|
||||
const res = await agent
|
||||
.post('/user/list')
|
||||
.set('Authorization', `Bearer ${user.token}`)
|
||||
.send({});
|
||||
|
||||
assert.equal(res.body.code, 403);
|
||||
});
|
||||
|
||||
it('Web 管理端 admin 可访问 /user/list', async () => {
|
||||
const webAdmin = await createUser(nextMobile(), 'Web管理员');
|
||||
await addMembership(webAdmin.user._id, WEB_ADMIN_APP, ['admin']);
|
||||
|
||||
const res = await agent
|
||||
.post('/user/list')
|
||||
.set('Authorization', `Bearer ${webAdmin.token}`)
|
||||
.send({ pageSize: 10 });
|
||||
|
||||
assert.equal(res.body.code, 0, res.body.msg);
|
||||
});
|
||||
|
||||
it('disabled 成员 403', async () => {
|
||||
const disabled = await createUser(nextMobile(), '停用成员');
|
||||
await addMembership(disabled.user._id, ADMIN_APP, ['admin'], { status: 'disabled' });
|
||||
|
||||
const res = await agent
|
||||
.post('/user/list')
|
||||
.set('Authorization', `Bearer ${disabled.token}`)
|
||||
.send({});
|
||||
|
||||
assert.equal(res.body.code, 403);
|
||||
});
|
||||
|
||||
it('A 应用 user + B 应用 admin:按应用逐条判角色,必须放行', async () => {
|
||||
// 典型画像:先登录小程序管理端(自动 ["user"]),后被授予 Web 后台 ["admin"]。
|
||||
// wxapp_companion 排序在 web-escort-admin 之前,只取第一条判角色会误拒。
|
||||
const mixed = await createUser(nextMobile(), '混合角色管理员');
|
||||
await addMembership(mixed.user._id, ADMIN_APP, ['user']);
|
||||
await addMembership(mixed.user._id, WEB_ADMIN_APP, ['admin']);
|
||||
|
||||
const res = await agent
|
||||
.post('/user/list')
|
||||
.set('Authorization', `Bearer ${mixed.token}`)
|
||||
.send({ pageSize: 10 });
|
||||
|
||||
assert.equal(res.body.code, 0, res.body.msg);
|
||||
});
|
||||
|
||||
it('userList 关键词筛选只返回有效成员', async () => {
|
||||
const admin = await createUser(nextMobile(), '筛选管理员');
|
||||
await addMembership(admin.user._id, ADMIN_APP, ['admin']);
|
||||
|
||||
const active = await createUser(nextMobile(), '关键词有效成员');
|
||||
await addMembership(active.user._id, CONSUMER_APP, ['user']);
|
||||
|
||||
const disabled = await createUser(nextMobile(), '关键词停用成员');
|
||||
await addMembership(disabled.user._id, CONSUMER_APP, ['user'], { status: 'disabled' });
|
||||
|
||||
const res = await agent
|
||||
.post('/user/list')
|
||||
.set('Authorization', `Bearer ${admin.token}`)
|
||||
.send({ keyword: '关键词', pageSize: 200 });
|
||||
|
||||
assert.equal(res.body.code, 0, res.body.msg);
|
||||
const ids = res.body.data.users.map((user) => String(user._id));
|
||||
assert.ok(ids.includes(String(active.user._id)));
|
||||
assert.ok(!ids.includes(String(disabled.user._id)));
|
||||
});
|
||||
});
|
||||
|
||||
describe('用户视图与应用配置', () => {
|
||||
it('userInfo 返回 apps 与兼容 app,并保留 tcm.organization', async () => {
|
||||
const user = await createUser(nextMobile(), '视图用户');
|
||||
await addMembership(user.user._id, CONSUMER_APP, ['user'], {
|
||||
config: { theme: 'dark', notifications: { marketing: true } },
|
||||
});
|
||||
await DBModel.UserIdentity.create({
|
||||
userId: user.user._id,
|
||||
appId: CONSUMER_APP,
|
||||
platform: 'weixin',
|
||||
provider: 'weixin-mini',
|
||||
openid: `openid-view-${user.user._id}`,
|
||||
});
|
||||
await DBModel.User.updateOne(
|
||||
{ _id: user.user._id },
|
||||
{
|
||||
$set: {
|
||||
'app.tcm.organization.id': 'org-legacy-1',
|
||||
'app.tcm.role': ['user'],
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
const res = await agent
|
||||
.post('/user/userInfo')
|
||||
.set('Authorization', `Bearer ${user.token}`)
|
||||
.send({});
|
||||
|
||||
assert.equal(res.body.code, 0, res.body.msg);
|
||||
const view = res.body.data.user;
|
||||
const consumer = view.apps.find((item) => item.appId === CONSUMER_APP);
|
||||
|
||||
assert.ok(consumer);
|
||||
assert.equal(consumer.config.theme, 'dark');
|
||||
assert.equal(consumer.config.notifications.marketing, true);
|
||||
assert.equal(consumer.config.notifications.orderStatus, true);
|
||||
assert.deepEqual(view.app[CONSUMER_APP].role, ['user']);
|
||||
assert.ok(view.app[CONSUMER_APP].wxopenid);
|
||||
assert.equal(view.app.tcm.organization.id, 'org-legacy-1');
|
||||
});
|
||||
|
||||
it('app-config 只更新传入的叶子字段,未知 key 400', async () => {
|
||||
const user = await createUser(nextMobile(), '配置用户');
|
||||
await addMembership(user.user._id, CONSUMER_APP, ['user'], {
|
||||
config: { notifications: { orderStatus: false, marketing: false } },
|
||||
});
|
||||
|
||||
const ok = await agent
|
||||
.post('/user/app-config')
|
||||
.set('Authorization', `Bearer ${user.token}`)
|
||||
.send({
|
||||
appId: CONSUMER_APP,
|
||||
config: { notifications: { marketing: true } },
|
||||
});
|
||||
|
||||
assert.equal(ok.body.code, 0, ok.body.msg);
|
||||
assert.equal(ok.body.data.config.notifications.marketing, true);
|
||||
assert.equal(ok.body.data.config.notifications.orderStatus, false);
|
||||
|
||||
const stored = await DBModel.UserApp.findOne({
|
||||
userId: user.user._id,
|
||||
appId: CONSUMER_APP,
|
||||
}).lean();
|
||||
assert.equal(stored.config.notifications.marketing, true);
|
||||
assert.equal(stored.config.notifications.orderStatus, false);
|
||||
|
||||
const bad = await agent
|
||||
.post('/user/app-config')
|
||||
.set('Authorization', `Bearer ${user.token}`)
|
||||
.send({ appId: CONSUMER_APP, config: { role: ['admin'] } });
|
||||
|
||||
assert.equal(bad.body.code, 400);
|
||||
|
||||
const afterBad = await DBModel.UserApp.findOne({
|
||||
userId: user.user._id,
|
||||
appId: CONSUMER_APP,
|
||||
}).lean();
|
||||
assert.deepEqual(afterBad.roles, ['user']);
|
||||
});
|
||||
|
||||
it('未配置 schema 的应用返回 400,无成员关系返回 403', async () => {
|
||||
const user = await createUser(nextMobile(), '配置边界用户');
|
||||
await addMembership(user.user._id, 'ttapp-escort', ['user']);
|
||||
|
||||
const noSchema = await agent
|
||||
.post('/user/app-config')
|
||||
.set('Authorization', `Bearer ${user.token}`)
|
||||
.send({ appId: 'ttapp-escort', config: { theme: 'dark' } });
|
||||
|
||||
assert.equal(noSchema.body.code, 400);
|
||||
|
||||
const noMember = await agent
|
||||
.post('/user/app-config')
|
||||
.set('Authorization', `Bearer ${user.token}`)
|
||||
.send({ appId: CONSUMER_APP, config: { theme: 'dark' } });
|
||||
|
||||
assert.equal(noMember.body.code, 403);
|
||||
});
|
||||
});
|
||||
|
||||
describe('授权', () => {
|
||||
it('grant 授权 / 撤销,保护最后一个管理员,且不能跨应用授权', async () => {
|
||||
const webAdmin = await createUser(nextMobile(), 'Web管理员');
|
||||
await addMembership(webAdmin.user._id, WEB_ADMIN_APP, ['admin']);
|
||||
|
||||
const target = await createUser(nextMobile(), '授权目标');
|
||||
|
||||
// 跨应用授权被拒绝:Web 管理员不能授予小程序管理端的角色
|
||||
const crossApp = await agent
|
||||
.post('/user/grant')
|
||||
.set('Authorization', `Bearer ${webAdmin.token}`)
|
||||
.send({
|
||||
userId: String(target.user._id),
|
||||
appId: ADMIN_APP,
|
||||
action: 'grant',
|
||||
roles: ['admin'],
|
||||
});
|
||||
assert.equal(crossApp.body.code, 403, `应拒绝跨应用授权: ${crossApp.body.msg}`);
|
||||
|
||||
const grant = await agent
|
||||
.post('/user/grant')
|
||||
.set('Authorization', `Bearer ${webAdmin.token}`)
|
||||
.send({
|
||||
userId: String(target.user._id),
|
||||
appId: WEB_ADMIN_APP,
|
||||
action: 'grant',
|
||||
roles: ['admin'],
|
||||
});
|
||||
assert.equal(grant.body.code, 0, grant.body.msg);
|
||||
|
||||
const membership = await DBModel.UserApp.findOne({
|
||||
userId: target.user._id,
|
||||
appId: WEB_ADMIN_APP,
|
||||
}).lean();
|
||||
assert.ok(membership.roles.includes('admin'));
|
||||
|
||||
// 过渡期旧字段同步,api/health 仍能识别
|
||||
const legacy = await DBModel.User.findById(target.user._id).lean();
|
||||
assert.deepEqual(legacy.app[WEB_ADMIN_APP].role, ['admin']);
|
||||
|
||||
// 撤销目标管理员后 webAdmin 仍是管理员
|
||||
const revoke = await agent
|
||||
.post('/user/grant')
|
||||
.set('Authorization', `Bearer ${webAdmin.token}`)
|
||||
.send({
|
||||
userId: String(target.user._id),
|
||||
appId: WEB_ADMIN_APP,
|
||||
action: 'revoke',
|
||||
roles: ['admin'],
|
||||
});
|
||||
assert.equal(revoke.body.code, 0, revoke.body.msg);
|
||||
assert.deepEqual(revoke.body.data.roles, ['admin']);
|
||||
|
||||
// 最后一个管理员保护:若测试库中 webAdmin/target 之外没有其他真实管理员,
|
||||
// 撤销自己应被拒绝;现网库可能存在脚本创建的真实管理员,此时无法构造该场景
|
||||
const otherAdminCount = await DBModel.UserApp.countDocuments({
|
||||
appId: WEB_ADMIN_APP,
|
||||
status: 'active',
|
||||
roles: 'admin',
|
||||
userId: { $nin: [webAdmin.user._id, target.user._id] },
|
||||
});
|
||||
|
||||
if (otherAdminCount === 0) {
|
||||
const revokeLast = await agent
|
||||
.post('/user/grant')
|
||||
.set('Authorization', `Bearer ${webAdmin.token}`)
|
||||
.send({
|
||||
userId: String(webAdmin.user._id),
|
||||
appId: WEB_ADMIN_APP,
|
||||
action: 'revoke',
|
||||
roles: ['admin'],
|
||||
});
|
||||
assert.equal(revokeLast.body.code, 400);
|
||||
assert.match(revokeLast.body.msg, /最后一个管理员/);
|
||||
|
||||
// 保护触发后管理员身份未被撤销
|
||||
const stillAdmin = await DBModel.UserApp.findOne({
|
||||
userId: webAdmin.user._id,
|
||||
appId: WEB_ADMIN_APP,
|
||||
}).lean();
|
||||
assert.ok(stillAdmin.roles.includes('admin'));
|
||||
}
|
||||
});
|
||||
|
||||
it('撤销不存在的成员关系返回 404,撤销未持有的角色返回 400', async () => {
|
||||
const webAdmin = await createUser(nextMobile(), 'Web管理员2');
|
||||
await addMembership(webAdmin.user._id, WEB_ADMIN_APP, ['admin']);
|
||||
|
||||
const stranger = await createUser(nextMobile(), '无成员关系用户');
|
||||
|
||||
const noMembership = await agent
|
||||
.post('/user/grant')
|
||||
.set('Authorization', `Bearer ${webAdmin.token}`)
|
||||
.send({
|
||||
userId: String(stranger.user._id),
|
||||
appId: WEB_ADMIN_APP,
|
||||
action: 'revoke',
|
||||
roles: ['admin'],
|
||||
});
|
||||
assert.equal(noMembership.body.code, 404);
|
||||
|
||||
const notHeld = await agent
|
||||
.post('/user/grant')
|
||||
.set('Authorization', `Bearer ${webAdmin.token}`)
|
||||
.send({
|
||||
userId: String(webAdmin.user._id),
|
||||
appId: WEB_ADMIN_APP,
|
||||
action: 'revoke',
|
||||
roles: ['user'],
|
||||
});
|
||||
assert.equal(notHeld.body.code, 400);
|
||||
});
|
||||
});
|
||||
|
||||
describe('原有管理接口', () => {
|
||||
it('批量用户信息与锁定接口仍按管理端鉴权工作', async () => {
|
||||
const admin = await createUser(nextMobile(), '批量管理员');
|
||||
await addMembership(admin.user._id, ADMIN_APP, ['admin']);
|
||||
const target = await createUser(nextMobile(), '批量目标用户');
|
||||
|
||||
const batch = await agent
|
||||
.post('/user/info/batch')
|
||||
.set('Authorization', `Bearer ${admin.token}`)
|
||||
.send({ userIds: [String(target.user._id)] });
|
||||
|
||||
assert.equal(batch.body.code, 0, batch.body.msg);
|
||||
assert.equal(batch.body.data.users.length, 1);
|
||||
assert.ok(Array.isArray(batch.body.data.users[0].apps));
|
||||
|
||||
const locked = await agent
|
||||
.post('/user/lock')
|
||||
.set('Authorization', `Bearer ${admin.token}`)
|
||||
.send({ userId: String(target.user._id), locked: true });
|
||||
|
||||
assert.equal(locked.body.code, 0, locked.body.msg);
|
||||
|
||||
const afterLock = await DBModel.User.findById(target.user._id).lean();
|
||||
assert.equal(afterLock.status.account, 'lock');
|
||||
assert.equal(afterLock.security.token, null);
|
||||
});
|
||||
});
|
||||
|
||||
describe('微信登录', () => {
|
||||
const openidByCode = new Map();
|
||||
const unionidByCode = new Map();
|
||||
|
||||
let wxMobile;
|
||||
let wxOpenid;
|
||||
let wxUserId;
|
||||
|
||||
before(() => {
|
||||
originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = async (url) => {
|
||||
const parsed = new URL(String(url));
|
||||
|
||||
if (parsed.pathname.includes('jscode2session')) {
|
||||
const code = parsed.searchParams.get('js_code');
|
||||
if (!openidByCode.has(code)) {
|
||||
return new Response(
|
||||
JSON.stringify({ errcode: 40029, errmsg: 'invalid code' }),
|
||||
{ status: 200, headers: { 'Content-Type': 'application/json' } }
|
||||
);
|
||||
}
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
openid: openidByCode.get(code),
|
||||
unionid: unionidByCode.get(code),
|
||||
}),
|
||||
{ status: 200, headers: { 'Content-Type': 'application/json' } }
|
||||
);
|
||||
}
|
||||
|
||||
throw new Error(`unexpected fetch: ${url}`);
|
||||
};
|
||||
});
|
||||
|
||||
it('新用户登录写 user / user_identity / user_app', async () => {
|
||||
wxMobile = nextMobile();
|
||||
wxOpenid = `wx-openid-${wxMobile}`;
|
||||
openidByCode.set('code-new', wxOpenid);
|
||||
|
||||
const res = await agent.post('/user/wxsignin').send({
|
||||
code: 'code-new',
|
||||
appId: CONSUMER_APP,
|
||||
phoneNumber: wxMobile,
|
||||
name: '微信新用户',
|
||||
});
|
||||
|
||||
assert.equal(res.body.code, 0, res.body.msg);
|
||||
|
||||
const user = await DBModel.User.findOne({ 'profile.mobile': wxMobile });
|
||||
assert.ok(user);
|
||||
wxUserId = user._id;
|
||||
|
||||
assert.ok(
|
||||
await DBModel.UserIdentity.exists({
|
||||
appId: CONSUMER_APP,
|
||||
provider: 'weixin-mini',
|
||||
openid: wxOpenid,
|
||||
})
|
||||
);
|
||||
|
||||
const membership = await DBModel.UserApp.findOne({
|
||||
userId: user._id,
|
||||
appId: CONSUMER_APP,
|
||||
}).lean();
|
||||
assert.deepEqual(membership.roles, ['user']);
|
||||
assert.ok(res.body.data.user.apps.some((item) => item.appId === CONSUMER_APP));
|
||||
assert.ok(res.body.data.user.app[CONSUMER_APP].wxopenid);
|
||||
});
|
||||
|
||||
it('同 openid 再次登录不新增用户,并刷新 lastLoginAt', async () => {
|
||||
const res = await agent.post('/user/wxsignin').send({
|
||||
code: 'code-new',
|
||||
appId: CONSUMER_APP,
|
||||
phoneNumber: wxMobile,
|
||||
});
|
||||
|
||||
assert.equal(res.body.code, 0, res.body.msg);
|
||||
|
||||
const count = await DBModel.User.countDocuments({ 'profile.mobile': wxMobile });
|
||||
assert.equal(count, 1);
|
||||
|
||||
const membership = await DBModel.UserApp.findOne({
|
||||
userId: wxUserId,
|
||||
appId: CONSUMER_APP,
|
||||
}).lean();
|
||||
assert.ok(membership.lastLoginAt);
|
||||
});
|
||||
|
||||
it('同一 unionid 登录第二个应用合并到同一 user', async () => {
|
||||
unionidByCode.set('code-new', 'unionid-merge-1');
|
||||
|
||||
// 先让首个应用的身份补上 unionid(模拟微信开放平台已绑定)
|
||||
const repeat = await agent.post('/user/wxsignin').send({
|
||||
code: 'code-new',
|
||||
appId: CONSUMER_APP,
|
||||
phoneNumber: wxMobile,
|
||||
});
|
||||
assert.equal(repeat.body.code, 0, repeat.body.msg);
|
||||
|
||||
openidByCode.set('code-second-app', `wx-openid-admin-${wxMobile}`);
|
||||
unionidByCode.set('code-second-app', 'unionid-merge-1');
|
||||
|
||||
const res = await agent.post('/user/wxsignin').send({
|
||||
code: 'code-second-app',
|
||||
appId: ADMIN_APP,
|
||||
phoneNumber: wxMobile,
|
||||
});
|
||||
|
||||
assert.equal(res.body.code, 0, res.body.msg);
|
||||
|
||||
const user = await DBModel.User.findOne({ 'profile.mobile': wxMobile });
|
||||
assert.equal(String(user._id), String(wxUserId));
|
||||
|
||||
const memberships = await DBModel.UserApp.find({ userId: user._id }).lean();
|
||||
assert.ok(memberships.some((item) => item.appId === ADMIN_APP));
|
||||
|
||||
const identities = await DBModel.UserIdentity.find({ userId: user._id }).lean();
|
||||
assert.equal(identities.length, 2);
|
||||
});
|
||||
|
||||
it('旧 app 字段命中时复用老用户并补写新表', async () => {
|
||||
const mobile = nextMobile();
|
||||
const openid = `wx-legacy-${mobile}`;
|
||||
|
||||
const legacy = await DBModel.User.create({
|
||||
profile: { name: '旧用户', mobile },
|
||||
status: { account: 'normal' },
|
||||
social: { wechat: {} },
|
||||
app: {
|
||||
[CONSUMER_APP]: { role: ['user'], wxopenid: openid },
|
||||
},
|
||||
});
|
||||
|
||||
openidByCode.set('code-legacy', openid);
|
||||
|
||||
const res = await agent.post('/user/wxsignin').send({
|
||||
code: 'code-legacy',
|
||||
appId: CONSUMER_APP,
|
||||
phoneNumber: mobile,
|
||||
});
|
||||
|
||||
assert.equal(res.body.code, 0, res.body.msg);
|
||||
assert.equal(String(res.body.data.user._id), String(legacy._id));
|
||||
|
||||
const count = await DBModel.User.countDocuments({ 'profile.mobile': mobile });
|
||||
assert.equal(count, 1);
|
||||
|
||||
assert.ok(
|
||||
await DBModel.UserIdentity.exists({
|
||||
userId: legacy._id,
|
||||
appId: CONSUMER_APP,
|
||||
provider: 'weixin-mini',
|
||||
openid,
|
||||
})
|
||||
);
|
||||
assert.ok(
|
||||
await DBModel.UserApp.exists({
|
||||
userId: legacy._id,
|
||||
appId: CONSUMER_APP,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('手机号已在其他应用注册、本应用无成员关系时直接并入', async () => {
|
||||
const mobile = nextMobile();
|
||||
const openid = `wx-merge-${mobile}`;
|
||||
openidByCode.set('code-merge', openid);
|
||||
|
||||
// 老账号只有就诊人端成员关系,陪诊师端还没有
|
||||
const existing = await createUser(mobile, '梁娟');
|
||||
await addMembership(existing.user._id, CONSUMER_APP, ['user']);
|
||||
|
||||
const res = await agent.post('/user/wxsignin').send({
|
||||
code: 'code-merge',
|
||||
appId: ADMIN_APP,
|
||||
phoneNumber: mobile,
|
||||
name: '张三',
|
||||
});
|
||||
|
||||
assert.equal(res.body.code, 0, res.body.msg);
|
||||
assert.equal(String(res.body.data.user._id), String(existing.user._id));
|
||||
assert.equal(await DBModel.User.countDocuments({ 'profile.mobile': mobile }), 1);
|
||||
|
||||
// 只补当前应用的成员关系与 openid 身份,账号资料不被覆盖
|
||||
const membership = await DBModel.UserApp.findOne({
|
||||
userId: existing.user._id,
|
||||
appId: ADMIN_APP,
|
||||
}).lean();
|
||||
assert.ok(membership);
|
||||
assert.deepEqual(membership.roles, ['user']);
|
||||
|
||||
assert.ok(
|
||||
await DBModel.UserIdentity.exists({
|
||||
userId: existing.user._id,
|
||||
appId: ADMIN_APP,
|
||||
provider: 'weixin-mini',
|
||||
openid,
|
||||
})
|
||||
);
|
||||
|
||||
const user = await DBModel.User.findById(existing.user._id).lean();
|
||||
assert.equal(user.profile.name, '梁娟');
|
||||
});
|
||||
|
||||
it('手机号已在本应用注册时,换微信登录被拒绝', async () => {
|
||||
const mobile = nextMobile();
|
||||
const existing = await createUser(mobile, '梁娟');
|
||||
await addMembership(existing.user._id, ADMIN_APP, ['user']);
|
||||
|
||||
openidByCode.set('code-merge-bound', `wx-merge-bound-${mobile}`);
|
||||
|
||||
const res = await agent.post('/user/wxsignin').send({
|
||||
code: 'code-merge-bound',
|
||||
appId: ADMIN_APP,
|
||||
phoneNumber: mobile,
|
||||
name: '梁娟',
|
||||
});
|
||||
|
||||
assert.equal(res.body.code, 409);
|
||||
assert.match(res.body.msg, /已在本应用注册/);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user