362 lines
11 KiB
JavaScript
362 lines
11 KiB
JavaScript
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 normalizeRolePermissions(rawValue) {
|
|
if (rawValue === undefined || rawValue === null) {
|
|
return { allAccess: false, permissionIds: [] };
|
|
}
|
|
|
|
if (Array.isArray(rawValue)) {
|
|
const normalizedItems = rawValue.map(item => (typeof item === 'string' ? item.trim() : item));
|
|
if (normalizedItems.some(item => item === '*')) {
|
|
return { allAccess: true, permissionIds: [] };
|
|
}
|
|
|
|
const permissionIds = normalizedItems
|
|
.map(item => Number(item))
|
|
.filter(item => Number.isFinite(item) && item > 0)
|
|
.map(item => Math.floor(item));
|
|
|
|
return {
|
|
allAccess: false,
|
|
permissionIds: Array.from(new Set(permissionIds)).sort((a, b) => a - b),
|
|
};
|
|
}
|
|
|
|
if (typeof rawValue === 'number') {
|
|
return normalizeRolePermissions([ rawValue ]);
|
|
}
|
|
|
|
if (typeof rawValue === 'string') {
|
|
const trimmed = rawValue.trim();
|
|
if (!trimmed) {
|
|
return { allAccess: false, permissionIds: [] };
|
|
}
|
|
if (trimmed === '*') {
|
|
return { allAccess: true, permissionIds: [] };
|
|
}
|
|
|
|
try {
|
|
const parsed = JSON.parse(trimmed);
|
|
if (parsed !== rawValue) {
|
|
return normalizeRolePermissions(parsed);
|
|
}
|
|
} catch (_) {
|
|
// ignore parse errors and continue.
|
|
}
|
|
|
|
if (trimmed.includes(',')) {
|
|
return normalizeRolePermissions(trimmed.split(','));
|
|
}
|
|
|
|
return normalizeRolePermissions([ trimmed ]);
|
|
}
|
|
|
|
return { allAccess: false, permissionIds: [] };
|
|
}
|
|
|
|
function serializeRolePermissions(rawValue) {
|
|
const state = normalizeRolePermissions(rawValue);
|
|
return state.allAccess ? '*' : JSON.stringify(state.permissionIds);
|
|
}
|
|
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, status FROM wms_permission WHERE type = 'api' AND path IN (${placeholders})`,
|
|
methodPaths
|
|
);
|
|
|
|
const result = new Map();
|
|
for (const row of rows) {
|
|
result.set(row.path, {
|
|
id: Number(row.id),
|
|
status: Number(row.status),
|
|
});
|
|
}
|
|
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 activatePermission(conn, permissionId) {
|
|
const [ result ] = await conn.query(
|
|
'UPDATE wms_permission SET status = 1, update_at = NOW() WHERE id = ? AND status <> 1',
|
|
[ permissionId ]
|
|
);
|
|
return result.affectedRows > 0;
|
|
}
|
|
|
|
async function bindRolePermission(conn, roleId, permissionId) {
|
|
const [ roleRows ] = await conn.query(
|
|
'SELECT permissions FROM wms_role WHERE id = ? LIMIT 1',
|
|
[ roleId ]
|
|
);
|
|
const roleRow = roleRows[0];
|
|
if (!roleRow) {
|
|
throw new Error(`Role not found: ${roleId}`);
|
|
}
|
|
|
|
const currentState = normalizeRolePermissions(roleRow.permissions);
|
|
|
|
if (currentState.allAccess || currentState.permissionIds.includes(Number(permissionId))) {
|
|
return false;
|
|
}
|
|
|
|
const nextPermissions = [ ...currentState.permissionIds, Number(permissionId) ];
|
|
const [ result ] = await conn.query(
|
|
'UPDATE wms_role SET permissions = ?, updated_at = NOW() WHERE id = ?',
|
|
[ serializeRolePermissions(nextPermissions), roleId ]
|
|
);
|
|
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 disabledPaths = methodPaths.filter(item => {
|
|
const row = existingMap.get(item);
|
|
return row && Number(row.status) !== 1;
|
|
});
|
|
const created = [];
|
|
const reactivated = [];
|
|
const touchedPermissionIds = [];
|
|
|
|
if (!args.dryRun && (missingPaths.length > 0 || disabledPaths.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);
|
|
}
|
|
|
|
for (const methodPath of disabledPaths) {
|
|
const permissionRow = existingMap.get(methodPath);
|
|
if (!permissionRow || !permissionRow.id) {
|
|
continue;
|
|
}
|
|
|
|
const updated = await activatePermission(conn, permissionRow.id);
|
|
if (updated) {
|
|
reactivated.push({ methodPath, permissionId: permissionRow.id });
|
|
}
|
|
touchedPermissionIds.push(permissionRow.id);
|
|
}
|
|
|
|
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 permissionRow = latestMap.get(methodPath);
|
|
if (permissionRow && permissionRow.id) touchedPermissionIds.push(permissionRow.id);
|
|
}
|
|
|
|
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,
|
|
disabledPermissionCount: disabledPaths.length,
|
|
createdPermissionCount: created.length,
|
|
reactivatedPermissionCount: reactivated.length,
|
|
roleBindingCreated,
|
|
sampleMissing: missingPaths.slice(0, 20),
|
|
sampleDisabled: disabledPaths.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);
|
|
});
|