const fs = require('fs'); const path = require('path'); const mysql = require('mysql2/promise'); const ROOT = process.cwd(); const DEFAULT_CONFIG_PATH = path.join(ROOT, 'config', 'config.local.js'); const DEFAULT_METHOD_DOC_PATH = path.join(ROOT, 'methods', 'system.json'); function parseArgs(argv) { const args = { dryRun: false, roleId: 2, dbClient: 'wms', configPath: DEFAULT_CONFIG_PATH, methodDocPath: DEFAULT_METHOD_DOC_PATH, }; for (const item of argv) { if (item === '--dry-run') { args.dryRun = true; continue; } if (item.startsWith('--role-id=')) { args.roleId = Number(item.split('=')[1]); continue; } if (item.startsWith('--db-client=')) { args.dbClient = String(item.split('=')[1] || '').trim() || 'wms'; continue; } if (item.startsWith('--config-path=')) { const raw = String(item.split('=')[1] || '').trim(); args.configPath = path.resolve(ROOT, raw); continue; } if (item.startsWith('--method-doc=')) { const raw = String(item.split('=')[1] || '').trim(); args.methodDocPath = path.resolve(ROOT, raw); continue; } } if (!Number.isInteger(args.roleId) || args.roleId <= 0) { throw new Error('Invalid --role-id, must be a positive integer.'); } return args; } function loadConfig(configPath) { if (!fs.existsSync(configPath)) { throw new Error(`Config file not found: ${configPath}`); } const configFactory = require(configPath); const config = typeof configFactory === 'function' ? configFactory({ name: 'wms-permission-sync' }) : configFactory; return config; } function loadAuthRequiredMethods(methodDocPath) { if (!fs.existsSync(methodDocPath)) { throw new Error(`Method doc not found: ${methodDocPath}`); } const json = JSON.parse(fs.readFileSync(methodDocPath, 'utf8')); const groups = json && json.methods && Array.isArray(json.methods.groups) ? json.methods.groups : []; const methodSet = new Set(); for (const group of groups) { const list = group && Array.isArray(group.list) ? group.list : []; for (const item of list) { if (!item || !item.method || item.isNeedAuth !== true) continue; methodSet.add(String(item.method).trim()); } } return [ ...methodSet ].sort(); } function buildPermissionDefaults(methodPath, templateRow) { return { path: methodPath, type: 'api', component: templateRow ? templateRow.component : null, name: templateRow && templateRow.name ? templateRow.name : methodPath, redirect: templateRow ? templateRow.redirect : null, meta_title: templateRow && templateRow.meta_title ? templateRow.meta_title : `API:${methodPath}`, meta_icon: templateRow ? templateRow.meta_icon : null, hidden: templateRow ? Number(templateRow.hidden || 0) : 0, always_show: templateRow ? Number(templateRow.always_show || 0) : 0, parent_id: templateRow && templateRow.parent_id ? Number(templateRow.parent_id) : null, sort: templateRow ? Number(templateRow.sort || 0) : 0, status: templateRow ? Number(templateRow.status || 1) : 1, }; } async function queryPermissionTemplate(conn) { const [ rows ] = await conn.query(` SELECT component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, sort, status FROM wms_permission WHERE type = 'api' ORDER BY id ASC LIMIT 1 `); return rows[0] || null; } async function queryExistingPermissions(conn, methodPaths) { if (methodPaths.length === 0) return new Map(); const placeholders = methodPaths.map(() => '?').join(','); const [ rows ] = await conn.query( `SELECT id, path FROM wms_permission WHERE type = 'api' AND path IN (${placeholders})`, methodPaths ); const result = new Map(); for (const row of rows) { result.set(row.path, row.id); } return result; } async function insertPermission(conn, defaults) { const [ result ] = await conn.query( `INSERT INTO wms_permission (path, type, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, sort, status, created_at, update_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, [ defaults.path, defaults.type, defaults.component, defaults.name, defaults.redirect, defaults.meta_title, defaults.meta_icon, defaults.hidden, defaults.always_show, defaults.parent_id, defaults.sort, defaults.status, ] ); return result.insertId; } async function bindRolePermission(conn, roleId, permissionId) { const [ result ] = await conn.query( 'INSERT IGNORE INTO wms_role_permission (role_id, permission_id, created_at) VALUES (?, ?, NOW())', [ roleId, permissionId ] ); return result.affectedRows > 0; } async function main() { const args = parseArgs(process.argv.slice(2)); const cfg = loadConfig(args.configPath); const dbClient = cfg && cfg.mysql && cfg.mysql.clients && cfg.mysql.clients[args.dbClient]; if (!dbClient) { throw new Error(`MySQL client not found in config.mysql.clients: ${args.dbClient}`); } const methodPaths = loadAuthRequiredMethods(args.methodDocPath); if (methodPaths.length === 0) { console.log('[sync-system-api-permission] no isNeedAuth=true methods found.'); return; } const conn = await mysql.createConnection({ host: dbClient.host, port: Number(dbClient.port), user: dbClient.user, password: dbClient.password, database: dbClient.database, charset: dbClient.charset || 'utf8mb4', }); try { const templateRow = await queryPermissionTemplate(conn); const existingMap = await queryExistingPermissions(conn, methodPaths); const missingPaths = methodPaths.filter(item => !existingMap.has(item)); const created = []; const touchedPermissionIds = []; if (!args.dryRun && missingPaths.length > 0) { await conn.beginTransaction(); try { for (const methodPath of missingPaths) { const defaults = buildPermissionDefaults(methodPath, templateRow); const permissionId = await insertPermission(conn, defaults); created.push({ methodPath, permissionId }); touchedPermissionIds.push(permissionId); } await conn.commit(); } catch (error) { await conn.rollback(); throw error; } } const latestMap = args.dryRun ? existingMap : await queryExistingPermissions(conn, methodPaths); for (const methodPath of methodPaths) { const permissionId = latestMap.get(methodPath); if (permissionId) touchedPermissionIds.push(permissionId); } const uniquePermissionIds = [ ...new Set(touchedPermissionIds) ]; let roleBindingCreated = 0; if (!args.dryRun) { for (const permissionId of uniquePermissionIds) { const createdBinding = await bindRolePermission(conn, args.roleId, permissionId); if (createdBinding) roleBindingCreated++; } } const summary = { mode: args.dryRun ? 'dry-run' : 'apply', roleId: args.roleId, totalAuthMethods: methodPaths.length, existingPermissionCount: existingMap.size, missingPermissionCount: missingPaths.length, createdPermissionCount: created.length, roleBindingCreated, sampleMissing: missingPaths.slice(0, 20), }; console.log('[sync-system-api-permission] summary'); console.log(JSON.stringify(summary, null, 2)); } finally { await conn.end(); } } main().catch(error => { console.error('[sync-system-api-permission] failed'); console.error(error && error.stack ? error.stack : String(error)); process.exit(1); });