"use strict"; /** * 授权管理员 / 紧急恢复(不走 HTTP) * * 用法: * node scripts/grant_admin.js [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 [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; });