diff --git a/.gitignore b/.gitignore index 0f67650..c86acff 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ /node_modules/ /logs/ +/backup/ .env diff --git a/app.js b/app.js index f8bdb63..f5884b2 100644 --- a/app.js +++ b/app.js @@ -3,11 +3,14 @@ import bodyParser from 'koa-bodyparser'; import cors from '@koa/cors'; import http from 'http'; import { DBModel } from './models/index.js'; +import { assertRegistryCoverage } from './models/app_registry.js'; import registerRoutes from './routes/index.js'; import ResponseUtil from './utils/api_response.js'; class APP { constructor() { + // 配置缺失在启动阶段暴露,而不是等某个应用首次登录才报错 + assertRegistryCoverage(); this.app = new Koa(); this.setupDB(); this.setupMiddleware(); diff --git a/conf.json b/conf.json index ea1b94f..ae42140 100644 --- a/conf.json +++ b/conf.json @@ -8,6 +8,12 @@ "wxapp-escort-admin": { "appid": "wxf94dd97b91af09a2", "secret": "79ba226684740830af0029763d3045f0" + }, + "web-escort-admin": { + "appid": "", + "secret": "", + "callbackUri": "http://localhost:9010/user/wechat/qr/callback", + "webOrigin": "http://localhost:5173" } }, "mongodb": { diff --git a/handler/users.js b/handler/users.js index 39d6c02..c437229 100644 --- a/handler/users.js +++ b/handler/users.js @@ -1,8 +1,23 @@ import Joi from 'joi'; +import mongoose from 'mongoose'; import { DBModel } from "../models/index.js"; import ResponseUtil from "../utils/api_response.js"; import { hashPassword, verifyPassword, hashToken } from "../utils/crypto.js"; -import { sanitizeUser, isAdmin } from "../middleware/auth.js"; +import { sanitizeUser } from "../middleware/auth.js"; +import { APP_REGISTRY, GRANTABLE_ROLES } from "../models/app_registry.js"; +import { + hasConfigSchema, + validateAppConfig, + resolveConfig, + flattenLeaves, +} from "../models/app_config.js"; +import { + backfillOneFromLegacy, + upsertIdentity, + upsertLoginMembership, + grantRoles, + revokeRoles, +} from "../models/user_membership.js"; import config from "../conf.json" with { type: "json" }; // 微信 access_token 进程内缓存(有效期 7200s,提前 5 分钟刷新) @@ -11,6 +26,49 @@ const wxAccessTokenCache = new Map(); // 微信接口超时:微信侧偶发慢响应,不设超时会让请求一直挂起并占用连接 const WX_REQUEST_TIMEOUT = 8000; +// 手机号格式与字段长度上限:格式统一账号体系,长度防止超大字段写满 16MB 文档 +const MOBILE_PATTERN = /^1[3-9]\d{9}$/; +const NAME_MAX = 50; + +// ==================== 微信扫码登录(开放平台网站应用) ==================== + +// Web 后台的 appId 与扫码登录 provider,与小程序端完全隔离 +const WEB_ADMIN_APP = "web-escort-admin"; +const WECHAT_WEB_PROVIDER = "weixin-web"; +const QR_STATE_TTL = 5 * 60 * 1000; +const QR_TICKET_TTL = 60 * 1000; +const QR_STORE_LIMIT = 2000; + +// state / ticket 都是一次性短生命周期数据,放进程内即可。 +// 多实例部署时需换 Redis,否则回调可能落到没有对应 state 的实例 +const qrStateStore = new Map(); +const qrTicketStore = new Map(); + +function pruneStore(store, now) { + for (const [key, value] of store) { + if (value.expiresAt <= now) store.delete(key); + } + // 上限保护:异常刷接口时按插入顺序淘汰最早的 + while (store.size > QR_STORE_LIMIT) { + store.delete(store.keys().next().value); + } +} + +function wechatWebConfig() { + // 与小程序共用 config.app:appid/secret 走同一处配置,扫码专用参数挂在同一条目下 + const cfg = config.app?.[WEB_ADMIN_APP] || {}; + return { + appid: String(cfg.appid || "").trim(), + secret: String(cfg.secret || "").trim(), + callbackUri: String(cfg.callbackUri || "").trim(), + webOrigin: String(cfg.webOrigin || "").trim().replace(/\/+$/, ""), + }; +} + +function isWechatWebReady(cfg) { + return !!(cfg.appid && cfg.secret && cfg.callbackUri && cfg.webOrigin); +} + async function getWxAccessToken(appConfig) { const cached = wxAccessTokenCache.get(appConfig.appid); if (cached && Date.now() < cached.expiresAt) { @@ -33,16 +91,20 @@ async function getWxAccessToken(appConfig) { const registerSchema = Joi.object({ userInfo: Joi.object({ profile: Joi.object({ - mobile: Joi.string().required().messages({ + mobile: Joi.string().pattern(MOBILE_PATTERN).required().messages({ 'any.required': '缺少手机号', - 'string.empty': '手机号不能为空' + 'string.empty': '手机号不能为空', + 'string.pattern.base': '手机号格式不正确', + }), + name: Joi.string().allow('').max(NAME_MAX).messages({ + 'string.max': `姓名不能超过 ${NAME_MAX} 个字符`, }), - name: Joi.string().allow(''), }).required(), security: Joi.object({ - passwd: Joi.string().min(6).required().messages({ + passwd: Joi.string().min(6).max(72).required().messages({ 'any.required': '缺少密码', - 'string.min': '密码至少6位' + 'string.min': '密码至少6位', + 'string.max': '密码过长', }), }).required(), location: Joi.object({ @@ -68,22 +130,119 @@ const signinSchema = Joi.object({ }); const wxSigninSchema = Joi.object({ - code: Joi.string().required().messages({ 'any.required': '缺少微信登录凭证 code' }), + code: Joi.string().max(128).required().messages({ 'any.required': '缺少微信登录凭证 code' }), appId: Joi.string().required().messages({ 'any.required': '缺少 appId' }), // 推荐:传微信手机号凭证 code,由服务端换取手机号(可信) - phoneCode: Joi.string().allow('', null), + phoneCode: Joi.string().max(128).allow('', null), // 已废弃(不安全):客户端直传手机号,仅允许用于新建账号 - phoneNumber: Joi.string().allow('', null), - name: Joi.string().allow('', null), + phoneNumber: Joi.string().pattern(MOBILE_PATTERN).allow('', null).messages({ + 'string.pattern.base': '手机号格式不正确', + }), + name: Joi.string().max(NAME_MAX).allow('', null), }); const wxGetPhoneSchema = Joi.object({ - code: Joi.string().required().messages({ 'any.required': '缺少手机号凭证 code' }), + code: Joi.string().max(128).required().messages({ 'any.required': '缺少手机号凭证 code' }), appId: Joi.string().required().messages({ 'any.required': '缺少 appId' }), }); +const appConfigSchema = Joi.object({ + appId: Joi.string().required().messages({ 'any.required': '缺少 appId' }), + config: Joi.object().required().messages({ 'any.required': '缺少 config' }), +}); + +const grantSchema = Joi.object({ + userId: Joi.string().hex().length(24).required().messages({ + 'any.required': '缺少用户ID', + 'string.hex': '用户ID不合法', + 'string.length': '用户ID不合法', + }), + appId: Joi.string().required().messages({ 'any.required': '缺少 appId' }), + action: Joi.string().valid('grant', 'revoke').required().messages({ + 'any.required': '缺少 action', + 'any.only': 'action 只能是 grant 或 revoke', + }), + roles: Joi.array().items(Joi.string()).default(['admin']), +}); + const LOCK_AFTER_FAILED_ATTEMPTS = 10; +function groupByUserId(list) { + const map = new Map(); + for (const item of list) { + const key = String(item.userId); + if (!map.has(key)) map.set(key, []); + map.get(key).push(item); + } + return map; +} + +/** + * R2 单点适配层:app 与 apps 只能在这里生成。 + * + * - apps:新表投影,config 合并默认值后返回 + * - app :过渡期兼容视图,以库里旧 app 为基底保留 tcm.organization 等历史字段, + * 再用新表覆盖 role / wxopenid。这样原应用不改代码也能继续工作, + * 下个版本下游全部改读 apps 后再移除。 + */ +async function buildUserViews(users) { + const list = (users || []).filter(Boolean); + if (!list.length) return []; + + const ids = list.map((user) => user._id); + const [memberships, identities] = await Promise.all([ + DBModel.UserApp.find({ userId: { $in: ids } }).sort({ appId: 1 }).lean(), + DBModel.UserIdentity.find({ userId: { $in: ids }, openid: { $exists: true } }) + .sort({ appId: 1 }) + .lean(), + ]); + + const membershipsByUser = groupByUserId(memberships); + const identitiesByUser = groupByUserId(identities); + + return list.map((user) => { + const safe = sanitizeUser(user); + const key = String(user._id); + const userMemberships = membershipsByUser.get(key) || []; + const userIdentities = identitiesByUser.get(key) || []; + + const apps = userMemberships.map((membership) => ({ + appId: membership.appId, + roles: membership.roles || [], + status: membership.status, + config: resolveConfig(membership.appId, membership.config), + })); + + const baseApp = safe.app && typeof safe.app === 'object' && !Array.isArray(safe.app) + ? safe.app + : {}; + const legacyApp = { ...baseApp }; + + for (const membership of userMemberships) { + const identity = userIdentities.find( + (item) => item.appId === membership.appId && item.openid + ); + const existing = legacyApp[membership.appId] + && typeof legacyApp[membership.appId] === 'object' + ? legacyApp[membership.appId] + : {}; + + legacyApp[membership.appId] = { + ...existing, + role: membership.roles || [], + ...(identity?.openid ? { wxopenid: identity.openid } : {}), + }; + } + + return { ...safe, apps, app: legacyApp }; + }); +} + +async function buildUserView(user) { + const [view] = await buildUserViews([user]); + return view; +} + class HandlerUser { // 生成 token(DB 中只存哈希,原始 token 仅在登录响应中返回一次) // 必须用 CSPRNG:Math.random 的输出可预测,token 可预测就等于可冒充任意用户 @@ -103,8 +262,8 @@ class HandlerUser { } // 登录/注册响应:脱敏后单独附加本次签发的原始 token - buildLoginResponse(user, raw) { - const safe = sanitizeUser(user); + async buildLoginResponse(user, raw) { + const safe = await buildUserView(user); safe.security = safe.security || {}; safe.security.token = raw; safe.security.tokenExpiry = user.security.tokenExpiry; @@ -159,7 +318,7 @@ class HandlerUser { // 生成 token(哈希入库,响应附原始 token) const { raw } = await this.issueToken(user); - return ResponseUtil.success(ctx, { user: this.buildLoginResponse(user, raw) }, "注册成功"); + return ResponseUtil.success(ctx, { user: await this.buildLoginResponse(user, raw) }, "注册成功"); } catch (err) { if (err?.code === 11000) { return ResponseUtil.error(ctx, "手机号已注册", null, 409); @@ -221,7 +380,211 @@ class HandlerUser { user.security.lastLoginIp = ctx.ip || ctx.request.ip; const { raw } = await this.issueToken(user); - return ResponseUtil.success(ctx, { user: this.buildLoginResponse(user, raw) }, "登录成功"); + return ResponseUtil.success(ctx, { user: await this.buildLoginResponse(user, raw) }, "登录成功"); + } catch (err) { + return ResponseUtil.internalError(ctx, err); + } + } + + /** + * 生成微信扫码登录地址 + * + * mode=login:未登录可调用,扫码后登录后台 + * mode=bind :需要已登录,扫码后把该微信绑定到当前账号(不改变任何角色) + */ + async wechatQrUrl(ctx) { + const cfg = wechatWebConfig(); + if (!isWechatWebReady(cfg)) { + return ResponseUtil.error(ctx, "未配置微信扫码登录,请联系管理员", null, 503); + } + + const mode = ctx.request.query.mode === "bind" ? "bind" : "login"; + const current = ctx.state.user; + if (mode === "bind" && !current) { + return ResponseUtil.unauthorized(ctx, "绑定微信需要先登录"); + } + + const now = Date.now(); + pruneStore(qrStateStore, now); + + const crypto = await import("crypto"); + const state = crypto.randomBytes(16).toString("hex"); + qrStateStore.set(state, { + mode, + userId: current?._id ? String(current._id) : null, + expiresAt: now + QR_STATE_TTL, + }); + + const url = "https://open.weixin.qq.com/connect/qrconnect" + + `?appid=${encodeURIComponent(cfg.appid)}` + + `&redirect_uri=${encodeURIComponent(cfg.callbackUri)}` + + "&response_type=code&scope=snsapi_login" + + `&state=${state}#wechat_redirect`; + + return ResponseUtil.success(ctx, { + url, + state, + mode, + expiresIn: Math.floor(QR_STATE_TTL / 1000), + }, "获取成功"); + } + + /** + * 微信扫码回调(浏览器 302 跳转,不走 JSON) + * + * 安全红线:扫码只解决「你是谁」,不解决「你能不能进后台」。 + * 没有 web-escort-admin 的 admin 成员关系一律拒绝,绝不自动创建账号或授权。 + */ + async wechatQrCallback(ctx) { + const cfg = wechatWebConfig(); + if (!isWechatWebReady(cfg)) { + return ResponseUtil.error(ctx, "未配置微信扫码登录", null, 503); + } + + const redirectError = (code) => { + ctx.redirect(`${cfg.webOrigin}/auth/wechat-callback?error=${encodeURIComponent(code)}`); + }; + + const state = ctx.request.query.state ? String(ctx.request.query.state) : ""; + const record = state ? qrStateStore.get(state) : null; + // state 一次性:无论后续成功失败都不能复用 + if (state) qrStateStore.delete(state); + + if (!record || record.expiresAt <= Date.now()) { + return redirectError("state_invalid"); + } + + const code = ctx.request.query.code ? String(ctx.request.query.code) : ""; + // 用户取消授权时微信只回 state,不回 code + if (!code) return redirectError("cancelled"); + + try { + const tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" + + `?appid=${encodeURIComponent(cfg.appid)}` + + `&secret=${encodeURIComponent(cfg.secret)}` + + `&code=${encodeURIComponent(code)}` + + "&grant_type=authorization_code"; + const resp = await fetch(tokenUrl, { signal: AbortSignal.timeout(WX_REQUEST_TIMEOUT) }); + const data = await resp.json(); + + if (!data?.openid) { + return redirectError("wechat_failed"); + } + + // 绑定模式:只写身份,不碰角色和成员状态 + if (record.mode === "bind") { + if (!record.userId) return redirectError("bind_user_missing"); + + // openid 已属于其他账号时给出明确冲突提示,而不是兜底成 server_error + try { + await upsertIdentity({ + userId: record.userId, + appId: WEB_ADMIN_APP, + platform: "weixin", + provider: WECHAT_WEB_PROVIDER, + openid: data.openid, + unionid: data.unionid, + }); + } catch (err) { + if (err?.code === 11000) return redirectError("identity_conflict"); + throw err; + } + + return ctx.redirect(`${cfg.webOrigin}/auth/wechat-callback?bound=1`); + } + + // 登录模式:本应用 openid → unionid 跨应用 → 旧字段兜底 + const identity = await DBModel.UserIdentity.findOne({ + appId: WEB_ADMIN_APP, + provider: WECHAT_WEB_PROVIDER, + openid: data.openid, + }); + let user = identity ? await DBModel.User.findById(identity.userId) : null; + + if (!user && data.unionid) { + const samePerson = await DBModel.UserIdentity.findOne({ + provider: WECHAT_WEB_PROVIDER, + unionid: data.unionid, + }); + if (samePerson) user = await DBModel.User.findById(samePerson.userId); + } + if (!user) { + user = await DBModel.User.findOne({ [`app.${WEB_ADMIN_APP}.wxopenid`]: data.openid }); + } + + if (!user) return redirectError("not_bound"); + if (user.status?.account === "lock") return redirectError("locked"); + + const membership = await DBModel.UserApp.findOne({ + userId: user._id, + appId: WEB_ADMIN_APP, + status: "active", + roles: "admin", + }); + if (!membership) return redirectError("forbidden"); + + // openid 已绑到其他账号时触发唯一索引,按冲突处理,不做静默改绑 + try { + await upsertIdentity({ + userId: user._id, + appId: WEB_ADMIN_APP, + platform: "weixin", + provider: WECHAT_WEB_PROVIDER, + openid: data.openid, + unionid: data.unionid, + }); + } catch (err) { + if (err?.code === 11000) return redirectError("identity_conflict"); + throw err; + } + + await DBModel.UserApp.updateOne( + { _id: membership._id }, + { $set: { lastLoginAt: new Date() } } + ); + + // 回调地址在前端,token 不能放 URL(会进浏览器历史和 nginx 日志), + // 只带一个 60 秒有效、一次性的 ticket,由前端换取 token + const now = Date.now(); + pruneStore(qrTicketStore, now); + const crypto = await import("crypto"); + const ticket = crypto.randomBytes(24).toString("hex"); + qrTicketStore.set(ticket, { userId: String(user._id), expiresAt: now + QR_TICKET_TTL }); + + return ctx.redirect(`${cfg.webOrigin}/auth/wechat-callback?ticket=${ticket}`); + } catch (err) { + console.error("[wechat-qr] 回调处理失败:", err.message); + return redirectError("server_error"); + } + } + + // 用一次性 ticket 换取 token + async wechatQrExchange(ctx) { + const ticket = ctx.request.body?.ticket ? String(ctx.request.body.ticket) : ""; + if (!ticket) return ResponseUtil.badRequest(ctx, "缺少 ticket"); + + const record = qrTicketStore.get(ticket); + if (record) qrTicketStore.delete(ticket); + + if (!record || record.expiresAt <= Date.now()) { + return ResponseUtil.unauthorized(ctx, "登录凭证已失效,请重新扫码"); + } + + try { + const user = await DBModel.User.findById(record.userId); + if (!user) return ResponseUtil.unauthorized(ctx, "账号不存在"); + if (user.status?.account === "lock") return ResponseUtil.forbidden(ctx, "账户已被锁定"); + + const membership = await DBModel.UserApp.findOne({ + userId: user._id, + appId: WEB_ADMIN_APP, + status: "active", + roles: "admin", + }); + if (!membership) return ResponseUtil.forbidden(ctx, "无后台管理权限"); + + const { raw } = await this.issueToken(user); + return ResponseUtil.success(ctx, { user: await this.buildLoginResponse(user, raw) }, "登录成功"); } catch (err) { return ResponseUtil.internalError(ctx, err); } @@ -244,7 +607,8 @@ class HandlerUser { async userInfo(ctx) { // 已通过 auth 中间件验证的登录用户 if (ctx.state.user) { - return ResponseUtil.success(ctx, { user: sanitizeUser(ctx.state.user) }, "获取用户信息成功"); + const user = await buildUserView(ctx.state.user); + return ResponseUtil.success(ctx, { user }, "获取用户信息成功"); } // 不再支持「凭 userId 明文查询」:用户ID不是凭证, @@ -267,13 +631,28 @@ class HandlerUser { return ResponseUtil.badRequest(ctx, "缺少用户信息"); } + // updateFromUserInfo 是白名单取字段,这里只补最小防护: + // 手机号格式统一,addresses 限数组且限长(防止超大文档写入) + if (userInfo.profile?.mobile !== undefined + && !MOBILE_PATTERN.test(String(userInfo.profile.mobile))) { + return ResponseUtil.badRequest(ctx, "手机号格式不正确"); + } + if (userInfo.addresses !== undefined + && (!Array.isArray(userInfo.addresses) || userInfo.addresses.length > 50)) { + return ResponseUtil.badRequest(ctx, "地址列表不合法"); + } + const updatedUser = await DBModel.User.updateFromUserInfo(user._id, userInfo); if (!updatedUser) { return ResponseUtil.internalError(ctx, "更新用户失败"); } - return ResponseUtil.success(ctx, { user: sanitizeUser(updatedUser) }, "更新成功"); + return ResponseUtil.success(ctx, { user: await buildUserView(updatedUser) }, "更新成功"); } catch (err) { + // 字段校验失败(如 sex 非法枚举)应返回 400 而不是 500 + if (err?.name === "ValidationError") { + return ResponseUtil.badRequest(ctx, err.message); + } // 手机号允许用户自助修改,但必须是全局唯一的:撞号时给出明确提示而不是通用错误 if (err?.code === 11000) { return ResponseUtil.error(ctx, "该手机号已被使用", null, 409); @@ -284,33 +663,362 @@ class HandlerUser { // 获取用户列表 async userList(ctx) { - // auth() 中间件已验证登录态 - const user = ctx.state.user; - if (!user) { + // 鉴权已由路由层 auth({ appIds, roles }) 完成 + if (!ctx.state.user) { return ResponseUtil.unauthorized(ctx, "用户未登录或 token 无效"); } - if (!isAdmin(user)) { - return ResponseUtil.unauthorized(ctx, "用户无管理员权限"); - } - try { const page = Math.max(1, parseInt(ctx.request.body?.page) || 1); const pageSize = Math.min(200, Math.max(1, parseInt(ctx.request.body?.pageSize) || 100)); - const filter = { "app.wxapp-escort": { $exists: true } }; + const { keyword, accountStatus, startDate, endDate } = ctx.request.body || {}; - const [users, total] = await Promise.all([ - DBModel.User.find(filter).skip((page - 1) * pageSize).limit(pageSize), - DBModel.User.countDocuments(filter), + // total 现在是「该应用的有效成员数」,不再是「登录过该小程序的人数」 + const membershipMatch = { appId: "wxapp-escort", status: "active" }; + const userMatch = {}; + + if (keyword && String(keyword).trim()) { + // 关键词转义,避免用户输入的括号等字符被当成正则元字符 + const safe = String(keyword).trim().replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const reg = new RegExp(safe, "i"); + userMatch.$or = [ + { "userDoc.profile.name": reg }, + { "userDoc.profile.mobile": reg }, + { "userDoc.profile.email": reg }, + { "userDoc.profile.pinyin": reg }, + ]; + } + + if (accountStatus) { + if (!["normal", "lock"].includes(accountStatus)) { + return ResponseUtil.badRequest(ctx, "账号状态筛选值不正确"); + } + userMatch["userDoc.status.account"] = accountStatus; + } + + // 注册时间范围:meta.createtime 存的是 Date,按 UTC 日界换算 + const parseDay = (value) => { + if (!value || !/^\d{4}-\d{2}-\d{2}$/.test(String(value))) return null; + const date = new Date(`${value}T00:00:00.000Z`); + return Number.isNaN(date.getTime()) ? null : date; + }; + const from = parseDay(startDate); + const to = parseDay(endDate); + if (from || to) { + userMatch["userDoc.meta.createtime"] = {}; + if (from) userMatch["userDoc.meta.createtime"].$gte = from; + if (to) { + to.setUTCDate(to.getUTCDate() + 1); // 含结束日当天 + userMatch["userDoc.meta.createtime"].$lt = to; + } + } + + // 以 user_app 为分页主体,$lookup 用户表后再应用搜索/状态/时间筛选, + // 这样权限口径是「有效成员」,同时保留原管理端的筛选与创建时间倒序。 + const basePipeline = [ + { $match: membershipMatch }, + { + $lookup: { + from: "user", + localField: "userId", + foreignField: "_id", + as: "userDoc", + }, + }, + { $unwind: "$userDoc" }, + ]; + if (Object.keys(userMatch).length) basePipeline.push({ $match: userMatch }); + + const [rows, totalRows] = await Promise.all([ + DBModel.UserApp.aggregate([ + ...basePipeline, + { $sort: { "userDoc.meta.createtime": -1, "userDoc._id": -1 } }, + { $skip: (page - 1) * pageSize }, + { $limit: pageSize }, + ]).exec(), + DBModel.UserApp.aggregate([...basePipeline, { $count: "total" }]).exec(), ]); - const safeUsers = users.map((u) => sanitizeUser(u)); + const users = rows.map((row) => row.userDoc); + const total = totalRows[0]?.total || 0; + const safeUsers = await buildUserViews(users); + return ResponseUtil.success(ctx, { users: safeUsers, total, page, pageSize }, "获取用户列表成功"); } catch (err) { return ResponseUtil.internalError(ctx, err); } } + /** + * 管理端批量取用户基础信息 + * + * 用途:就诊人列表/订单列表只存 userId,前端需要展示归属用户昵称与手机号。 + * 走批量而不是让前端逐行查,避免 N+1;ids 上限 100 与列表分页量级对齐 + */ + async batchUserInfo(ctx) { + const current = ctx.state.user; + if (!current) { + return ResponseUtil.unauthorized(ctx, "用户未登录或 token 无效"); + } + + try { + const rawIds = ctx.request.body?.userIds; + if (!Array.isArray(rawIds) || rawIds.length === 0) { + return ResponseUtil.badRequest(ctx, "缺少用户ID列表"); + } + + const ids = [...new Set(rawIds.map((id) => String(id || "").trim()))] + .filter((id) => /^[0-9a-fA-F]{24}$/.test(id)); + + if (!ids.length) { + return ResponseUtil.badRequest(ctx, "用户ID列表不合法"); + } + if (ids.length > 100) { + return ResponseUtil.badRequest(ctx, "单次最多查询 100 个用户"); + } + + const users = await DBModel.User.find({ _id: { $in: ids } }); + const safeUsers = await buildUserViews(users); + return ResponseUtil.success(ctx, { users: safeUsers }, "查询成功"); + } catch (err) { + return ResponseUtil.internalError(ctx, err); + } + } + + /** + * 锁定 / 解锁账号 + * + * 只改 status.account(枚举只有 normal / lock),并在解锁时清零失败登录次数, + * 与 doc/backend-architecture.md 里「解锁需手动改库」的遗留事项对应。 + * 锁定会同时作废 token:否则已登录会话在 health 侧最多还能用 5 分钟 + */ + async lockUser(ctx) { + const current = ctx.state.user; + if (!current) { + return ResponseUtil.unauthorized(ctx, "用户未登录或 token 无效"); + } + + try { + const { userId, locked } = ctx.request.body || {}; + if (!userId || !/^[0-9a-fA-F]{24}$/.test(String(userId))) { + return ResponseUtil.badRequest(ctx, "用户ID不合法"); + } + if (typeof locked !== "boolean") { + return ResponseUtil.badRequest(ctx, "缺少 locked 参数"); + } + // 防止管理员把自己锁在门外 + if (String(userId) === String(current._id)) { + return ResponseUtil.badRequest(ctx, "不能修改当前登录账号的锁定状态"); + } + + const set = { + "status.account": locked ? "lock" : "normal", + "meta.updatetime": Date.now(), + }; + if (locked) { + // 作废已有会话,避免锁定了却还能继续用旧 token + set["security.token"] = null; + set["security.tokenExpiry"] = null; + } else { + set["security.failedLoginAttempts"] = 0; + } + + const user = await DBModel.User.findByIdAndUpdate(userId, { $set: set }, { new: true }); + if (!user) { + return ResponseUtil.notFound(ctx, "用户不存在"); + } + + return ResponseUtil.success(ctx, { user: await buildUserView(user) }, locked ? "账号已锁定" : "账号已解锁"); + } catch (err) { + return ResponseUtil.internalError(ctx, err); + } + } + + /** + * 更新当前用户在某应用内的个人配置 + * body: { appId, config } + */ + async appConfig(ctx) { + const { error, value } = appConfigSchema.validate(ctx.request.body, { abortEarly: false }); + if (error) { + return ResponseUtil.badRequest(ctx, error.details[0].message); + } + + const user = ctx.state.user; + if (!user) { + return ResponseUtil.unauthorized(ctx, "用户未登录或 token 无效"); + } + + const { appId, config } = value; + + if (!APP_REGISTRY[appId]) { + return ResponseUtil.badRequest(ctx, `未配置 appId: ${appId}`); + } + if (!hasConfigSchema(appId)) { + return ResponseUtil.badRequest(ctx, `该应用暂不支持配置: ${appId}`); + } + + try { + const membership = await DBModel.UserApp.findOne({ + userId: user._id, + appId, + status: "active", + }); + if (!membership) { + return ResponseUtil.forbidden(ctx, "无权访问该应用"); + } + + let patch; + try { + patch = validateAppConfig(appId, config); + } catch (err) { + return ResponseUtil.badRequest(ctx, err.message); + } + + // 只更新传入的叶子路径;未传的兄弟字段保持不变 + const flat = flattenLeaves(patch); + if (Object.keys(flat).length === 0) { + return ResponseUtil.badRequest(ctx, "没有可更新的配置项"); + } + + const set = { configUpdatedAt: new Date() }; + for (const [path, item] of Object.entries(flat)) { + set[`config.${path}`] = item; + } + + await DBModel.UserApp.updateOne({ _id: membership._id }, { $set: set }); + + const updated = await DBModel.UserApp.findById(membership._id).lean(); + return ResponseUtil.success( + ctx, + { appId, config: resolveConfig(appId, updated?.config) }, + "配置更新成功" + ); + } catch (err) { + return ResponseUtil.internalError(ctx, err); + } + } + + /** + * 授予 / 撤销应用角色 + * body: { userId, appId, action: "grant" | "revoke", roles: ["admin"] } + */ + async grant(ctx) { + const { error, value } = grantSchema.validate(ctx.request.body, { abortEarly: false }); + if (error) { + return ResponseUtil.badRequest(ctx, error.details[0].message); + } + + const operator = ctx.state.user; + if (!operator) { + return ResponseUtil.unauthorized(ctx, "用户未登录或 token 无效"); + } + + const { userId, appId, action } = value; + const targetRoles = [...new Set( + (value.roles || ["admin"]).map((role) => String(role || "").trim()).filter(Boolean) + )]; + + if (!APP_REGISTRY[appId]) { + return ResponseUtil.badRequest(ctx, `未配置 appId: ${appId}`); + } + if (!targetRoles.length) { + return ResponseUtil.badRequest(ctx, "角色不能为空"); + } + if (!targetRoles.every((role) => GRANTABLE_ROLES.includes(role))) { + return ResponseUtil.badRequest(ctx, "不支持的角色"); + } + if (!mongoose.isValidObjectId(userId)) { + return ResponseUtil.badRequest(ctx, "用户ID不合法"); + } + + try { + // 操作者必须持有目标应用的 admin 角色才能授权/撤销(与方案文档 6.8 一致, + // 避免 Web 后台管理员改动小程序管理端的角色) + const operatorMembership = await DBModel.UserApp.findOne({ + userId: operator._id, + appId, + status: "active", + roles: "admin", + }).select("_id"); + if (!operatorMembership) { + return ResponseUtil.forbidden(ctx, "无权管理该应用的角色"); + } + + const targetUser = await DBModel.User.findById(userId).select("_id"); + if (!targetUser) { + return ResponseUtil.notFound(ctx, "用户不存在"); + } + + if (action === "grant") { + const granted = await grantRoles({ + userId, + appId, + roles: targetRoles, + grantedBy: operator._id, + }); + return ResponseUtil.success(ctx, { userId, appId, roles: granted }, "授权成功"); + } + + // 撤销前确认目标用户确实持有要撤销的角色 + const current = await DBModel.UserApp.findOne({ userId, appId }).lean(); + if (!current) { + return ResponseUtil.notFound(ctx, "该用户在该应用没有成员关系"); + } + const removable = targetRoles.filter( + (role) => Array.isArray(current.roles) && current.roles.includes(role) + ); + if (!removable.length) { + return ResponseUtil.badRequest(ctx, "该用户不持有要撤销的角色"); + } + + const removesAdmin = removable.includes("admin"); + + if (removesAdmin) { + // 撤销前先友好拒绝最常见情况 + const remainingBefore = await DBModel.UserApp.countDocuments({ + appId, + status: "active", + roles: "admin", + userId: { $ne: userId }, + }); + if (remainingBefore === 0) { + return ResponseUtil.badRequest(ctx, "不能撤销最后一个管理员"); + } + } + + const revoked = await revokeRoles({ + userId, + appId, + roles: removable, + grantedBy: operator._id, + }); + + if (removesAdmin) { + // 并发补偿:check-then-act 存在竞态(两个管理员同时互撤都可能通过预检), + // 撤销后复核,若已无启用管理员则立即回滚本次撤销,保证任何时刻至少一个管理员 + const remainingAfter = await DBModel.UserApp.countDocuments({ + appId, + status: "active", + roles: "admin", + }); + if (remainingAfter === 0) { + await grantRoles({ + userId, + appId, + roles: ["admin"], + grantedBy: operator._id, + }); + return ResponseUtil.badRequest(ctx, "不能撤销最后一个管理员"); + } + } + + return ResponseUtil.success(ctx, { userId, appId, roles: revoked }, "撤销成功"); + } catch (err) { + return ResponseUtil.internalError(ctx, err); + } + } + // 微信登录 async wxSignin(ctx) { const { error, value } = wxSigninSchema.validate(ctx.request.body, { abortEarly: false }); @@ -321,10 +1029,14 @@ class HandlerUser { try { const { code, phoneNumber, name, appId } = value; - let app = config.app[appId]; + const app = config.app[appId]; if (!app) { return ResponseUtil.badRequest(ctx, `未配置 appId: ${appId}`); } + const meta = APP_REGISTRY[appId]; + if (!meta) { + return ResponseUtil.badRequest(ctx, `未登记 appId: ${appId}`); + } // 手机号获取: // 1) 优先用 phoneCode 由服务端向微信换取(可信,可绑定已有账号) @@ -358,55 +1070,151 @@ class HandlerUser { return ResponseUtil.error(ctx, `微信接口错误: ${sessionData.errmsg}`, null, 400); } - const { openid } = sessionData; + const openid = String(sessionData.openid || "").trim(); if (!openid) { return ResponseUtil.error(ctx, "微信登录失败,未获取到 openid", null, 400); } + const unionid = String(sessionData.unionid || "").trim() || undefined; - let key = `app.${appId}.wxopenid`; - let user = await DBModel.User.findOne({ [key]: openid }); + // 1. 先按本应用身份查 + const identity = await DBModel.UserIdentity.findOne({ + appId, + provider: meta.provider, + openid, + }); + let user = identity ? await DBModel.User.findById(identity.userId) : null; + // 1.5 过渡期兜底:新表未命中时回查旧 app 字段,命中则补写新表。 + // 回填有遗漏时不会把老用户当成新用户建重复账号。 if (!user) { - const mobile = verifiedPhoneNumber || phoneNumber; + user = await DBModel.User.findOne({ [`app.${appId}.wxopenid`]: openid }); + if (user) { + try { + await backfillOneFromLegacy(user, appId, openid, unionid); + } catch (err) { + console.warn(`[wxSignin] 旧数据补写失败 user=${user._id} app=${appId}:`, err.message); + } + } + } + + // 2. 跨应用:unionid 优先(微信开放平台已绑定时才有值) + if (!user && unionid) { + const samePerson = await DBModel.UserIdentity.findOne({ + provider: meta.provider, + unionid, + }); + if (samePerson) user = await DBModel.User.findById(samePerson.userId); + } + + // 3. 手机号兜底:只允许服务端验证过的手机号绑定已有账号 + if (!user && verifiedPhoneNumber) { + user = await DBModel.User.findOne({ "profile.mobile": verifiedPhoneNumber }); + } + + // 4. 仍不存在则新建平台账号(成员关系在步骤 6 写入) + if (!user) { + const mobile = String(verifiedPhoneNumber || phoneNumber || "").trim(); if (!mobile) { return ResponseUtil.badRequest(ctx, "缺少手机号"); } - const existingUser = await DBModel.User.findOne({ "profile.mobile": mobile }); - if (existingUser) { - // 已有账号:仅允许服务端验证过的手机号绑定微信,防止账号接管 - if (!verifiedPhoneNumber) { + // 未验证的手机号只允许用于新建账号,不能合并到已有账号 + if (!verifiedPhoneNumber) { + const existing = await DBModel.User.findOne({ "profile.mobile": mobile }); + if (existing) { return ResponseUtil.error(ctx, "该手机号已注册,请先使用手机号登录后再绑定微信", null, 409); } - user = existingUser; - } else { - // 新建用户 - const newUser = { + } + + try { + user = await DBModel.User.create({ profile: { name: name || mobile, mobile }, status: { account: "normal" }, + social: { wechat: {} }, app: {}, - }; - newUser.app[appId] = { role: ["user"], wxopenid: openid }; - user = await DBModel.User.setUser(newUser); + }); + } catch (err) { + if (err?.code === 11000) { + return ResponseUtil.error(ctx, "该手机号已注册,请先使用手机号登录后再绑定微信", null, 409); + } + throw err; } } - if (user) { - // 绑定/更新 openid;不覆盖已有用户的手机号 - if (!(appId in user.app)) { - user.app[appId] = { role: ["user"], wxopenid: openid }; + // 5. 绑定身份:唯一索引兜底。 + // 11000 可能来自 unionid(该微信已绑定其他账号)或 openid(并发绑定), + // 必须按 keyPattern / message 区分,不能一律报同一种错误。 + try { + await upsertIdentity({ + userId: user._id, + appId, + platform: meta.platform, + provider: meta.provider, + openid, + unionid, + }); + } catch (err) { + if (err?.code !== 11000) throw err; + + const pattern = err.keyPattern || err.cause?.keyPattern || {}; + const unionidConflict = unionid + && ("unionid" in pattern || /unionid/i.test(err.message || "")); + + if (unionidConflict) { + const owner = await DBModel.UserIdentity.findOne({ + provider: meta.provider, + unionid, + }); + if (!owner || String(owner.userId) !== String(user._id)) { + return ResponseUtil.error(ctx, "该微信已绑定其他账号", null, 409); + } + + // 同一用户在其他应用已占用 unionid:本应用身份不写 unionid,重试一次 + try { + await upsertIdentity({ + userId: user._id, + appId, + platform: meta.platform, + provider: meta.provider, + openid, + }); + } catch (retryErr) { + if (retryErr?.code === 11000) { + return ResponseUtil.error(ctx, "该微信身份已绑定其他账号", null, 409); + } + throw retryErr; + } } else { - user.app[appId].wxopenid = openid; + const bound = await DBModel.UserIdentity.findOne({ + appId, + provider: meta.provider, + openid, + }); + if (!bound || String(bound.userId) !== String(user._id)) { + return ResponseUtil.error(ctx, "该微信身份已绑定其他账号", null, 409); + } } - } else { - return ResponseUtil.internalError(ctx, "用户不存在"); } - // 更新Token(哈希入库) + // 6. 保证成员关系存在,并刷新最后登录时间(已有管理员角色不会被降级) + await upsertLoginMembership({ userId: user._id, appId }); + + // 7. 过渡期双写旧 app 字段,供 api/health 等未迁移的下游继续读取。 + // 下个版本下游改读 user_app 后再删除。 + await DBModel.User.updateOne( + { _id: user._id, [`app.${appId}.role`]: { $exists: false } }, + { $set: { [`app.${appId}.role`]: ["user"] } } + ); + await DBModel.User.updateOne( + { _id: user._id }, + { $set: { [`app.${appId}.wxopenid`]: openid } } + ); + + // 8. 更新Token(哈希入库) user.security.lastLoginIp = ctx.ip || ctx.request.ip; const { raw } = await this.issueToken(user); - return ResponseUtil.success(ctx, { user: this.buildLoginResponse(user, raw) }, "登录成功"); + return ResponseUtil.success(ctx, { user: await this.buildLoginResponse(user, raw) }, "登录成功"); } catch (err) { return ResponseUtil.internalError(ctx, err); } diff --git a/middleware/auth.js b/middleware/auth.js index 56e6614..b6844fd 100644 --- a/middleware/auth.js +++ b/middleware/auth.js @@ -40,10 +40,19 @@ async function findUserByToken(rawToken) { * 认证中间件 - 验证 token 并挂载用户信息到 ctx * 可选参数: * - required: 是否必须登录(默认 true) - * - roles: 允许的角色列表(可选) + * - appId / appIds: 允许访问的应用(任一即可),声明后必须存在有效成员关系 + * - roles: 允许的角色列表(必须与 appId / appIds 一起使用) + * + * 角色只在该应用内判定,不再遍历用户的所有应用; + * 传 appIds 是为了同时支持小程序管理端与 Web 管理端。 */ function auth(options = {}) { - const { required = true, roles } = options; + const { required = true, appId, appIds, roles } = options; + const allowedAppIds = Array.isArray(appIds) && appIds.length + ? appIds + : appId + ? [appId] + : []; return async (ctx, next) => { const token = extractToken(ctx); @@ -69,17 +78,32 @@ function auth(options = {}) { return ResponseUtil.forbidden(ctx, '账户已被锁定'); } - // 角色检查 - if (roles && roles.length > 0) { - const hasRole = roles.some(role => { - // 检查 app 字段中的角色 - return Object.values(user.app || {}).some(appData => - appData && Array.isArray(appData.role) && appData.role.includes(role) - ); - }); - if (!hasRole) { - return ResponseUtil.forbidden(ctx, '权限不足'); + if (allowedAppIds.length > 0) { + // 一次取出所有允许应用的启用成员关系:用户可能同时是多个管理端成员, + // 角色判定必须逐条看,不能只取排序第一条(否则 A 应用的 user 会挡住 B 应用的 admin) + const memberships = await DBModel.UserApp.find({ + userId: user._id, + appId: { $in: allowedAppIds }, + status: 'active', + }).sort({ appId: 1 }); + + if (!memberships.length) { + return ResponseUtil.forbidden(ctx, '无权访问该应用'); } + + let membership = memberships[0]; + if (roles && roles.length > 0) { + membership = memberships.find((m) => roles.some((r) => m.roles?.includes(r))); + if (!membership) { + return ResponseUtil.forbidden(ctx, '权限不足'); + } + } + + ctx.state.membership = membership; + ctx.state.appId = membership.appId; + } else if (roles && roles.length > 0) { + // 角色校验必须带应用维度,缺 appId 视为路由配置错误 + return ResponseUtil.internalError(ctx, '角色校验缺少 appId'); } ctx.state.user = user; @@ -87,33 +111,6 @@ function auth(options = {}) { }; } -/** - * 管理端身份判定(与 health 服务 utils/permissions.js 同一口径) - * - * 不再用「app 里存在 wxapp-escort-admin 键」:该键历史上可由 /user/register 的 - * 客户端入参写入,任何人都能据此自封管理员。现在注册侧拒绝写 app, - * 但库里可能残留历史账号,因此要求显式 role === 'admin'; - * role 缺失的历史账号暂按管理员放行并打告警,待库中补齐 role 后收紧。 - * - * @param {Object} user 用户文档或脱敏后的用户对象 - * @returns {boolean} - */ -function isAdmin(user) { - const entry = user?.app?.['wxapp-escort-admin']; - if (!entry) return false; - - const roles = Array.isArray(entry.role) ? entry.role : [entry.role].filter(Boolean); - if (roles.includes('admin')) return true; - - if (entry.role === undefined) { - console.warn( - "[auth] 管理员账号缺少 role 字段,请补齐 app.wxapp-escort-admin.role = ['admin']" - ); - return true; - } - return false; -} - /** * 返回用户安全对象(去除密码、token 等敏感字段) * 注意:登录/注册响应中的 token 由 handler 单独附加 @@ -129,4 +126,4 @@ function sanitizeUser(user) { return obj; } -export { auth, extractToken, sanitizeUser, findUserByToken, isAdmin }; +export { auth, extractToken, sanitizeUser, findUserByToken }; diff --git a/models/app_config.js b/models/app_config.js new file mode 100644 index 0000000..4cc0900 --- /dev/null +++ b/models/app_config.js @@ -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-escort-admin": 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-escort-admin": { + 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; +} diff --git a/models/app_registry.js b/models/app_registry.js new file mode 100644 index 0000000..6f51937 --- /dev/null +++ b/models/app_registry.js @@ -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-escort-admin": { 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-escort-admin", "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; +} diff --git a/models/index.js b/models/index.js index 2fb22f7..57628dd 100644 --- a/models/index.js +++ b/models/index.js @@ -2,6 +2,8 @@ import mongoose from 'mongoose'; import { UserSchema } from "./schema/user.js" +import { UserAppSchema } from "./schema/user_app.js" +import { UserIdentitySchema } from "./schema/user_identity.js" import config from '../conf.json' with { type: 'json' }; import logger from '../utils/logger.js'; @@ -9,6 +11,8 @@ class MongoDBSchema { constructor() { this.dbConnection = null; this.User = null; + this.UserApp = null; + this.UserIdentity = null; } init() { @@ -35,6 +39,8 @@ class MongoDBSchema { ); this.User = this.dbConnection.model('user', UserSchema) + this.UserApp = this.dbConnection.model('user_app', UserAppSchema) + this.UserIdentity = this.dbConnection.model('user_identity', UserIdentitySchema) } } diff --git a/models/schema/user.js b/models/schema/user.js index aade68c..639e801 100644 --- a/models/schema/user.js +++ b/models/schema/user.js @@ -208,7 +208,19 @@ UserSchema.statics.delUser = async function (_id, mobile, email, wxunionid, cb) } try { - return await this.findOneAndDelete(filter, cb); + const user = await this.findOne(filter); + if (!user) return null; + + // 删除账号时同步清理成员关系与外部身份,避免残留关系被新账号复用。 + // 用原生命令集合而不是 this.db.model(...):不依赖模型是否已注册。 + await Promise.all([ + this.db.collection('user_app').deleteMany({ userId: user._id }), + this.db.collection('user_identity').deleteMany({ userId: user._id }), + ]); + + await this.deleteOne({ _id: user._id }); + if (typeof cb === 'function') cb(null, user); + return user; } catch (error) { return null; } diff --git a/models/schema/user_app.js b/models/schema/user_app.js new file mode 100644 index 0000000..c17d203 --- /dev/null +++ b/models/schema/user_app.js @@ -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 }; diff --git a/models/schema/user_identity.js b/models/schema/user_identity.js new file mode 100644 index 0000000..abe23f5 --- /dev/null +++ b/models/schema/user_identity.js @@ -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 }; diff --git a/models/user_membership.js b/models/user_membership.js new file mode 100644 index 0000000..168fe12 --- /dev/null +++ b/models/user_membership.js @@ -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; +} diff --git a/routes/index.js b/routes/index.js index 9b12dc4..5239d58 100644 --- a/routes/index.js +++ b/routes/index.js @@ -2,6 +2,9 @@ import Router from 'koa-router'; import { HandlerUser } from '../handler/users.js'; import { rateLimit } from '../middleware/ratelimit.js'; import { auth } from '../middleware/auth.js'; +import { ADMIN_APP_IDS } from '../models/app_registry.js'; + +const adminAuth = auth({ appIds: ADMIN_APP_IDS, roles: ['admin'] }); class ApiRouter { constructor() { @@ -18,10 +21,23 @@ class ApiRouter { userRouter.post('/signin', rateLimit(10, 60_000), this.handler.signin.bind(this.handler)); userRouter.post('/wxsignin', rateLimit(10, 60_000), this.handler.wxSignin.bind(this.handler)); + // 微信扫码登录(开放平台网站应用):生成二维码地址 / 微信回调 / ticket 换 token + userRouter.get('/wechat/qr/url', auth({ required: false }), rateLimit(20, 60_000), this.handler.wechatQrUrl.bind(this.handler)); + userRouter.get('/wechat/qr/callback', rateLimit(20, 60_000), this.handler.wechatQrCallback.bind(this.handler)); + userRouter.post('/wechat/qr/exchange', rateLimit(20, 60_000), this.handler.wechatQrExchange.bind(this.handler)); + userRouter.post('/signout', auth({ required: false }), this.handler.signout.bind(this.handler)); userRouter.post('/userInfo', auth({ required: false }), this.handler.userInfo.bind(this.handler)); userRouter.post('/update', auth(), this.handler.updateUser.bind(this.handler)); - userRouter.post('/list', auth(), this.handler.userList.bind(this.handler)); + // 管理端接口统一在路由层声明应用与角色,handler 内不再重复鉴权 + userRouter.post('/list', adminAuth, this.handler.userList.bind(this.handler)); + // 管理端:批量取用户信息(就诊人/订单展示归属用户)、锁定/解锁 + userRouter.post('/info/batch', adminAuth, this.handler.batchUserInfo.bind(this.handler)); + userRouter.post('/lock', adminAuth, this.handler.lockUser.bind(this.handler)); + // 应用内个人配置:登录用户只能改自己的配置,成员关系在 handler 内按 appId 校验 + userRouter.post('/app-config', auth(), this.handler.appConfig.bind(this.handler)); + // 授权入口:管理员授予/撤销应用角色 + userRouter.post('/grant', adminAuth, this.handler.grant.bind(this.handler)); userRouter.post('/wxgetphonenumber', rateLimit(10, 60_000), this.handler.wxGetPhoneNumber.bind(this.handler)); this.router.use(userRouter.routes()); diff --git a/scripts/backup_user_collection.js b/scripts/backup_user_collection.js new file mode 100644 index 0000000..3832c3f --- /dev/null +++ b/scripts/backup_user_collection.js @@ -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; +}); diff --git a/scripts/create_web_admin.js b/scripts/create_web_admin.js new file mode 100644 index 0000000..62f895d --- /dev/null +++ b/scripts/create_web_admin.js @@ -0,0 +1,122 @@ +"use strict"; + +/** + * 创建 / 重置 Web 后台管理员账号 + * + * 用途:Web 后台(ui/web_escort_admin)还没有任何管理账号时的初始化入口。 + * 之所以用脚本而不是接口:登录只会授予普通成员身份,管理员角色必须有服务端授权入口, + * 由脚本直接写库是首个管理员最稳妥的来源(与 doc/user-multi-app-plan.md 6.8 一致)。 + * + * 用法: + * node scripts/create_web_admin.js [手机号] [密码] [姓名] + * + * 默认值:13800000000 / Escort@2026 / 系统管理员 + * + * 行为: + * - 手机号不存在 → 新建账号并写入密码 + * - 手机号已存在 → 重置密码与失败次数(幂等,可重复执行) + * - 两种情况下都把 app["web-escort-admin"].role 置为 ["admin"] + * + * 注意:这里同时写旧字段 app 和新表 user_app: + * - app 供 api/health 等未迁移的下游继续读取 + * - user_app 供重构后的登录/鉴权读取 + * 下个版本下游全部迁移后再删除旧字段写入。 + */ + +import mongoose from "mongoose"; +import config from "../conf.json" with { type: "json" }; +import { UserSchema } from "../models/schema/user.js"; +import { UserAppSchema } from "../models/schema/user_app.js"; +import { hashPassword } from "../utils/crypto.js"; + +const WEB_ADMIN_APP = "web-escort-admin"; +const DEFAULT_MOBILE = "13800000000"; +const DEFAULT_PASSWORD = "Escort@2026"; +const DEFAULT_NAME = "系统管理员"; + +const mobile = String(process.argv[2] || DEFAULT_MOBILE).trim(); +const password = String(process.argv[3] || DEFAULT_PASSWORD); +const name = String(process.argv[4] || DEFAULT_NAME).trim(); + +async function main() { + if (!/^1[3-9]\d{9}$/.test(mobile)) { + throw new Error("手机号格式不正确"); + } + if (password.length < 6) { + throw new Error("密码至少 6 位"); + } + + const connection = mongoose.createConnection(config.mongodb.str, config.mongodb.option); + await connection.asPromise(); + const User = connection.model("user", UserSchema); + // 注册 UserApp 模型:autoIndex 由此确保 userId+appId 唯一索引存在, + // 全新环境先跑本脚本(先于 migrate / 服务启动)也不会缺索引 + const UserApp = connection.model("user_app", UserAppSchema); + + const passwd = await hashPassword(password); + + let user = await User.findOne({ "profile.mobile": mobile }); + let created = false; + + if (!user) { + user = new User({ + profile: { name, mobile }, + security: { passwd, passwdSalt: undefined }, + status: { account: "normal" }, + app: {}, + meta: { createtime: Date.now(), updatetime: Date.now() }, + }); + created = true; + } else { + // 已存在则重置凭证:脚本是唯一的管理员恢复手段,不做「已存在就跳过」 + user.security.passwd = passwd; + user.security.passwdSalt = undefined; + user.security.failedLoginAttempts = 0; + user.status.account = "normal"; + if (!user.profile?.name) user.profile.name = name; + user.meta = { ...(user.meta || {}), updatetime: Date.now() }; + } + + // 只授予 Web 后台这一个应用的 admin,不动小程序端(wxapp-escort-admin)的身份 + user.app = user.app || {}; + user.app[WEB_ADMIN_APP] = { + ...(user.app[WEB_ADMIN_APP] || {}), + role: ["admin"], + }; + + await user.save(); + + // 新模型(doc/user-multi-app-plan.md 方案 B)的授权主体是 user_app, + // isAdmin / auth({ appIds }) 只认这张表;旧 app 字段仅为下游过渡期兼容 + await UserApp.updateOne( + { userId: user._id, appId: WEB_ADMIN_APP }, + { + $addToSet: { roles: "admin" }, + $set: { status: "active", grantedAt: new Date() }, + $setOnInsert: { source: "manual" }, + }, + { upsert: true } + ); + + const membership = await UserApp.findOne({ userId: user._id, appId: WEB_ADMIN_APP }); + if (!membership) { + throw new Error("写入 user_app 成员关系失败"); + } + + console.log("---------------------------------------------"); + console.log(created ? "已创建 Web 后台管理员账号" : "已重置现有账号为 Web 后台管理员"); + console.log(` 用户ID : ${user._id}`); + console.log(` 姓名 : ${user.profile?.name || name}`); + console.log(` 手机号 : ${mobile}`); + console.log(` 密码 : ${password}`); + console.log(` 应用 : ${WEB_ADMIN_APP} / role=admin`); + console.log("---------------------------------------------"); + console.log("请登录后尽快修改默认密码。"); + + await connection.close(); +} + +main().catch(async (err) => { + console.error("[create_web_admin] 失败:", err.message); + process.exitCode = 1; +}); diff --git a/scripts/diff_legacy_vs_new.js b/scripts/diff_legacy_vs_new.js new file mode 100644 index 0000000..9c4adef --- /dev/null +++ b/scripts/diff_legacy_vs_new.js @@ -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; +}); diff --git a/scripts/grant_admin.js b/scripts/grant_admin.js new file mode 100644 index 0000000..e90af53 --- /dev/null +++ b/scripts/grant_admin.js @@ -0,0 +1,63 @@ +"use strict"; + +/** + * 授权管理员 / 紧急恢复(不走 HTTP) + * + * 用法: + * node scripts/grant_admin.js [roles] + * + * 示例: + * node scripts/grant_admin.js 66f0... wxapp-escort-admin admin + * node scripts/grant_admin.js 66f0... wxapp-escort-admin 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 [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; +}); diff --git a/scripts/migrate_user_app.js b/scripts/migrate_user_app.js new file mode 100644 index 0000000..bff31dd --- /dev/null +++ b/scripts/migrate_user_app.js @@ -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; +}); diff --git a/test/api.test.js b/test/api.test.js index 6341d35..d989aee 100644 --- a/test/api.test.js +++ b/test/api.test.js @@ -24,6 +24,10 @@ describe('用户接口集成测试', () => { await DBModel.User.delUser(userId); } app.stop(); + // 关闭数据库连接,否则 node --test 进程不会退出 + if (DBModel.dbConnection) { + await DBModel.dbConnection.close(); + } }); describe('POST /user/register', () => { @@ -194,12 +198,12 @@ describe('用户接口集成测试', () => { assert.equal(res.body.data.user.profile.name, '更新后的名字'); }); - it('无 token 更新应返回 400', async () => { + it('无 token 更新应返回 401', async () => { const res = await agent .post('/user/update') .send({ profile: { name: 'test' } }); - assert.equal(res.body.code, 400); + assert.equal(res.body.code, 401); }); }); diff --git a/test/app_config.test.js b/test/app_config.test.js new file mode 100644 index 0000000..4c9466a --- /dev/null +++ b/test/app_config.test.js @@ -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-escort-admin', 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), {}); + }); +}); diff --git a/test/app_registry.test.js b/test/app_registry.test.js new file mode 100644 index 0000000..4a38a72 --- /dev/null +++ b/test/app_registry.test.js @@ -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-escort-admin')); + assert.ok(ADMIN_APP_IDS.includes('web-escort-admin')); + assert.deepEqual(GRANTABLE_ROLES, ['user', 'admin']); + }); +}); diff --git a/test/auth.test.js b/test/auth.test.js index c3f5562..80a83da 100644 --- a/test/auth.test.js +++ b/test/auth.test.js @@ -68,7 +68,7 @@ describe('sanitizeUser', () => { assert.equal(safe.security.passwdSalt, undefined); assert.equal(safe.security.passwordResetToken, undefined); assert.equal(safe.security.passwordResetExpiry, undefined); - assert.equal(safe.security.token, 'valid_token'); + assert.equal(safe.security.token, undefined); assert.equal(safe.profile.mobile, '13800138000'); }); diff --git a/test/multi_app.test.js b/test/multi_app.test.js new file mode 100644 index 0000000..53efc40 --- /dev/null +++ b/test/multi_app.test.js @@ -0,0 +1,578 @@ +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-escort-admin'; +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-escort-admin 排序在 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, + }) + ); + }); +});