Compare commits
28
Commits
main
...
ff262de194
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ff262de194 | ||
|
|
efd4e4444c | ||
|
|
5fabb6ba86 | ||
|
|
d7d12bb19a | ||
|
|
946160f3f4 | ||
|
|
a429079cd9 | ||
|
|
1bf584ad35 | ||
|
|
30d9a8503f | ||
|
|
be60104f21 | ||
|
|
acf89ba932 | ||
|
|
f0edd6d548 | ||
|
|
1974975882 | ||
|
|
2486b0a4b6 | ||
|
|
058e9135ae | ||
|
|
70307d4eb8 | ||
|
|
ddcf200de2 | ||
|
|
fba44ca015 | ||
|
|
b3f933e30a | ||
|
|
6fe4ba9fdd | ||
|
|
12be175ce8 | ||
|
|
f3cd769d7d | ||
|
|
ca147ac2a8 | ||
|
|
40f2c21bfa | ||
|
|
99108b2187 | ||
|
|
803d8b7bfb | ||
|
|
603f2987f6 | ||
|
|
2245960ccf | ||
|
|
2c6efee887 |
@@ -0,0 +1,4 @@
|
||||
/node_modules/
|
||||
/logs/
|
||||
/backup/
|
||||
.env
|
||||
Vendored
+17
@@ -0,0 +1,17 @@
|
||||
{
|
||||
// 使用 IntelliSense 了解相关属性。
|
||||
// 悬停以查看现有属性的描述。
|
||||
// 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
"name": "debug",
|
||||
"skipFiles": [
|
||||
"<node_internals>/**"
|
||||
],
|
||||
"program": "${workspaceFolder}\\index.js"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import Koa from 'koa';
|
||||
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();
|
||||
this.setupRoutes();
|
||||
this.setupFallback();
|
||||
}
|
||||
|
||||
setupDB() {
|
||||
DBModel.init();
|
||||
}
|
||||
|
||||
setupMiddleware() {
|
||||
// 服务在 nginx 之后,需信任代理头才能拿到真实客户端 IP
|
||||
// (否则 ctx.ip 恒为 127.0.0.1,限流会变成全站共享一个桶)
|
||||
this.app.proxy = true;
|
||||
this.app.proxyIpHeader = "X-Real-IP";
|
||||
|
||||
this.app.use(cors());
|
||||
this.app.use(bodyParser());
|
||||
|
||||
this.app.use(async (ctx, next) => {
|
||||
const start = Date.now();
|
||||
await next();
|
||||
const ms = Date.now() - start;
|
||||
console.log(`${ctx.method} ${ctx.url} - ${ctx.status} - ${ms}ms`);
|
||||
});
|
||||
}
|
||||
|
||||
setupRoutes() {
|
||||
this.app.use(async (ctx, next) => {
|
||||
if (ctx.path === '/') {
|
||||
ResponseUtil.success(ctx, { name: 'user-api', version: '1.0.0' });
|
||||
return;
|
||||
}
|
||||
await next();
|
||||
});
|
||||
|
||||
this.app.use(registerRoutes.getRoutes());
|
||||
this.app._router = registerRoutes.router;
|
||||
}
|
||||
|
||||
setupFallback() {
|
||||
this.app.use(async (ctx) => {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, msg: 'Not Found' };
|
||||
});
|
||||
}
|
||||
|
||||
start(port) {
|
||||
this.server = http.createServer(this.app.callback());
|
||||
this.server.listen(port, () => {
|
||||
console.log(`Server: running on http://localhost:${port}`);
|
||||
});
|
||||
}
|
||||
|
||||
stop() {
|
||||
if (this.server) {
|
||||
this.server.close();
|
||||
this.server = null;
|
||||
console.log('Server stopped');
|
||||
}
|
||||
}
|
||||
|
||||
static createKoaApp() {
|
||||
const instance = new APP();
|
||||
return instance.app;
|
||||
}
|
||||
}
|
||||
|
||||
export { APP };
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"port": 9010,
|
||||
"app": {
|
||||
"wxapp-escort": {
|
||||
"appid": "wxf73c79e16837af07",
|
||||
"secret": "5a061d65f4d35d19e62e83b98f6c63cf"
|
||||
},
|
||||
"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": {
|
||||
"str": "mongodb://huashengtec.com:6000",
|
||||
"host": "huashengtec.com",
|
||||
"db": "health",
|
||||
"option": {
|
||||
"user": "ehason",
|
||||
"pass": "Ehason_dbuser_2026",
|
||||
"dbName": "eiot_user",
|
||||
"authSource": "admin",
|
||||
"autoIndex": true,
|
||||
"socketTimeoutMS": 3000,
|
||||
"serverSelectionTimeoutMS": 30000
|
||||
},
|
||||
"debug": false
|
||||
}
|
||||
}
|
||||
+1344
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,6 @@
|
||||
import { APP } from './app.js'
|
||||
import config from './conf.json' with { type: 'json' };
|
||||
|
||||
// HTTP server
|
||||
const koaApp = new APP();
|
||||
koaApp.start(parseInt(process.env.PORT || config.port || "9010"));
|
||||
@@ -0,0 +1,156 @@
|
||||
import { DBModel } from '../models/index.js';
|
||||
import ResponseUtil from '../utils/api_response.js';
|
||||
import { hashToken } from '../utils/crypto.js';
|
||||
|
||||
/**
|
||||
* 从请求中提取 token(优先 Authorization header)
|
||||
*/
|
||||
function extractToken(ctx) {
|
||||
// 优先从 Authorization: Bearer xxx 获取
|
||||
const authHeader = ctx.header?.authorization;
|
||||
if (authHeader && authHeader.startsWith('Bearer ')) {
|
||||
return authHeader.slice(7);
|
||||
}
|
||||
|
||||
// 兼容旧方式:body/query/header 中的 token 字段
|
||||
return ctx.request.body?.token
|
||||
|| ctx.request.query?.token
|
||||
|| ctx.header?.token;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 token 查找用户
|
||||
* DB 中存储的是 token 的 sha256 哈希;兼容旧明文 token,命中后自动迁移为哈希
|
||||
* 多端会话:命中 security.tokens 中任意一条即可,同时兼容旧的单 token 字段
|
||||
*/
|
||||
async function findUserByToken(rawToken) {
|
||||
const hashed = await hashToken(rawToken);
|
||||
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 });
|
||||
if (user) {
|
||||
user.security.token = hashed;
|
||||
await user.save();
|
||||
}
|
||||
}
|
||||
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)
|
||||
* - appId / appIds: 允许访问的应用(任一即可),声明后必须存在有效成员关系
|
||||
* - roles: 允许的角色列表(必须与 appId / appIds 一起使用)
|
||||
*
|
||||
* 角色只在该应用内判定,不再遍历用户的所有应用;
|
||||
* 传 appIds 是为了同时支持小程序管理端与 Web 管理端。
|
||||
*/
|
||||
function auth(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);
|
||||
|
||||
if (!token) {
|
||||
if (!required) {
|
||||
ctx.state.user = null;
|
||||
return await next();
|
||||
}
|
||||
return ResponseUtil.unauthorized(ctx, '缺少认证 token');
|
||||
}
|
||||
|
||||
const user = await findUserByToken(token);
|
||||
if (!user) {
|
||||
return ResponseUtil.unauthorized(ctx, '用户未登录或 token 无效');
|
||||
}
|
||||
|
||||
// 按本次 token 命中的会话判断过期,不能只看 legacy tokenExpiry:
|
||||
// 多端会话下其它端新登录不会影响本端
|
||||
const expiry = resolveTokenExpiry(user, await hashToken(token));
|
||||
if (expiry && new Date() > expiry) {
|
||||
return ResponseUtil.unauthorized(ctx, '登录已过期,请重新登录');
|
||||
}
|
||||
|
||||
if (user.status.account === 'lock') {
|
||||
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;
|
||||
await next();
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回用户安全对象(去除密码、token 等敏感字段)
|
||||
* 注意:登录/注册响应中的 token 由 handler 单独附加
|
||||
*/
|
||||
function sanitizeUser(user) {
|
||||
const obj = user.toObject ? user.toObject() : { ...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 };
|
||||
@@ -0,0 +1,51 @@
|
||||
import ResponseUtil from '../utils/api_response.js';
|
||||
|
||||
/**
|
||||
* 内存速率限制
|
||||
* 基于 IP + 接口路径维度,不引入 Redis
|
||||
*/
|
||||
const rateLimitStore = new Map();
|
||||
|
||||
// 每 60 秒清理一次过期记录
|
||||
const cleanupTimer = setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const [key, record] of rateLimitStore.entries()) {
|
||||
if (now - record.resetAt > record.windowMs) {
|
||||
rateLimitStore.delete(key);
|
||||
}
|
||||
}
|
||||
}, 60_000);
|
||||
cleanupTimer.unref();
|
||||
|
||||
/**
|
||||
* 创建速率限制中间件
|
||||
* @param {number} max - 窗口内最大请求数
|
||||
* @param {number} windowMs - 窗口时长(毫秒),默认 60 秒
|
||||
*/
|
||||
function rateLimit(max = 10, windowMs = 60_000) {
|
||||
return async (ctx, next) => {
|
||||
const ip = ctx.ip || ctx.request.ip;
|
||||
const key = `${ip}:${ctx.path}`;
|
||||
const now = Date.now();
|
||||
|
||||
let record = rateLimitStore.get(key);
|
||||
if (!record || now - record.resetAt > windowMs) {
|
||||
record = { count: 0, resetAt: now, windowMs };
|
||||
rateLimitStore.set(key, record);
|
||||
}
|
||||
|
||||
record.count++;
|
||||
|
||||
if (record.count > max) {
|
||||
const retryAfter = Math.ceil((record.resetAt + windowMs - now) / 1000);
|
||||
ctx.set('Retry-After', retryAfter);
|
||||
return ResponseUtil.error(ctx, `请求过于频繁,请 ${retryAfter} 秒后重试`, null, 429);
|
||||
}
|
||||
|
||||
ctx.set('X-RateLimit-Limit', max);
|
||||
ctx.set('X-RateLimit-Remaining', Math.max(0, max - record.count));
|
||||
await next();
|
||||
};
|
||||
}
|
||||
|
||||
export { rateLimit };
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
'use strict';
|
||||
|
||||
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';
|
||||
|
||||
class MongoDBSchema {
|
||||
constructor() {
|
||||
this.dbConnection = null;
|
||||
this.User = null;
|
||||
this.UserApp = null;
|
||||
this.UserIdentity = null;
|
||||
}
|
||||
|
||||
init() {
|
||||
mongoose.set("debug", config.mongodb.debug);
|
||||
|
||||
this.dbConnection = mongoose.createConnection(config.mongodb.str, config.mongodb.option);
|
||||
this.dbConnection.on("error", () => {
|
||||
logger.error("...mongodb connect error ...");
|
||||
});
|
||||
this.dbConnection.on("connected", async () => {
|
||||
logger.info(`Mongodb: ${config.mongodb.host}/${config.mongodb.option.dbName} connected`);
|
||||
});
|
||||
this.dbConnection.on("disconnected", () =>
|
||||
logger.warn(`Mongodb: ${config.mongodb.host}/${config.mongodb.option.dbName} disconnected`)
|
||||
);
|
||||
this.dbConnection.on("reconnected", () =>
|
||||
logger.info(`Mongodb: ${config.mongodb.host}/${config.mongodb.option.dbName} reconnected`)
|
||||
);
|
||||
this.dbConnection.on("disconnecting", () =>
|
||||
logger.warn(`Mongodb: ${config.mongodb.host}/${config.mongodb.option.dbName} disconnecting`)
|
||||
);
|
||||
this.dbConnection.on("close", () =>
|
||||
logger.warn(`Mongodb: ${config.mongodb.host}/${config.mongodb.option.dbName} closed`)
|
||||
);
|
||||
|
||||
this.User = this.dbConnection.model('user', UserSchema)
|
||||
this.UserApp = this.dbConnection.model('user_app', UserAppSchema)
|
||||
this.UserIdentity = this.dbConnection.model('user_identity', UserIdentitySchema)
|
||||
}
|
||||
}
|
||||
|
||||
const DBModel = new MongoDBSchema()
|
||||
export { DBModel };
|
||||
|
||||
@@ -0,0 +1,287 @@
|
||||
"use strict";
|
||||
|
||||
import mongoose from "mongoose";
|
||||
|
||||
/**
|
||||
* 用户Schema定义
|
||||
*
|
||||
* 包含6个主要分类块:基本信息、安全信息、社交信息、状态信息、中医相关信息和元数据。
|
||||
* 支持多种登录方式和中医系统中的角色权限管理。
|
||||
*/
|
||||
const UserSchema = mongoose.Schema(
|
||||
{
|
||||
// 基本信息 - 用户的个人标识信息
|
||||
profile: {
|
||||
name: { type: String, comment: '用户姓名' },
|
||||
pinyin: { type: String, default: '', comment: '姓名的拼音,用于搜索' },
|
||||
pinyinFL: { type: String, default: '', comment: '姓名拼音的首字母,用于搜索' },
|
||||
// 手机号既用于登录,也是账号识别键:必须全局唯一,
|
||||
// 否则并发注册可能产生两个同号账号,登录结果不确定
|
||||
mobile: { type: String, index: true, unique: true, sparse: true, trim: true, comment: '手机号码' },
|
||||
email: { type: String, index: true, trim: true, unique: true, sparse: true, comment: '电子邮箱' },
|
||||
idnumber: { type: String, index: true, trim: true, unique: true, sparse: true, comment: '身份证号码' },
|
||||
ssn: { type: String, index: true, trim: true, unique: true, sparse: true, comment: '社保卡号' },
|
||||
sex: { type: String, enum: ["male", "female"], default: "male", comment: '性别' },
|
||||
birth: { type: Date, default: 0, comment: '出生日期' },
|
||||
},
|
||||
|
||||
// 安全信息 - 用户的登录凭证和安全相关数据
|
||||
security: {
|
||||
passwd: { type: String, comment: '密码(加密存储)' },
|
||||
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' },
|
||||
passwordResetToken: { type: String, sparse: true, comment: '密码重置令牌' },
|
||||
passwordResetExpiry: { type: Date, comment: '密码重置令牌过期时间' },
|
||||
},
|
||||
|
||||
// 位置信息 - 用户的省份、城市和区县
|
||||
location: {
|
||||
province: { type: String, default: '', comment: '省份' },
|
||||
city: { type: String, default: '', comment: '城市' },
|
||||
district: { type: String, default: '', comment: '区县' },
|
||||
},
|
||||
|
||||
// 地址信息 - 用户多个地址(用于邮寄等)
|
||||
addresses: [
|
||||
{
|
||||
label: { type: String, default: '', comment: '地址标签,如"家庭"、"公司"' },
|
||||
province: { type: String, default: '', comment: '省份' },
|
||||
city: { type: String, default: '', comment: '城市' },
|
||||
district: { type: String, default: '', comment: '区县' },
|
||||
address: { type: String, default: '', comment: '详细地址' },
|
||||
postcode: { type: String, default: '', comment: '邮政编码' },
|
||||
isDefault: { type: Boolean, default: false, comment: '是否默认地址' },
|
||||
},
|
||||
],
|
||||
|
||||
// 社交信息 - 用户的社交账号关联
|
||||
social: {
|
||||
wechat:{
|
||||
unionid: { type: String, index: true, unique: true, sparse: true, comment: '微信UnionID' },
|
||||
}
|
||||
},
|
||||
|
||||
// 状态信息 - 用户账户的状态标记
|
||||
status: {
|
||||
account: { type: String, enum: ["normal", "lock"], default: "normal", comment: '账户状态' },
|
||||
},
|
||||
|
||||
// 带wxopenid
|
||||
app: {
|
||||
type: mongoose.Schema.Types.Mixed,
|
||||
default: {}
|
||||
},
|
||||
|
||||
// 元数据 - 系统管理信息
|
||||
meta: {
|
||||
createtime: { type: Date, default: Date.now, comment: '创建时间' },
|
||||
updatetime: { type: Date, default: Date.now, comment: '更新时间' },
|
||||
},
|
||||
},
|
||||
{
|
||||
minimize: false, // 允许保存空对象
|
||||
strict: false, // 允许添加Schema中未定义的字段
|
||||
collection: "user", // MongoDB集合名称
|
||||
timestamps: false, // 不自动添加createdAt和updatedAt字段
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* 设置/更新用户信息
|
||||
*
|
||||
* @param {Object} _user - 要设置或更新的用户对象
|
||||
* @param {Function} cb - 可选的回调函数
|
||||
* @returns {Promise<Object|null>} 操作结果
|
||||
*/
|
||||
UserSchema.statics.setUser = async function (_user, cb) {
|
||||
const filter = {};
|
||||
let update = {};
|
||||
|
||||
// 如果有_id字段,说明是更新操作
|
||||
if (_user._id) {
|
||||
filter._id = _user._id;
|
||||
// 移除_id字段,避免尝试更新它
|
||||
delete _user._id;
|
||||
update = _user;
|
||||
update.meta.updatetime = Date.now();
|
||||
} else {
|
||||
// 新建用户
|
||||
update = _user;
|
||||
update.meta = {
|
||||
createtime: Date.now(),
|
||||
updatetime: Date.now()
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
if (filter._id) {
|
||||
// 更新用户
|
||||
return await this.findOneAndUpdate(filter, { $set: update }, { new: true, upsert: true }, cb);
|
||||
} else {
|
||||
// 创建新用户
|
||||
const newUser = new this(update);
|
||||
return await newUser.save(cb);
|
||||
}
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 根据用户信息更新用户文档
|
||||
*
|
||||
* @param {ObjectId} userId - 用户ID
|
||||
* @param {Object} userInfo - 包含要更新字段的用户信息对象
|
||||
* @returns {Promise<Object|null>} 更新后的用户对象或null
|
||||
*/
|
||||
UserSchema.statics.updateFromUserInfo = async function (userId, userInfo) {
|
||||
const updateData = {};
|
||||
|
||||
updateData['meta.updatetime'] = Date.now();
|
||||
|
||||
if (userInfo.profile) {
|
||||
if (userInfo.profile.name !== undefined) {
|
||||
updateData['profile.name'] = userInfo.profile.name;
|
||||
}
|
||||
if (userInfo.profile.sex !== undefined) {
|
||||
updateData['profile.sex'] = userInfo.profile.sex;
|
||||
}
|
||||
if (userInfo.profile.birth !== undefined) {
|
||||
updateData['profile.birth'] = userInfo.profile.birth ? new Date(userInfo.profile.birth) : null;
|
||||
}
|
||||
if (userInfo.profile.mobile !== undefined) {
|
||||
updateData['profile.mobile'] = userInfo.profile.mobile;
|
||||
}
|
||||
}
|
||||
|
||||
if (userInfo.location) {
|
||||
if (userInfo.location.province !== undefined) {
|
||||
updateData['location.province'] = userInfo.location.province;
|
||||
}
|
||||
if (userInfo.location.city !== undefined) {
|
||||
updateData['location.city'] = userInfo.location.city;
|
||||
}
|
||||
if (userInfo.location.district !== undefined) {
|
||||
updateData['location.district'] = userInfo.location.district;
|
||||
}
|
||||
}
|
||||
|
||||
if (userInfo.addresses) {
|
||||
updateData['addresses'] = userInfo.addresses;
|
||||
}
|
||||
|
||||
// 保留原有异常:唯一索引冲突(手机号撞号)需要由 handler 给出明确提示
|
||||
return await this.findOneAndUpdate(
|
||||
{ _id: userId },
|
||||
{ $set: updateData },
|
||||
{ new: true, upsert: false, runValidators: true }
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* 删除用户
|
||||
*
|
||||
* @param {ObjectId} _id - 用户ID
|
||||
* @param {string} mobile - 手机号码
|
||||
* @param {string} email - 电子邮箱
|
||||
* @param {string} wxunionid - 微信unionid
|
||||
* @param {Function} cb - 可选的回调函数
|
||||
* @returns {Promise<Object|null>} 操作结果
|
||||
*/
|
||||
UserSchema.statics.delUser = async function (_id, mobile, email, wxunionid, cb) {
|
||||
const filter = {};
|
||||
|
||||
if (_id) {
|
||||
filter._id = _id;
|
||||
} else if (mobile) {
|
||||
filter['profile.mobile'] = mobile;
|
||||
} else if (email) {
|
||||
filter['profile.email'] = email;
|
||||
} else if (wxunionid) {
|
||||
filter['social.wechat.unionid'] = wxunionid;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
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;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 增加失败登录尝试次数
|
||||
*
|
||||
* @param {ObjectId} _id - 用户ID
|
||||
* @returns {Promise<Object|null>} 操作结果
|
||||
*/
|
||||
UserSchema.statics.incrementFailedLoginAttempts = async function (_id) {
|
||||
try {
|
||||
return await this.findOneAndUpdate(
|
||||
{ _id },
|
||||
{
|
||||
$inc: { 'security.failedLoginAttempts': 1 },
|
||||
'meta.updatetime': Date.now()
|
||||
},
|
||||
{ new: true }
|
||||
);
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 重置失败登录尝试次数
|
||||
*
|
||||
* @param {ObjectId} _id - 用户ID
|
||||
* @returns {Promise<Object|null>} 操作结果
|
||||
*/
|
||||
UserSchema.statics.resetFailedLoginAttempts = async function (_id) {
|
||||
try {
|
||||
return await this.findOneAndUpdate(
|
||||
{ _id },
|
||||
{
|
||||
'security.failedLoginAttempts': 0,
|
||||
'meta.updatetime': Date.now()
|
||||
},
|
||||
{ new: true }
|
||||
);
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
// 索引设置 - 优化查询性能
|
||||
|
||||
// 手机号和密码复合索引,用于登录验证
|
||||
UserSchema.index({ "profile.mobile": 1, "security.passwd": 1 });
|
||||
|
||||
export { UserSchema };
|
||||
@@ -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;
|
||||
}
|
||||
Generated
+1606
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"name": "api_user",
|
||||
"version": "1.0.0",
|
||||
"description": "user api service",
|
||||
"type": "module",
|
||||
"main": "app.js",
|
||||
"scripts": {
|
||||
"start": "node index.js",
|
||||
"test": "node --test test/*.test.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@koa/cors": "^5.0.0",
|
||||
"bcrypt": "^6.0.0",
|
||||
"joi": "^18.2.1",
|
||||
"koa": "^2.15.3",
|
||||
"koa-bodyparser": "^4.4.1",
|
||||
"koa-router": "^12.0.1",
|
||||
"mongoose": "^8.4.0",
|
||||
"node-fetch": "^3.3.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"supertest": "^7.0.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
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() {
|
||||
this.router = new Router();
|
||||
this.handler = new HandlerUser();
|
||||
this.setupRoutes();
|
||||
}
|
||||
|
||||
setupRoutes() {
|
||||
const userRouter = new Router({ prefix: '/user' });
|
||||
|
||||
// 限流:注册/登录接口 5次/分钟,微信登录 10次/分钟
|
||||
userRouter.post('/register', rateLimit(5, 60_000), this.handler.register.bind(this.handler));
|
||||
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));
|
||||
// 管理端接口统一在路由层声明应用与角色,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());
|
||||
|
||||
this.printRoutes(this.router.stack);
|
||||
}
|
||||
|
||||
getRoutes() {
|
||||
return this.router.routes();
|
||||
}
|
||||
|
||||
printRoutes(stack) {
|
||||
for (const layer of stack) {
|
||||
if (layer.path) {
|
||||
const methods = layer.methods.filter(m => m !== '_all');
|
||||
methods.forEach(m => console.log(` [${m.toUpperCase()}] ${layer.path}`));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default new ApiRouter();
|
||||
@@ -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;
|
||||
});
|
||||
@@ -0,0 +1,347 @@
|
||||
import { describe, it, before, after } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import supertest from 'supertest';
|
||||
import { APP } from '../app.js';
|
||||
import { DBModel } from '../models/index.js';
|
||||
|
||||
describe('用户接口集成测试', () => {
|
||||
let app, agent;
|
||||
const testMobile = '13900000001';
|
||||
const testPasswd = 'test123456';
|
||||
let token = '';
|
||||
let userId = '';
|
||||
|
||||
before(async () => {
|
||||
app = new APP();
|
||||
agent = supertest(app.app.callback());
|
||||
// 等待数据库连接
|
||||
await new Promise(resolve => setTimeout(resolve, 2000));
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
// 清理测试数据
|
||||
if (userId) {
|
||||
await DBModel.User.delUser(userId);
|
||||
}
|
||||
app.stop();
|
||||
// 关闭数据库连接,否则 node --test 进程不会退出
|
||||
if (DBModel.dbConnection) {
|
||||
await DBModel.dbConnection.close();
|
||||
}
|
||||
});
|
||||
|
||||
describe('POST /user/register', () => {
|
||||
it('应成功注册新用户', async () => {
|
||||
const res = await agent
|
||||
.post('/user/register')
|
||||
.send({
|
||||
userInfo: {
|
||||
profile: { mobile: testMobile, name: '测试用户' },
|
||||
security: { passwd: testPasswd },
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(res.body.code, 0, `注册失败: ${res.body.msg}`);
|
||||
assert.ok(res.body.data.user);
|
||||
assert.ok(res.body.data.user.security.token);
|
||||
assert.equal(res.body.data.user.profile.mobile, testMobile);
|
||||
// 密码字段不应返回
|
||||
assert.equal(res.body.data.user.security.passwd, undefined);
|
||||
assert.equal(res.body.data.user.security.passwdSalt, undefined);
|
||||
|
||||
token = res.body.data.user.security.token;
|
||||
userId = res.body.data.user._id;
|
||||
});
|
||||
|
||||
it('重复注册应返回 409', async () => {
|
||||
const res = await agent
|
||||
.post('/user/register')
|
||||
.send({
|
||||
userInfo: {
|
||||
profile: { mobile: testMobile, name: '测试用户' },
|
||||
security: { passwd: testPasswd },
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(res.body.code, 409);
|
||||
assert.equal(res.body.msg, '手机号已注册');
|
||||
});
|
||||
|
||||
it('缺少手机号应返回 400', async () => {
|
||||
const res = await agent
|
||||
.post('/user/register')
|
||||
.send({
|
||||
userInfo: {
|
||||
profile: { name: '测试用户' },
|
||||
security: { passwd: testPasswd },
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(res.body.code, 400);
|
||||
});
|
||||
|
||||
it('缺少密码应返回 400', async () => {
|
||||
const res = await agent
|
||||
.post('/user/register')
|
||||
.send({
|
||||
userInfo: {
|
||||
profile: { mobile: '13900000099' },
|
||||
security: {},
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(res.body.code, 400);
|
||||
});
|
||||
|
||||
it('密码少于6位应返回 400', async () => {
|
||||
const res = await agent
|
||||
.post('/user/register')
|
||||
.send({
|
||||
userInfo: {
|
||||
profile: { mobile: '13900000098' },
|
||||
security: { passwd: '123' },
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(res.body.code, 400);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /user/signin', () => {
|
||||
it('用正确密码登录应成功', async () => {
|
||||
const res = await agent
|
||||
.post('/user/signin')
|
||||
.send({ mobile: testMobile, passwd: testPasswd });
|
||||
|
||||
assert.equal(res.body.code, 0, `登录失败: ${res.body.msg}`);
|
||||
assert.ok(res.body.data.user.security.token);
|
||||
// 更新 token
|
||||
token = res.body.data.user.security.token;
|
||||
// 应记录最后登录信息
|
||||
assert.ok(res.body.data.user.security.lastLoginAt);
|
||||
});
|
||||
|
||||
it('错误密码应返回 401', async () => {
|
||||
const res = await agent
|
||||
.post('/user/signin')
|
||||
.send({ mobile: testMobile, passwd: 'wrongpassword' });
|
||||
|
||||
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')
|
||||
.send({ mobile: '13999999999', passwd: 'test123456' });
|
||||
|
||||
assert.equal(res.body.code, 401);
|
||||
});
|
||||
|
||||
it('缺少手机号应返回 400', async () => {
|
||||
const res = await agent
|
||||
.post('/user/signin')
|
||||
.send({ passwd: testPasswd });
|
||||
|
||||
assert.equal(res.body.code, 400);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /user/userInfo', () => {
|
||||
it('用 Authorization Bearer 获取用户信息', async () => {
|
||||
const res = await agent
|
||||
.post('/user/userInfo')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({});
|
||||
|
||||
assert.equal(res.body.code, 0, `获取用户信息失败: ${res.body.msg}`);
|
||||
assert.equal(res.body.data.user.profile.mobile, testMobile);
|
||||
assert.equal(res.body.data.user.security.passwd, undefined);
|
||||
});
|
||||
|
||||
it('用 body token 获取用户信息(向后兼容)', async () => {
|
||||
const res = await agent
|
||||
.post('/user/userInfo')
|
||||
.send({ token });
|
||||
|
||||
assert.equal(res.body.code, 0);
|
||||
assert.equal(res.body.data.user.profile.mobile, testMobile);
|
||||
});
|
||||
|
||||
it('无效 token 应返回 401', async () => {
|
||||
const res = await agent
|
||||
.post('/user/userInfo')
|
||||
.set('Authorization', 'Bearer invalid_token')
|
||||
.send({});
|
||||
|
||||
assert.equal(res.body.code, 401);
|
||||
});
|
||||
|
||||
it('缺少 token 应返回 400', async () => {
|
||||
const res = await agent
|
||||
.post('/user/userInfo')
|
||||
.send({});
|
||||
|
||||
assert.equal(res.body.code, 400);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /user/update', () => {
|
||||
it('更新用户信息应成功', async () => {
|
||||
const res = await agent
|
||||
.post('/user/update')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({
|
||||
profile: { name: '更新后的名字' },
|
||||
});
|
||||
|
||||
assert.equal(res.body.code, 0, `更新失败: ${res.body.msg}`);
|
||||
assert.equal(res.body.data.user.profile.name, '更新后的名字');
|
||||
});
|
||||
|
||||
it('无 token 更新应返回 401', async () => {
|
||||
const res = await agent
|
||||
.post('/user/update')
|
||||
.send({ profile: { name: 'test' } });
|
||||
|
||||
assert.equal(res.body.code, 401);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /user/signout', () => {
|
||||
it('退出登录应成功', async () => {
|
||||
const res = await agent
|
||||
.post('/user/signout')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({});
|
||||
|
||||
assert.equal(res.body.code, 0);
|
||||
assert.equal(res.body.msg, '退出登录成功');
|
||||
});
|
||||
|
||||
it('退出后用旧 token 获取信息应返回 401', async () => {
|
||||
const res = await agent
|
||||
.post('/user/userInfo')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({});
|
||||
|
||||
assert.equal(res.body.code, 401);
|
||||
});
|
||||
});
|
||||
|
||||
describe('密码迁移:MD5 → bcrypt', () => {
|
||||
it('旧 MD5 用户登录应自动升级密码', async () => {
|
||||
// 先注册一个新用户
|
||||
const mobile = '13900000002';
|
||||
const passwd = 'md5test123';
|
||||
|
||||
// 直接写入一个 MD5 密码的用户
|
||||
const crypto = await import('crypto');
|
||||
const salt = crypto.randomBytes(8).toString('hex');
|
||||
const md5Hash = crypto.createHash('md5').update(passwd + salt).digest('hex');
|
||||
|
||||
const newUser = {
|
||||
profile: { mobile, name: 'MD5测试用户' },
|
||||
security: { passwd: md5Hash, passwdSalt: salt },
|
||||
status: { account: 'normal' },
|
||||
app: {},
|
||||
social: { wechat: {} },
|
||||
};
|
||||
|
||||
const user = await DBModel.User.setUser(newUser);
|
||||
assert.ok(user);
|
||||
|
||||
// 用旧密码登录
|
||||
const res = await agent
|
||||
.post('/user/signin')
|
||||
.send({ mobile, passwd });
|
||||
|
||||
assert.equal(res.body.code, 0, `MD5迁移登录失败: ${res.body.msg}`);
|
||||
|
||||
// 验证密码已升级为 bcrypt
|
||||
const updatedUser = await DBModel.User.findOne({ 'profile.mobile': mobile });
|
||||
assert.ok(updatedUser.security.passwd.startsWith('$2'), '密码应已升级为 bcrypt');
|
||||
assert.equal(updatedUser.security.passwdSalt, undefined, 'salt 应已清除');
|
||||
|
||||
// 清理
|
||||
await DBModel.User.delUser(updatedUser._id);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { extractToken, sanitizeUser } from '../middleware/auth.js';
|
||||
|
||||
// 模拟 ctx 对象
|
||||
function mockCtx(overrides = {}) {
|
||||
return {
|
||||
header: {},
|
||||
request: { body: {}, query: {} },
|
||||
ip: '127.0.0.1',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('extractToken', () => {
|
||||
it('优先从 Authorization Bearer header 提取', () => {
|
||||
const ctx = mockCtx({
|
||||
header: { authorization: 'Bearer abc123' },
|
||||
request: { body: { token: 'body_token' } },
|
||||
});
|
||||
assert.equal(extractToken(ctx), 'abc123');
|
||||
});
|
||||
|
||||
it('无 Bearer header 时从 body 提取', () => {
|
||||
const ctx = mockCtx({
|
||||
request: { body: { token: 'body_token' } },
|
||||
});
|
||||
assert.equal(extractToken(ctx), 'body_token');
|
||||
});
|
||||
|
||||
it('无 Bearer header 时从 query 提取', () => {
|
||||
const ctx = mockCtx({
|
||||
request: { query: { token: 'query_token' } },
|
||||
});
|
||||
assert.equal(extractToken(ctx), 'query_token');
|
||||
});
|
||||
|
||||
it('无 Bearer header 时从 header token 字段提取', () => {
|
||||
const ctx = mockCtx({
|
||||
header: { token: 'header_token' },
|
||||
});
|
||||
assert.equal(extractToken(ctx), 'header_token');
|
||||
});
|
||||
|
||||
it('无任何 token 时返回 undefined', () => {
|
||||
const ctx = mockCtx();
|
||||
assert.equal(extractToken(ctx), undefined);
|
||||
});
|
||||
});
|
||||
|
||||
describe('sanitizeUser', () => {
|
||||
it('应删除密码和重置令牌相关字段', () => {
|
||||
const user = {
|
||||
toObject: () => ({
|
||||
profile: { mobile: '13800138000' },
|
||||
security: {
|
||||
passwd: 'hashed',
|
||||
passwdSalt: 'salt',
|
||||
token: 'valid_token',
|
||||
passwordResetToken: 'reset_token',
|
||||
passwordResetExpiry: new Date(),
|
||||
},
|
||||
}),
|
||||
};
|
||||
|
||||
const safe = sanitizeUser(user);
|
||||
assert.equal(safe.security.passwd, undefined);
|
||||
assert.equal(safe.security.passwdSalt, undefined);
|
||||
assert.equal(safe.security.passwordResetToken, undefined);
|
||||
assert.equal(safe.security.passwordResetExpiry, undefined);
|
||||
assert.equal(safe.security.token, undefined);
|
||||
assert.equal(safe.profile.mobile, '13800138000');
|
||||
});
|
||||
|
||||
it('处理普通对象(无 toObject 方法)', () => {
|
||||
const user = {
|
||||
profile: { mobile: '13800138000' },
|
||||
security: { passwd: 'x', passwdSalt: 'y' },
|
||||
};
|
||||
|
||||
const safe = sanitizeUser(user);
|
||||
assert.equal(safe.security.passwd, undefined);
|
||||
assert.equal(safe.security.passwdSalt, undefined);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, it, before, after } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { hashPassword, verifyPassword } from '../utils/crypto.js';
|
||||
|
||||
describe('crypto 工具', () => {
|
||||
it('bcrypt 加密后验证应通过', async () => {
|
||||
const passwd = 'test123456';
|
||||
const hash = await hashPassword(passwd);
|
||||
assert.ok(hash.startsWith('$2'), 'bcrypt hash 应以 $2 开头');
|
||||
|
||||
const { valid, needsUpgrade } = await verifyPassword(passwd, hash, '');
|
||||
assert.equal(valid, true);
|
||||
assert.equal(needsUpgrade, false);
|
||||
});
|
||||
|
||||
it('错误密码验证应失败', async () => {
|
||||
const hash = await hashPassword('correct');
|
||||
const { valid } = await verifyPassword('wrong', hash, '');
|
||||
assert.equal(valid, false);
|
||||
});
|
||||
|
||||
it('兼容旧 MD5 密码验证', async () => {
|
||||
const passwd = 'mypass';
|
||||
const salt = 'abc123';
|
||||
const crypto = await import('crypto');
|
||||
const md5Hash = crypto.createHash('md5').update(passwd + salt).digest('hex');
|
||||
|
||||
const { valid, needsUpgrade } = await verifyPassword(passwd, md5Hash, salt);
|
||||
assert.equal(valid, true);
|
||||
assert.equal(needsUpgrade, true, 'MD5 密码应标记为需要升级');
|
||||
});
|
||||
|
||||
it('MD5 密码错误时应返回 false', async () => {
|
||||
const salt = 'abc123';
|
||||
const crypto = await import('crypto');
|
||||
const md5Hash = crypto.createHash('md5').update('correct' + salt).digest('hex');
|
||||
|
||||
const { valid } = await verifyPassword('wrong', md5Hash, salt);
|
||||
assert.equal(valid, false);
|
||||
});
|
||||
|
||||
it('空 salt 时 MD5 也能验证', async () => {
|
||||
const passwd = 'test';
|
||||
const crypto = await import('crypto');
|
||||
const md5Hash = crypto.createHash('md5').update(passwd + '').digest('hex');
|
||||
|
||||
const { valid, needsUpgrade } = await verifyPassword(passwd, md5Hash, '');
|
||||
assert.equal(valid, true);
|
||||
assert.equal(needsUpgrade, true);
|
||||
});
|
||||
});
|
||||
@@ -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, /已在本应用注册/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, it, before, after, beforeEach } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import Koa from 'koa';
|
||||
import bodyParser from 'koa-bodyparser';
|
||||
import supertest from 'supertest';
|
||||
import { rateLimit } from '../middleware/ratelimit.js';
|
||||
|
||||
describe('rateLimit 中间件', () => {
|
||||
let app, agent;
|
||||
|
||||
before(() => {
|
||||
app = new Koa();
|
||||
app.use(bodyParser());
|
||||
app.use(rateLimit(3, 60_000));
|
||||
app.use(async (ctx) => {
|
||||
ctx.body = { ok: true };
|
||||
});
|
||||
agent = supertest(app.callback());
|
||||
});
|
||||
|
||||
it('前3次请求应正常通过', async () => {
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const res = await agent.post('/test').send({});
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.body.ok, true);
|
||||
}
|
||||
});
|
||||
|
||||
it('第4次请求应被限流', async () => {
|
||||
const res = await agent.post('/test').send({});
|
||||
assert.equal(res.status, 200); // HTTP 200,业务码 429
|
||||
assert.equal(res.body.code, 429);
|
||||
assert.ok(res.body.msg.includes('请求过于频繁'));
|
||||
assert.ok(res.headers['retry-after']);
|
||||
});
|
||||
|
||||
it('限流响应头应包含 X-RateLimit 信息', async () => {
|
||||
// 新建一个不受之前计数影响的中间件(不同限流阈值 + 不同路径)
|
||||
const freshApp = new Koa();
|
||||
freshApp.use(bodyParser());
|
||||
freshApp.use(rateLimit(100, 60_000));
|
||||
freshApp.use(async (ctx) => { ctx.body = { ok: true }; });
|
||||
const freshAgent = supertest(freshApp.callback());
|
||||
|
||||
const res = await freshAgent.post('/headercheck').send({});
|
||||
assert.equal(res.headers['x-ratelimit-limit'], '100');
|
||||
assert.equal(res.headers['x-ratelimit-remaining'], '99');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
import logger from "./logger.js";
|
||||
|
||||
/**
|
||||
* 响应工具类
|
||||
* 提供统一的响应格式
|
||||
*
|
||||
* 约定:业务状态一律走 body.code,HTTP 状态码固定 200;
|
||||
* 同时把 code 写进 X-Biz-Code 响应头,便于网关/监控按业务码告警。
|
||||
*/
|
||||
class ResponseUtil {
|
||||
/**
|
||||
* 成功响应
|
||||
* @param {Object} ctx - Koa上下文对象
|
||||
* @param {Object} data - 响应数据
|
||||
* @param {string} message - 响应消息
|
||||
*/
|
||||
static success(ctx, data, message = '操作成功') {
|
||||
ctx.status = 200;
|
||||
ctx.set('X-Biz-Code', '0');
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
msg: message,
|
||||
data,
|
||||
ts: Date.now()
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 错误响应
|
||||
* @param {Object} ctx - Koa上下文对象
|
||||
* @param {string} message - 错误消息
|
||||
* @param {number} errorCode - 应用错误码
|
||||
*/
|
||||
static error(ctx, message, data = null, errorCode = 500) {
|
||||
// 根据规则,只要进入controller,http状态码都是200
|
||||
ctx.status = 200;
|
||||
ctx.set('X-Biz-Code', String(errorCode));
|
||||
ctx.body = {
|
||||
code: errorCode,
|
||||
msg: message,
|
||||
data,
|
||||
ts: Date.now()
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求参数错误响应
|
||||
* @param {Object} ctx - Koa上下文对象
|
||||
* @param {string} message - 错误消息
|
||||
*/
|
||||
static badRequest(ctx, message = '请求参数错误', data = null) {
|
||||
return ResponseUtil.error(ctx, message, data, 400);
|
||||
}
|
||||
|
||||
/**
|
||||
* 未授权响应
|
||||
* @param {Object} ctx - Koa上下文对象
|
||||
* @param {string} message - 错误消息
|
||||
*/
|
||||
static unauthorized(ctx, message = '未授权', data = null) {
|
||||
return ResponseUtil.error(ctx, message, data, 401);
|
||||
}
|
||||
|
||||
/**
|
||||
* 禁止访问响应
|
||||
* @param {Object} ctx - Koa上下文对象
|
||||
* @param {string} message - 错误消息
|
||||
*/
|
||||
static forbidden(ctx, message = '禁止访问', data = null) {
|
||||
return ResponseUtil.error(ctx, message, data, 403);
|
||||
}
|
||||
|
||||
/**
|
||||
* 资源不存在响应
|
||||
* @param {Object} ctx - Koa上下文对象
|
||||
* @param {string} message - 错误消息
|
||||
*/
|
||||
static notFound(ctx, message = '资源不存在', data = null) {
|
||||
return ResponseUtil.error(ctx, message, data, 404);
|
||||
}
|
||||
|
||||
/**
|
||||
* 服务器内部错误响应
|
||||
*
|
||||
* 详细原因只进日志:err.message 可能含 Mongo 连接串、字段名等内部信息,
|
||||
* 直接回传等于把服务端实现细节暴露给前端。
|
||||
*
|
||||
* @param {Object} ctx - Koa上下文对象
|
||||
* @param {string|Error} detail - 内部错误详情(仅用于日志)
|
||||
* @param {Object} data - 附加数据
|
||||
*/
|
||||
static internalError(ctx, detail = null, data = null) {
|
||||
if (detail) {
|
||||
const text = detail instanceof Error ? detail.stack : String(detail);
|
||||
logger.error(`[internal] ${ctx.method} ${ctx.path}: ${text}`);
|
||||
}
|
||||
return ResponseUtil.error(ctx, '服务器繁忙,请稍后重试', data, 500);
|
||||
}
|
||||
}
|
||||
|
||||
export default ResponseUtil;
|
||||
@@ -0,0 +1,44 @@
|
||||
import bcrypt from 'bcrypt';
|
||||
|
||||
const SALT_ROUNDS = 10;
|
||||
|
||||
/**
|
||||
* 加密密码(bcrypt)
|
||||
*/
|
||||
async function hashPassword(passwd) {
|
||||
return await bcrypt.hash(passwd, SALT_ROUNDS);
|
||||
}
|
||||
|
||||
/**
|
||||
* 对 token 做哈希(用于 DB 存储,避免明文落库)
|
||||
*/
|
||||
async function hashToken(token) {
|
||||
const crypto = await import('crypto');
|
||||
return crypto.createHash('sha256').update(token).digest('hex');
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证密码
|
||||
* 支持 bcrypt 新密码和 MD5 旧密码(渐进式迁移)
|
||||
* @returns {{ valid: boolean, needsUpgrade: boolean }}
|
||||
*/
|
||||
async function verifyPassword(passwd, storedHash, salt) {
|
||||
// 尝试 bcrypt 验证
|
||||
if (storedHash && storedHash.startsWith('$2')) {
|
||||
const valid = await bcrypt.compare(passwd, storedHash);
|
||||
return { valid, needsUpgrade: false };
|
||||
}
|
||||
|
||||
// 兼容旧 MD5 密码
|
||||
const crypto = await import('crypto');
|
||||
const hash = crypto.createHash('md5');
|
||||
hash.update(passwd + (salt || ''));
|
||||
const md5Hash = hash.digest('hex');
|
||||
|
||||
return {
|
||||
valid: storedHash === md5Hash,
|
||||
needsUpgrade: storedHash === md5Hash
|
||||
};
|
||||
}
|
||||
|
||||
export { hashPassword, verifyPassword, hashToken };
|
||||
@@ -0,0 +1,48 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
const logDir = path.join(process.cwd(), 'logs');
|
||||
if (!fs.existsSync(logDir)) {
|
||||
fs.mkdirSync(logDir, { recursive: true });
|
||||
}
|
||||
|
||||
const LEVELS = {
|
||||
ERROR: 'ERROR',
|
||||
WARN: 'WARN',
|
||||
INFO: 'INFO',
|
||||
DEBUG: 'DEBUG'
|
||||
};
|
||||
|
||||
const getCurrentTimestamp = () => {
|
||||
return new Date().toISOString();
|
||||
};
|
||||
|
||||
const writeLog = (level, message, meta = {}) => {
|
||||
const timestamp = getCurrentTimestamp();
|
||||
const logEntry = {
|
||||
timestamp,
|
||||
level,
|
||||
message,
|
||||
meta
|
||||
};
|
||||
|
||||
console.log(`[${timestamp}] ${level}: ${message}`, meta);
|
||||
|
||||
const logFileName = `${new Date().toISOString().slice(0, 10)}.log`;
|
||||
const logFilePath = path.join(logDir, logFileName);
|
||||
|
||||
fs.appendFile(logFilePath, JSON.stringify(logEntry) + '\n', (err) => {
|
||||
if (err) {
|
||||
console.error('Failed to write log to file:', err);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const logger = {
|
||||
error: (message, meta) => writeLog(LEVELS.ERROR, message, meta),
|
||||
warn: (message, meta) => writeLog(LEVELS.WARN, message, meta),
|
||||
info: (message, meta) => writeLog(LEVELS.INFO, message, meta),
|
||||
debug: (message, meta) => writeLog(LEVELS.DEBUG, message, meta)
|
||||
};
|
||||
|
||||
export default logger;
|
||||
Reference in New Issue
Block a user