feat: 新增多插件 UI 支持及运行日志集中回传功能
本次提交包含多项功能更新: 1. 为多个插件(xq0002/0003/0004/0008/0010/0011/0020/0031_xq0032/0033/0035/0037/0045_xq0046/0047/0048)新增 UI 界面及配置支持 2. 新增运行日志集中回传功能,客户端自动上传运行日志到中心机集中存储 3. 新增插件分类字段支持,用于场景库分组管理 4. 优化 xq0034/0037/0048 等插件的功能及描述 5. 修复控制面响应兼容问题,支持新旧版本数据格式 6. 新增 xq0033 插件的状态存储模块,用于历史记录管理 7. 优化 CRM 登录窗口模式,支持全屏置顶
This commit is contained in:
@@ -33,7 +33,8 @@
|
||||
"tslib": "^2.8.1",
|
||||
"typeorm": "npm:@cool-midway/typeorm@0.3.20",
|
||||
"uuid": "^11.1.0",
|
||||
"ws": "^8.18.1"
|
||||
"ws": "^8.18.1",
|
||||
"typescript": "~5.8.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@midwayjs/bundle-helper": "^1.3.0",
|
||||
@@ -46,8 +47,7 @@
|
||||
"mwts": "^1.3.0",
|
||||
"mwtsc": "^1.15.1",
|
||||
"rimraf": "^6.0.1",
|
||||
"ts-jest": "^29.3.0",
|
||||
"typescript": "~5.8.2"
|
||||
"ts-jest": "^29.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
|
||||
@@ -4,15 +4,24 @@ import { CoolCacheStore } from '@cool-midway/core';
|
||||
import * as path from 'path';
|
||||
import { pCachePath, pUploadPath } from '../comm/path';
|
||||
import { availablePort } from '../comm/port';
|
||||
import { loadEnvFile } from '../modules/center/comm/env';
|
||||
|
||||
// 配置加载早于业务模块,这里显式加载 server/.env(幂等:进程已有变量优先),
|
||||
// 保证下方 DB/端口/Redis 的环境变量读取在服务器部署时生效。
|
||||
loadEnvFile();
|
||||
|
||||
// redis缓存(37du 启用:本地/生产共用 Redis 缓存,支持多实例)
|
||||
import { redisStore } from 'cache-manager-ioredis-yet';
|
||||
|
||||
// Redis 开关:CENTER_REDIS=0 时降级为本地文件缓存(内网机器无 Redis 也可跑)
|
||||
const useRedis = process.env.CENTER_REDIS !== '0';
|
||||
|
||||
export default {
|
||||
// 确保每个项目唯一,项目首次启动会自动生成
|
||||
keys: '585d0777-4f66-4cf2-a5d5-b8c3831f7441',
|
||||
koa: {
|
||||
port: availablePort(8001),
|
||||
// 生产固定端口:CENTER_PORT(如 8800);未配置时本地自动找空闲口(8001 起)
|
||||
port: parseInt(process.env.CENTER_PORT || '', 10) || availablePort(8001),
|
||||
},
|
||||
// 开启异步上下文管理
|
||||
asyncContextManager: {
|
||||
@@ -37,32 +46,30 @@ export default {
|
||||
fileSize: '200mb',
|
||||
whitelist: null,
|
||||
},
|
||||
// 缓存:Redis(37du 启用)。如本地无 Redis,可换回下方 CoolCacheStore 文件缓存
|
||||
// 缓存:Redis(默认启用,host/port/密码可用 CENTER_REDIS_HOST 等覆盖)。
|
||||
// 内网机器无 Redis 时在 server/.env 配 CENTER_REDIS=0 降级为下方 CoolCacheStore 文件缓存。
|
||||
cacheManager: {
|
||||
clients: {
|
||||
default: {
|
||||
store: redisStore,
|
||||
options: {
|
||||
port: 6379,
|
||||
host: '127.0.0.1',
|
||||
password: '',
|
||||
ttl: 0,
|
||||
db: 0,
|
||||
},
|
||||
},
|
||||
default: useRedis
|
||||
? {
|
||||
store: redisStore,
|
||||
options: {
|
||||
port: parseInt(process.env.CENTER_REDIS_PORT || '', 10) || 6379,
|
||||
host: process.env.CENTER_REDIS_HOST || '127.0.0.1',
|
||||
password: process.env.CENTER_REDIS_PASSWORD || '',
|
||||
ttl: 0,
|
||||
db: 0,
|
||||
},
|
||||
}
|
||||
: {
|
||||
store: CoolCacheStore,
|
||||
options: {
|
||||
path: pCachePath(),
|
||||
ttl: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
// cacheManager: {
|
||||
// clients: {
|
||||
// default: {
|
||||
// store: CoolCacheStore,
|
||||
// options: {
|
||||
// path: pCachePath(),
|
||||
// ttl: 0,
|
||||
// },
|
||||
// },
|
||||
// },
|
||||
// },
|
||||
cool: {
|
||||
// 已经插件化,本地文件上传查看 plugin/config.ts,其他云存储查看对应插件的使用
|
||||
file: {},
|
||||
|
||||
@@ -4,17 +4,18 @@ import { TenantSubscriber } from '../modules/base/db/tenant';
|
||||
|
||||
/**
|
||||
* 本地开发 npm run dev 读取的配置文件
|
||||
* DB 连接同生产支持 MYSQL_* 环境变量注入,未配置时走本地默认(127.0.0.1/cool)
|
||||
*/
|
||||
export default {
|
||||
typeorm: {
|
||||
dataSource: {
|
||||
default: {
|
||||
type: 'mysql',
|
||||
host: '127.0.0.1',
|
||||
port: 3306,
|
||||
username: 'root',
|
||||
password: '123456',
|
||||
database: 'cool',
|
||||
host: process.env.MYSQL_HOST || '127.0.0.1',
|
||||
port: parseInt(process.env.MYSQL_PORT || '', 10) || 3306,
|
||||
username: process.env.MYSQL_USER || 'root',
|
||||
password: process.env.MYSQL_PASSWORD || '123456',
|
||||
database: process.env.MYSQL_DATABASE || 'cool',
|
||||
// 自动建表 注意:线上部署的时候不要使用,有可能导致数据丢失
|
||||
synchronize: true,
|
||||
// 打印日志
|
||||
|
||||
@@ -4,18 +4,20 @@ import { entities } from '../entities';
|
||||
import { TenantSubscriber } from '../modules/base/db/tenant';
|
||||
|
||||
/**
|
||||
* 本地开发 npm run prod 读取的配置文件
|
||||
* 生产配置 npm start(NODE_ENV=production)读取
|
||||
* DB 连接支持 server/.env 环境变量注入(变量名对齐老 controlplane/.env):
|
||||
* MYSQL_HOST / MYSQL_PORT / MYSQL_USER / MYSQL_PASSWORD / MYSQL_DATABASE
|
||||
*/
|
||||
export default {
|
||||
typeorm: {
|
||||
dataSource: {
|
||||
default: {
|
||||
type: 'mysql',
|
||||
host: '127.0.0.1',
|
||||
port: 3306,
|
||||
username: 'root',
|
||||
password: '123456',
|
||||
database: 'cool',
|
||||
host: process.env.MYSQL_HOST || '127.0.0.1',
|
||||
port: parseInt(process.env.MYSQL_PORT || '', 10) || 3306,
|
||||
username: process.env.MYSQL_USER || 'root',
|
||||
password: process.env.MYSQL_PASSWORD || '123456',
|
||||
database: process.env.MYSQL_DATABASE || 'cool',
|
||||
// 自动建表 注意:线上部署的时候不要使用,有可能导致数据丢失
|
||||
synchronize: false,
|
||||
// 打印日志
|
||||
|
||||
@@ -21,6 +21,8 @@ import * as upload from '@midwayjs/upload';
|
||||
// import * as task from '@cool-midway/task';
|
||||
// import * as rpc from '@cool-midway/rpc';
|
||||
import { FileserverMonitorService } from './modules/center/service/fileserver-monitor';
|
||||
import { CenterLogService } from './modules/center/service/logstore';
|
||||
import { CenterRbacService } from './modules/center/service/rbac';
|
||||
|
||||
@Configuration({
|
||||
imports: [
|
||||
@@ -71,6 +73,26 @@ export class MainConfiguration {
|
||||
// 内网文件服务器离线监控(daemon 语义:随进程启停,异常不中断业务)
|
||||
const monitor = await this.app.getApplicationContext().getAsync(FileserverMonitorService);
|
||||
monitor.start();
|
||||
// 集中日志保留期清理(启动清理一次 + 周期清理,随进程启停)
|
||||
const logStore = await this.app.getApplicationContext().getAsync(CenterLogService);
|
||||
logStore.start();
|
||||
// 控制台 RBAC 幂等种子(initDB/initMenu=false,兜底超管角色、业务菜单、运行期账号)
|
||||
this.seedRbac();
|
||||
}
|
||||
|
||||
/** RBAC 种子:最多重试 3 次(等数据库连接就绪),失败仅记日志不阻断启动 */
|
||||
private seedRbac(attempt = 1) {
|
||||
this.app
|
||||
.getApplicationContext()
|
||||
.getAsync(CenterRbacService)
|
||||
.then(rbac => rbac.ensureSeed())
|
||||
.catch(e => {
|
||||
if (attempt < 3) {
|
||||
setTimeout(() => this.seedRbac(attempt + 1), 3000);
|
||||
return;
|
||||
}
|
||||
this.logger.error('[rbac] 控制台权限种子初始化失败:%s', (e as Error)?.message || e);
|
||||
});
|
||||
}
|
||||
|
||||
async onStop() {
|
||||
@@ -80,5 +102,11 @@ export class MainConfiguration {
|
||||
} catch (e) {
|
||||
/* ignore */
|
||||
}
|
||||
try {
|
||||
const logStore = await this.app.getApplicationContext().getAsync(CenterLogService);
|
||||
logStore.stop();
|
||||
} catch (e) {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,18 +14,19 @@ import * as entity11 from './modules/demo/entity/goods';
|
||||
import * as entity12 from './modules/center/entity/runtime';
|
||||
import * as entity13 from './modules/center/entity/resource';
|
||||
import * as entity14 from './modules/center/entity/plugin';
|
||||
import * as entity15 from './modules/center/entity/account';
|
||||
import * as entity16 from './modules/base/entity/base';
|
||||
import * as entity17 from './modules/base/entity/sys/user_role';
|
||||
import * as entity18 from './modules/base/entity/sys/user';
|
||||
import * as entity19 from './modules/base/entity/sys/role_menu';
|
||||
import * as entity20 from './modules/base/entity/sys/role_department';
|
||||
import * as entity21 from './modules/base/entity/sys/role';
|
||||
import * as entity22 from './modules/base/entity/sys/param';
|
||||
import * as entity23 from './modules/base/entity/sys/menu';
|
||||
import * as entity24 from './modules/base/entity/sys/log';
|
||||
import * as entity25 from './modules/base/entity/sys/department';
|
||||
import * as entity26 from './modules/base/entity/sys/conf';
|
||||
import * as entity15 from './modules/center/entity/dict';
|
||||
import * as entity16 from './modules/center/entity/account';
|
||||
import * as entity17 from './modules/base/entity/base';
|
||||
import * as entity18 from './modules/base/entity/sys/user_role';
|
||||
import * as entity19 from './modules/base/entity/sys/user';
|
||||
import * as entity20 from './modules/base/entity/sys/role_menu';
|
||||
import * as entity21 from './modules/base/entity/sys/role_department';
|
||||
import * as entity22 from './modules/base/entity/sys/role';
|
||||
import * as entity23 from './modules/base/entity/sys/param';
|
||||
import * as entity24 from './modules/base/entity/sys/menu';
|
||||
import * as entity25 from './modules/base/entity/sys/log';
|
||||
import * as entity26 from './modules/base/entity/sys/department';
|
||||
import * as entity27 from './modules/base/entity/sys/conf';
|
||||
export const entities = [
|
||||
...Object.values(entity0),
|
||||
...Object.values(entity1),
|
||||
@@ -54,4 +55,5 @@ export const entities = [
|
||||
...Object.values(entity24),
|
||||
...Object.values(entity25),
|
||||
...Object.values(entity26),
|
||||
...Object.values(entity27),
|
||||
];
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
export * from './comm/path';
|
||||
export * from './comm/port';
|
||||
export * from './comm/utils';
|
||||
export * from './modules/center/comm/env';
|
||||
export * from './config/config.default';
|
||||
export * from './modules/base/db/tenant';
|
||||
export * from './config/config.local';
|
||||
@@ -22,6 +23,7 @@ export * from './modules/demo/entity/goods';
|
||||
export * from './modules/center/entity/runtime';
|
||||
export * from './modules/center/entity/resource';
|
||||
export * from './modules/center/entity/plugin';
|
||||
export * from './modules/center/entity/dict';
|
||||
export * from './modules/center/entity/account';
|
||||
export * from './modules/base/entity/sys/user_role';
|
||||
export * from './modules/base/entity/sys/user';
|
||||
@@ -35,12 +37,13 @@ export * from './modules/base/entity/sys/department';
|
||||
export * from './modules/base/entity/sys/conf';
|
||||
export * from './entities';
|
||||
export * from './config/config.prod';
|
||||
export * from './modules/center/comm/env';
|
||||
export * from './modules/center/comm/conf';
|
||||
export * from './modules/center/service/crypto';
|
||||
export * from './modules/center/service/dingtalk';
|
||||
export * from './modules/center/service/notify';
|
||||
export * from './modules/center/service/fileserver-monitor';
|
||||
export * from './modules/center/service/logstore';
|
||||
export * from './modules/center/service/rbac';
|
||||
export * from './interface';
|
||||
export * from './modules/base/service/sys/conf';
|
||||
export * from './modules/base/service/sys/log';
|
||||
@@ -83,6 +86,7 @@ export * from './modules/center/config';
|
||||
export * from './modules/center/service/auth';
|
||||
export * from './modules/center/controller/admin/account';
|
||||
export * from './modules/center/controller/admin/auth';
|
||||
export * from './modules/center/controller/admin/dict';
|
||||
export * from './modules/center/controller/admin/menu';
|
||||
export * from './modules/center/controller/admin/ops';
|
||||
export * from './modules/center/controller/admin/plugin';
|
||||
@@ -91,6 +95,7 @@ export * from './modules/center/controller/api/creds';
|
||||
export * from './modules/center/controller/api/device';
|
||||
export * from './modules/center/controller/api/exchange';
|
||||
export * from './modules/center/controller/api/fileserver';
|
||||
export * from './modules/center/controller/api/log';
|
||||
export * from './modules/center/controller/api/me';
|
||||
export * from './modules/center/controller/api/misc';
|
||||
export * from './modules/center/controller/api/ping';
|
||||
|
||||
@@ -17,6 +17,14 @@ export const PKG_DIR = path.join(CENTER_DATA_DIR, 'packages');
|
||||
export const SHELL_DIR = path.join(CENTER_DATA_DIR, 'shell');
|
||||
export const AVATAR_DIR = path.join(CENTER_DATA_DIR, 'avatars');
|
||||
|
||||
/** 集中日志存储:客户端回传的壳日志(logs/shell/<device_id>.log)+ 运行日志导出等 */
|
||||
export const LOGS_DIR = path.join(CENTER_DATA_DIR, 'logs');
|
||||
export const SHELL_LOGS_DIR = path.join(LOGS_DIR, 'shell');
|
||||
/** 集中日志保留天数:超期 run_logs / 设备壳日志自动清理(默认 30 天,env 可配) */
|
||||
export const LOG_RETENTION_DAYS = Number(process.env.LOG_RETENTION_DAYS || 30) || 30;
|
||||
/** 壳日志增量上传单次体积上限(字节):防单次上传灌爆(客户端按增量上传,正常远小于该值) */
|
||||
export const SHELL_LOG_CHUNK_MAX = 4 * 1024 * 1024;
|
||||
|
||||
/** 离线授权票据有效期(天):执行机最多离线该天数 */
|
||||
export const LICENSE_TTL_DAYS = 7;
|
||||
|
||||
|
||||
@@ -1,3 +1,19 @@
|
||||
import * as fs from 'fs';
|
||||
|
||||
/**
|
||||
* 读取 @midwayjs/upload 的上传内容为 Buffer。
|
||||
* 注意:默认 mode='file' 时 file.data 是上传临时文件的**路径字符串**(不是二进制),
|
||||
* 直接当 Buffer 落盘会写入一段路径文本(插件包变成 76 字节文本 → 执行机报「不是合法 ZIP」)。
|
||||
* mode='stream' 时 data 才是可读流;这里兼容 Buffer / 路径 / 流三种形态。
|
||||
*/
|
||||
export function readUploadFile(file: any): Buffer {
|
||||
if (!file) return null;
|
||||
const data = file.data ?? file.filepath;
|
||||
if (Buffer.isBuffer(data)) return data;
|
||||
if (typeof data === 'string' && data) return fs.readFileSync(data);
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一分页边界(对齐 core/paging.py page_bounds 的换算;返回 [limit, offset])。
|
||||
* 注意:调用方均按 `LIMIT ? OFFSET ?` / `slice(offset, offset + limit)` 消费,
|
||||
|
||||
@@ -2,7 +2,9 @@ import { CoolController, BaseController } from '@cool-midway/core';
|
||||
import { Body, Get, Headers, Inject, Post, Provide, Query } from '@midwayjs/core';
|
||||
import { InjectEntityModel } from '@midwayjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import * as md5 from 'md5';
|
||||
import { AccountEntity } from '../../entity/account';
|
||||
import { BaseSysUserEntity } from '../../../base/entity/sys/user';
|
||||
import { PluginEntity, AccountPluginEntity, AccountPlatformEntity } from '../../entity/plugin';
|
||||
import { CenterAuthService, ApiError } from '../../service/auth';
|
||||
import { hashPassword } from '../../service/crypto';
|
||||
@@ -39,7 +41,7 @@ export class AdminAccountController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
await this.centerAuthService.requirePerms('center:account:list', xAdminToken, xApiToken);
|
||||
const [limit, offset] = pageBounds(page, pageSize);
|
||||
const cond: string[] = [];
|
||||
const args: any[] = [];
|
||||
@@ -88,7 +90,7 @@ export class AdminAccountController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
const login = await this.centerAuthService.requirePerms('center:account:list', xAdminToken, xApiToken);
|
||||
const account = (a?.account || '').trim();
|
||||
if (!account || !a?.password) throw new ApiError(400, 'account 与 password 必填');
|
||||
if (String(a.password).length < 8) throw new ApiError(400, '密码至少 8 位');
|
||||
@@ -103,6 +105,8 @@ export class AdminAccountController extends BaseController {
|
||||
dept: (a?.dept || '').trim(),
|
||||
nickname: (a?.nickname || '').trim(),
|
||||
});
|
||||
// 同步控制台登录身份源(客户端账号密码登录校验 base_sys_user)
|
||||
await this.syncLoginUser(account, String(a.password), (a?.nickname || '').trim());
|
||||
await this.centerAuthService.audit(login, 'account-create', account,
|
||||
`is_admin=${Number(!!a.is_admin)}, dept=${(a?.dept || '').trim()}`);
|
||||
return { ok: true, account, dept: (a?.dept || '').trim(), nickname: (a?.nickname || '').trim(), is_admin: !!a.is_admin };
|
||||
@@ -115,7 +119,7 @@ export class AdminAccountController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
const login = await this.centerAuthService.requirePerms('center:account:list', xAdminToken, xApiToken);
|
||||
const account = (a?.account || '').trim();
|
||||
if (!account) throw new ApiError(400, 'account 必填');
|
||||
const exists = await this.accountRepo.findOneBy({ account });
|
||||
@@ -149,7 +153,7 @@ export class AdminAccountController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
const login = await this.centerAuthService.requirePerms('center:account:list', xAdminToken, xApiToken);
|
||||
const account = (r?.account || '').trim();
|
||||
if (!account || !r?.new_password) throw new ApiError(400, 'account 与新密码必填');
|
||||
if (String(r.new_password).length < 8) throw new ApiError(400, '新密码至少 8 位');
|
||||
@@ -160,10 +164,41 @@ export class AdminAccountController extends BaseController {
|
||||
'UPDATE accounts SET password_hash = ?, salt = ?, must_change_pwd = 1 WHERE account = ?',
|
||||
[hash, salt, account]
|
||||
);
|
||||
// 登录身份源在 base_sys_user(客户端账号密码登录校验此表,md5),重置必须双写,否则客户端登录不了
|
||||
await this.syncLoginUser(account, String(r.new_password), exists.nickname || '');
|
||||
// 清登录失败计数,避免重置后仍被防爆破临时锁定
|
||||
await this.centerAuthService.authReset(account);
|
||||
await this.centerAuthService.audit(login, 'account-reset-pwd', account);
|
||||
return { ok: true, account };
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步控制台登录身份源 base_sys_user(客户端账号密码登录校验此表,md5)。
|
||||
* accounts 是执行机业务账号(hash+salt,仅登记用,无登录消费方),两表算法不同、必须双写。
|
||||
*/
|
||||
private async syncLoginUser(account: string, plainPwd: string, nickname: string): Promise<void> {
|
||||
const userRepo = this.accountRepo.manager.getRepository(BaseSysUserEntity);
|
||||
const exist = await userRepo.findOneBy({ username: account });
|
||||
const now = new Date();
|
||||
if (exist) {
|
||||
await userRepo.update(
|
||||
{ id: exist.id },
|
||||
{ password: md5(plainPwd), passwordV: Number(exist.passwordV || 0) + 1, updateTime: now } as any
|
||||
);
|
||||
} else {
|
||||
await userRepo.insert({
|
||||
username: account,
|
||||
password: md5(plainPwd),
|
||||
nickName: nickname || account,
|
||||
status: 1,
|
||||
passwordV: 1,
|
||||
remark: '由账号管理同步',
|
||||
createTime: now,
|
||||
updateTime: now,
|
||||
} as any);
|
||||
}
|
||||
}
|
||||
|
||||
/** POST /api/admin/account/delete */
|
||||
@Post('/account/delete')
|
||||
async accountDelete(
|
||||
@@ -171,7 +206,7 @@ export class AdminAccountController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
const login = await this.centerAuthService.requirePerms('center:account:list', xAdminToken, xApiToken);
|
||||
const account = (d?.account || '').trim();
|
||||
if (!account) throw new ApiError(400, 'account 必填');
|
||||
if (account === login) throw new ApiError(400, '不能删除当前登录的账号');
|
||||
@@ -190,7 +225,8 @@ export class AdminAccountController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
const login = await this.centerAuthService.requirePerms(
|
||||
['center:account:list', 'center:grant:list'], xAdminToken, xApiToken);
|
||||
const account = (g?.account || '').trim();
|
||||
const pluginId = (g?.plugin_id || '').trim();
|
||||
if (!account || !pluginId) throw new ApiError(400, 'account 与 plugin_id 不能为空');
|
||||
@@ -221,7 +257,8 @@ export class AdminAccountController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
const login = await this.centerAuthService.requirePerms(
|
||||
['center:account:list', 'center:grant:list'], xAdminToken, xApiToken);
|
||||
const account = (g?.account || '').trim();
|
||||
const platformId = (g?.platform_id || '').trim();
|
||||
if (!account || !platformId) throw new ApiError(400, 'account 与 platform_id 不能为空');
|
||||
|
||||
@@ -2,15 +2,18 @@ import { CoolController, BaseController } from '@cool-midway/core';
|
||||
import { Body, Get, Headers, Inject, Post, Provide } from '@midwayjs/core';
|
||||
import { InjectEntityModel } from '@midwayjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import * as md5 from 'md5';
|
||||
import { AccountEntity } from '../../entity/account';
|
||||
import { CenterAuthService, ApiError } from '../../service/auth';
|
||||
import { hashPassword, verifyPassword, signAdminToken } from '../../service/crypto';
|
||||
import { CenterRbacService } from '../../service/rbac';
|
||||
import { signAdminToken } from '../../service/crypto';
|
||||
|
||||
/**
|
||||
* 管理面登录/身份(对齐旧 FastAPI apis/auth.py + 壳子 server.js 代理)
|
||||
* 管理面登录/身份(RBAC 版)
|
||||
* 身份源:base_sys_user(cool RBAC),不再查 accounts(accounts 仅执行机业务账号)。
|
||||
* - POST /api/admin/auth:账号密码登录(公开入口)→ 签发 X-Admin-Token + 云令牌
|
||||
* - GET /api/admin/me:当前账号信息
|
||||
* - POST /api/admin/password:自助改密(旧密码校验)
|
||||
* - POST /api/admin/password:自助改密(原密码校验,base_sys_user passwordV+1)
|
||||
* - POST /api/admin/logout:退出(壳子代理调用,简单返回 ok)
|
||||
* - GET /api/admin/platforms:可授权平台列表(管理员)
|
||||
*/
|
||||
@@ -25,36 +28,52 @@ export class AdminAuthController extends BaseController {
|
||||
@Inject()
|
||||
centerAuthService: CenterAuthService;
|
||||
|
||||
@Inject()
|
||||
centerRbacService: CenterRbacService;
|
||||
|
||||
@InjectEntityModel(AccountEntity)
|
||||
accountRepo: Repository<AccountEntity>;
|
||||
|
||||
/** POST /api/admin/auth — 统一账户登录 */
|
||||
/** POST /api/admin/auth — 统一账户登录(base_sys_user + md5) */
|
||||
@Post('/auth')
|
||||
async auth(
|
||||
@Body() a: any,
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
async auth(@Body() a: any) {
|
||||
const account = (a?.account || '').trim();
|
||||
if (!account) throw new ApiError(400, 'account 不能为空');
|
||||
await this.centerAuthService.authGate(account);
|
||||
const row = await this.accountRepo.findOneBy({ account });
|
||||
if (!row || !verifyPassword(a?.password || '', row.salt, row.passwordHash)) {
|
||||
const user = await this.centerRbacService.getUserByUsername(account);
|
||||
if (!user) {
|
||||
// 业务工号(accounts 已建号)尚未同步控制台登录凭据时,给出可行动的提示
|
||||
const acct = await this.accountRepo.findOneBy({ account });
|
||||
await this.centerAuthService.authFail(account);
|
||||
throw new ApiError(401, acct ? '该账号尚未开通控制台登录密码,请联系管理员重置密码' : '账号或密码错误');
|
||||
}
|
||||
if (String(user.password || '') !== md5(String(a?.password || ''))) {
|
||||
await this.centerAuthService.authFail(account);
|
||||
throw new ApiError(401, '账号或密码错误');
|
||||
}
|
||||
if (!Number(row.status)) throw new ApiError(403, '账号已停用,请联系管理员');
|
||||
if (!Number(user.status)) throw new ApiError(403, '账号已停用,请联系管理员');
|
||||
await this.centerAuthService.authReset(account);
|
||||
const nickname = row.nickname || '';
|
||||
|
||||
const ctx = await this.centerRbacService.context(account);
|
||||
const isAdmin = !!ctx?.isAdmin;
|
||||
const nickname = user.nickName || user.name || user.username;
|
||||
const dept = await this.centerRbacService.deptName(user.departmentId);
|
||||
// 云令牌只对 accounts(执行机业务账号)有意义:cloudAccount() 会 innerJoin accounts
|
||||
const acctRow = await this.accountRepo.findOneBy({ account });
|
||||
const cloudToken = acctRow
|
||||
? await this.centerAuthService.issueCloudToken(account, nickname)
|
||||
: '';
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
account,
|
||||
is_admin: !!Number(row.isAdmin),
|
||||
dept: row.dept || '',
|
||||
is_admin: isAdmin,
|
||||
dept,
|
||||
nickname,
|
||||
avatar: row.avatar || '',
|
||||
must_change_pwd: !!Number(row.mustChangePwd),
|
||||
avatar: user.headImg || '',
|
||||
must_change_pwd: false,
|
||||
token: signAdminToken(account),
|
||||
cloud_token: await this.centerAuthService.issueCloudToken(account, nickname),
|
||||
cloud_token: cloudToken,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -74,19 +93,22 @@ export class AdminAuthController extends BaseController {
|
||||
}
|
||||
// 无效身份 → 401(触发前端自动登出回登录页,避免 200-空被误判为已登录)
|
||||
if (!account) throw new ApiError(401, '登录态无效或已过期,请重新登录');
|
||||
const row = await this.accountRepo.findOneBy({ account });
|
||||
if (!row || !Number(row.status)) throw new ApiError(401, '登录态无效或已过期,请重新登录');
|
||||
const ctx = await this.centerRbacService.context(account);
|
||||
if (!ctx || !Number(ctx.user.status)) {
|
||||
throw new ApiError(401, '登录态无效或已过期,请重新登录');
|
||||
}
|
||||
const user = ctx.user;
|
||||
return {
|
||||
account,
|
||||
is_admin: !!Number(row.isAdmin),
|
||||
dept: row.dept || '',
|
||||
nickname: row.nickname || '',
|
||||
avatar: row.avatar || '',
|
||||
must_change_pwd: !!Number(row.mustChangePwd),
|
||||
account: user.username,
|
||||
is_admin: !!ctx.isAdmin,
|
||||
dept: await this.centerRbacService.deptName(user.departmentId),
|
||||
nickname: user.nickName || user.name || user.username,
|
||||
avatar: user.headImg || '',
|
||||
must_change_pwd: false,
|
||||
};
|
||||
}
|
||||
|
||||
/** POST /api/admin/password — 自助改密 */
|
||||
/** POST /api/admin/password — 自助改密(base_sys_user) */
|
||||
@Post('/password')
|
||||
async password(
|
||||
@Body() p: any,
|
||||
@@ -106,15 +128,18 @@ export class AdminAuthController extends BaseController {
|
||||
}
|
||||
if (String(p.new_password).length < 8) throw new ApiError(400, '新密码至少 8 位');
|
||||
if (p.account !== login) throw new ApiError(403, '只能修改自己的密码');
|
||||
const row = await this.accountRepo.findOneBy({ account: login });
|
||||
const row = await this.centerRbacService.getUserByUsername(login);
|
||||
if (!row) throw new ApiError(401, '账号不存在');
|
||||
if (!row.salt || !verifyPassword(p.old_password || '', row.salt, row.passwordHash)) {
|
||||
if (String(row.password || '') !== md5(String(p.old_password || ''))) {
|
||||
throw new ApiError(401, '原密码错误');
|
||||
}
|
||||
const { hash, salt } = hashPassword(p.new_password);
|
||||
await this.accountRepo.manager.query(
|
||||
'UPDATE accounts SET password_hash = ?, salt = ?, must_change_pwd = 0 WHERE account = ?',
|
||||
[hash, salt, login]
|
||||
await this.centerRbacService.userRepo.update(
|
||||
{ id: row.id },
|
||||
{
|
||||
password: md5(String(p.new_password)),
|
||||
passwordV: Number(row.passwordV || 0) + 1,
|
||||
updateTime: new Date(),
|
||||
} as any
|
||||
);
|
||||
return { ok: true, account: login };
|
||||
}
|
||||
@@ -131,7 +156,7 @@ export class AdminAuthController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
await this.centerAuthService.requireLogin(xAdminToken, xApiToken);
|
||||
return { platforms: CONTROLPLANE_PLATFORMS };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
import { CoolController, BaseController } from '@cool-midway/core';
|
||||
import { Body, Del, Get, Headers, Inject, Param, Post, Provide, Put } from '@midwayjs/core';
|
||||
import { InjectEntityModel } from '@midwayjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { DictItemEntity } from '../../entity/dict';
|
||||
import { CenterAuthService, ApiError } from '../../service/auth';
|
||||
|
||||
/** 字典标识仅允许小写字母/数字/下划线 */
|
||||
const DICT_KEY_RE = /^[a-z][a-z0-9_]{0,63}$/;
|
||||
|
||||
/** 场景分类默认项:字典为空时一次性初始化(现网已有分类一并自动收录) */
|
||||
const DEFAULT_PLUGIN_CATEGORIES = ['人事考勤', '考勤', '人事', '人事绩效', '社保', '报表', '财务'];
|
||||
const SEED_DICT_KEY = 'plugin_category';
|
||||
|
||||
/**
|
||||
* 控制台字典(可维护枚举,如场景分类)
|
||||
* - GET /api/admin/dict/:key/items 列表(sort,id 升序)
|
||||
* - POST /api/admin/dict/:key/items 新增 { label }
|
||||
* - PUT /api/admin/dict/:key/items/:id 改名 { label } / 上移下移 { move: 'up'|'down' }
|
||||
* - DEL /api/admin/dict/:key/items/:id 删除
|
||||
* 权限跟随插件管理(center:plugin:list):字典项当前即场景分类,供插件页内维护。
|
||||
*/
|
||||
@Provide()
|
||||
@CoolController('/api/admin')
|
||||
export class AdminDictController extends BaseController {
|
||||
@Inject()
|
||||
centerAuthService: CenterAuthService;
|
||||
|
||||
@InjectEntityModel(DictItemEntity)
|
||||
dictRepo: Repository<DictItemEntity>;
|
||||
|
||||
/** GET /api/admin/dict/:key/items */
|
||||
@Get('/dict/:key/items')
|
||||
async items(
|
||||
@Param('key') key: string = '',
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
await this.centerAuthService.requirePerms('center:plugin:list', xAdminToken, xApiToken);
|
||||
const k = this.normKey(key);
|
||||
await this.ensureSeeded(k);
|
||||
const rows = await this.dictRepo
|
||||
.createQueryBuilder('d')
|
||||
.where('d.dictKey = :k', { k })
|
||||
.orderBy('d.sort', 'ASC')
|
||||
.addOrderBy('d.id', 'ASC')
|
||||
.getMany();
|
||||
return { items: rows.map(r => ({ id: Number(r.id), label: r.label, sort: r.sort })) };
|
||||
}
|
||||
|
||||
/** POST /api/admin/dict/:key/items — 新增字典项 */
|
||||
@Post('/dict/:key/items')
|
||||
async addItem(
|
||||
@Param('key') key: string = '',
|
||||
@Body() b: any,
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
const login = await this.centerAuthService.requirePerms('center:plugin:list', xAdminToken, xApiToken);
|
||||
const k = this.normKey(key);
|
||||
const label = String(b?.label || '').trim();
|
||||
this.checkLabel(label);
|
||||
await this.ensureSeeded(k);
|
||||
const dup = await this.dictRepo.findOneBy({ dictKey: k, label });
|
||||
if (dup) throw new ApiError(400, `字典项「${label}」已存在`);
|
||||
const max: any = await this.dictRepo
|
||||
.createQueryBuilder('d')
|
||||
.select('COALESCE(MAX(d.sort), -1)', 'max')
|
||||
.where('d.dictKey = :k', { k })
|
||||
.getRawOne();
|
||||
const sort = Number(max?.max ?? -1) + 1;
|
||||
const r = await this.dictRepo.insert({ dictKey: k, label, sort });
|
||||
await this.centerAuthService.audit(login, 'dict-add', `${k}:${label}`);
|
||||
return { ok: true, id: Number(r.identifiers?.[0]?.id || 0), label, sort };
|
||||
}
|
||||
|
||||
/** PUT /api/admin/dict/:key/items/:id — 改名 / 排序 */
|
||||
@Put('/dict/:key/items/:id')
|
||||
async updateItem(
|
||||
@Param('key') key: string = '',
|
||||
@Param('id') id: any,
|
||||
@Body() b: any,
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
const login = await this.centerAuthService.requirePerms('center:plugin:list', xAdminToken, xApiToken);
|
||||
const k = this.normKey(key);
|
||||
const itemId = Number(id || 0);
|
||||
const row = await this.dictRepo.findOneBy({ dictKey: k, id: itemId });
|
||||
if (!row) throw new ApiError(404, '字典项不存在');
|
||||
|
||||
if (b?.move === 'up' || b?.move === 'down') {
|
||||
const rows = await this.dictRepo
|
||||
.createQueryBuilder('d')
|
||||
.where('d.dictKey = :k', { k })
|
||||
.orderBy('d.sort', 'ASC')
|
||||
.addOrderBy('d.id', 'ASC')
|
||||
.getMany();
|
||||
const idx = rows.findIndex(r => Number(r.id) === itemId);
|
||||
const j = b.move === 'up' ? idx - 1 : idx + 1;
|
||||
if (idx >= 0 && j >= 0 && j < rows.length) {
|
||||
const a = rows[idx];
|
||||
const c = rows[j];
|
||||
await this.dictRepo.update({ id: a.id }, { sort: c.sort });
|
||||
await this.dictRepo.update({ id: c.id }, { sort: a.sort });
|
||||
}
|
||||
await this.centerAuthService.audit(login, 'dict-move', `${k}:${row.label} ${b.move}`);
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
if (b?.label !== undefined) {
|
||||
const label = String(b.label || '').trim();
|
||||
this.checkLabel(label);
|
||||
if (label !== row.label) {
|
||||
const dup = await this.dictRepo.findOneBy({ dictKey: k, label });
|
||||
if (dup) throw new ApiError(400, `字典项「${label}」已存在`);
|
||||
await this.dictRepo.update({ id: itemId }, { label });
|
||||
await this.centerAuthService.audit(login, 'dict-rename', `${k}:${row.label} → ${label}`);
|
||||
}
|
||||
return { ok: true };
|
||||
}
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
/** DEL /api/admin/dict/:key/items/:id — 删除字典项(不影响已引用该值的插件) */
|
||||
@Del('/dict/:key/items/:id')
|
||||
async delItem(
|
||||
@Param('key') key: string = '',
|
||||
@Param('id') id: any,
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
const login = await this.centerAuthService.requirePerms('center:plugin:list', xAdminToken, xApiToken);
|
||||
const k = this.normKey(key);
|
||||
const itemId = Number(id || 0);
|
||||
const row = await this.dictRepo.findOneBy({ dictKey: k, id: itemId });
|
||||
if (!row) throw new ApiError(404, '字典项不存在');
|
||||
await this.dictRepo.delete({ id: itemId });
|
||||
await this.centerAuthService.audit(login, 'dict-delete', `${k}:${row.label}`);
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
private normKey(key: string): string {
|
||||
const k = String(key || '').trim();
|
||||
if (!DICT_KEY_RE.test(k)) throw new ApiError(400, '字典标识仅允许小写字母/数字/下划线');
|
||||
return k;
|
||||
}
|
||||
|
||||
private checkLabel(label: string): void {
|
||||
if (!label) throw new ApiError(400, '字典项名称不能为空');
|
||||
if (label.length > 64) throw new ApiError(400, '字典项名称过长(≤64 字符)');
|
||||
}
|
||||
|
||||
/** 场景分类字典空表时一次性初始化:默认项 + 现网 plugins.category 自动收录(幂等) */
|
||||
private async ensureSeeded(k: string): Promise<void> {
|
||||
if (k !== SEED_DICT_KEY) return;
|
||||
const cnt = await this.dictRepo.createQueryBuilder('d').where('d.dictKey = :k', { k }).getCount();
|
||||
if (cnt > 0) return;
|
||||
const m = this.dictRepo.manager;
|
||||
for (let i = 0; i < DEFAULT_PLUGIN_CATEGORIES.length; i++) {
|
||||
await m.query(
|
||||
`INSERT IGNORE INTO dict_items(dict_key, label, sort) VALUES (?, ?, ?)`,
|
||||
[k, DEFAULT_PLUGIN_CATEGORIES[i], i]
|
||||
);
|
||||
}
|
||||
const rows: any[] = await m.query(
|
||||
`SELECT DISTINCT category FROM plugins WHERE category IS NOT NULL AND category <> '' ORDER BY category`
|
||||
);
|
||||
let sort = 100;
|
||||
for (const r of rows) {
|
||||
const label = String(r.category || '').trim();
|
||||
if (!label) continue;
|
||||
await m.query(`INSERT IGNORE INTO dict_items(dict_key, label, sort) VALUES (?, ?, ?)`, [k, label, sort++]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,114 +1,22 @@
|
||||
import { CoolController, BaseController } from '@cool-midway/core';
|
||||
import { Get, Headers, Inject, Provide } from '@midwayjs/core';
|
||||
import { InjectEntityModel } from '@midwayjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { AccountEntity } from '../../entity/account';
|
||||
import { CenterAuthService, ApiError } from '../../service/auth';
|
||||
import { CenterRbacService } from '../../service/rbac';
|
||||
|
||||
/**
|
||||
* 控制台业务菜单(RBAC 驱动)。
|
||||
* - GET /api/admin/me/menus:返回当前操作者的业务菜单树 + 权限标识集合。
|
||||
* 管理员(is_admin=1)返回全量;非管理员按 cool-admin 角色权限过滤(预留,2F 用户体系落地后生效)。
|
||||
* - GET /api/admin/me/menus:按当前账号角色从 base_sys_menu 过滤组树,返回业务菜单树 + 权限标识集合。
|
||||
* 超管(admin 用户 / label='admin' 角色)返回全部;普通账号仅返回其角色勾选的菜单(含祖先自动补全)。
|
||||
* - 前端据此驱动动态路由与按钮权限("菜单要权限"落点)。
|
||||
*/
|
||||
|
||||
interface MenuNode {
|
||||
path: string;
|
||||
name: string;
|
||||
component: string;
|
||||
meta: {
|
||||
title: string;
|
||||
icon: string;
|
||||
perms: string[];
|
||||
roles?: string[];
|
||||
/** 侧栏隐藏(如个人中心,仅从用户菜单进入) */
|
||||
isHide?: boolean;
|
||||
};
|
||||
children?: MenuNode[];
|
||||
}
|
||||
|
||||
/** 控制台菜单目录(path/component 与前端视图一一对应;perms 为按钮/页面权限标识) */
|
||||
const CONSOLE_MENUS: MenuNode[] = [
|
||||
{
|
||||
path: '/overview', name: 'Overview', component: '/overview/index',
|
||||
meta: { title: '概览', icon: 'ri:pie-chart-line', perms: ['center:overview:view'] },
|
||||
},
|
||||
{
|
||||
path: '/stats', name: 'Stats', component: '/stats/index',
|
||||
meta: { title: '数据看板', icon: 'ri:bar-chart-2-line', perms: ['center:stats:view'] },
|
||||
},
|
||||
{
|
||||
path: '/plugins', name: 'Plugins', component: '/plugins/index',
|
||||
meta: { title: '插件管理', icon: 'ri:box-3-line', perms: ['center:plugin:list'] },
|
||||
},
|
||||
{
|
||||
path: '/accounts', name: 'Accounts', component: '/accounts/index',
|
||||
meta: { title: '账号管理', icon: 'ri:user-3-line', perms: ['center:account:list'] },
|
||||
},
|
||||
{
|
||||
path: '/grants', name: 'Grants', component: '/grants/index',
|
||||
meta: { title: '权限授权', icon: 'ri:key-2-line', perms: ['center:grant:list'] },
|
||||
},
|
||||
{
|
||||
path: '/audit', name: 'Audit', component: '/audit/index',
|
||||
meta: { title: '审计报表', icon: 'ri:file-list-3-line', perms: ['center:audit:list'] },
|
||||
},
|
||||
{
|
||||
path: '/reports', name: 'Reports', component: '/reports/index',
|
||||
meta: { title: '运行记录', icon: 'ri:terminal-box-line', perms: ['center:report:list'] },
|
||||
},
|
||||
{
|
||||
path: '/devices', name: 'Devices', component: '/devices/index',
|
||||
meta: { title: '执行机设备', icon: 'ri:computer-line', perms: ['center:device:list'] },
|
||||
},
|
||||
{
|
||||
path: '/upgrade', name: 'Upgrade', component: '/upgrade/index',
|
||||
meta: { title: '升级进度', icon: 'ri:rocket-2-line', perms: ['center:device:summary'] },
|
||||
},
|
||||
{
|
||||
path: '/notify', name: 'Notify', component: '/notify/index',
|
||||
meta: { title: '通知推送', icon: 'ri:notification-3-line', perms: ['center:notify:list'] },
|
||||
},
|
||||
{
|
||||
path: '/creds', name: 'Creds', component: '/creds/index',
|
||||
meta: { title: '敏感凭证', icon: 'ri:shield-keyhole-line', perms: ['center:creds:list'] },
|
||||
},
|
||||
{
|
||||
path: '/file-sources', name: 'FileSources', component: '/file-sources/index',
|
||||
meta: { title: '大文件源', icon: 'ri:database-2-line', perms: ['center:fileSource:list'] },
|
||||
},
|
||||
{
|
||||
// 嵌套菜单的父级 component 必须是布局容器(RoutesAlias.Layout='/index/index'),
|
||||
// 否则一级带 children 的路由不会包 Layout,子页面渲染不出(空白页)
|
||||
path: '/system', name: 'System', component: '/index/index',
|
||||
meta: { title: '系统管理', icon: 'ri:settings-3-line', perms: [] },
|
||||
children: [
|
||||
{ path: 'user', name: 'SysUser', component: '/system/user', meta: { title: '用户管理', icon: '', perms: ['center:sys:user'] } },
|
||||
{ path: 'role', name: 'SysRole', component: '/system/role', meta: { title: '角色管理', icon: '', perms: ['center:sys:role'] } },
|
||||
{ path: 'menu', name: 'SysMenu', component: '/system/menu', meta: { title: '菜单管理', icon: '', perms: ['center:sys:menu'] } },
|
||||
{ path: 'department', name: 'SysDept', component: '/system/department', meta: { title: '部门管理', icon: '', perms: ['center:sys:dept'] } },
|
||||
// 个人中心:从头像下拉进入,不在侧栏显示(自助改密 + 头像)
|
||||
{ path: 'user-center', name: 'UserCenter', component: '/system/user-center', meta: { title: '个人中心', icon: '', perms: [], isHide: true } },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
/** 全部权限标识集合(供按钮级 v-permission 使用) */
|
||||
function allPerms(nodes: MenuNode[]): string[] {
|
||||
const out: string[] = [];
|
||||
const walk = (ns: MenuNode[]) => ns.forEach(n => { out.push(...n.meta.perms); if (n.children) walk(n.children); });
|
||||
walk(nodes);
|
||||
return out;
|
||||
}
|
||||
|
||||
@Provide()
|
||||
@CoolController('/api/admin')
|
||||
export class AdminMenuController extends BaseController {
|
||||
@Inject()
|
||||
centerAuthService: CenterAuthService;
|
||||
|
||||
@InjectEntityModel(AccountEntity)
|
||||
accountRepo: Repository<AccountEntity>;
|
||||
@Inject()
|
||||
centerRbacService: CenterRbacService;
|
||||
|
||||
/** GET /api/admin/me/menus */
|
||||
@Get('/me/menus')
|
||||
@@ -126,13 +34,6 @@ export class AdminMenuController extends BaseController {
|
||||
}
|
||||
// 无效身份 → 401(触发前端自动登出,避免 200-空菜单被误判后跳 500)
|
||||
if (!account) throw new ApiError(401, '登录态无效或已过期,请重新登录');
|
||||
const row = await this.accountRepo.findOneBy({ account });
|
||||
if (!row || !Number(row.status)) throw new ApiError(401, '登录态无效或已过期,请重新登录');
|
||||
const isAdmin = !!Number(row.isAdmin);
|
||||
// 非管理员:按 cool-admin 角色权限过滤(2F 用户体系落地后生效;当前业务控制台仍以 is_admin 为准)
|
||||
if (isAdmin) {
|
||||
return { account, menus: CONSOLE_MENUS, perms: allPerms(CONSOLE_MENUS), is_admin: true };
|
||||
}
|
||||
return { account, menus: [], perms: [], is_admin: false };
|
||||
return this.centerRbacService.menusForUser(account);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,8 +14,9 @@ import { FileSourceEntity, FileserverStatusEntity } from '../../entity/resource'
|
||||
import { ClientCredEntity } from '../../entity/account';
|
||||
import { CenterAuthService, ApiError } from '../../service/auth';
|
||||
import { rsaEncrypt } from '../../service/crypto';
|
||||
import { CenterLogService } from '../../service/logstore';
|
||||
import { PKG_DIR, SHELL_DIR, AVATAR_DIR } from '../../comm/conf';
|
||||
import { pageBounds } from '../../comm/util';
|
||||
import { pageBounds, readUploadFile } from '../../comm/util';
|
||||
|
||||
const ALLOWED_CREDS_KEYS = ['DINGTALK_APPKEY', 'DINGTALK_APPSECRET', 'DINGTALK_AGENT_ID', 'DINGTALK_CORP_ID'];
|
||||
const SAFE_NAME_RE = /^[A-Za-z0-9._-]+$/;
|
||||
@@ -35,6 +36,9 @@ export class AdminOpsController extends BaseController {
|
||||
@Inject()
|
||||
centerAuthService: CenterAuthService;
|
||||
|
||||
@Inject()
|
||||
centerLogService: CenterLogService;
|
||||
|
||||
@InjectEntityModel(PluginEntity) pluginRepo: Repository<PluginEntity>;
|
||||
@InjectEntityModel(PluginVersionEntity) pluginVersionRepo: Repository<PluginVersionEntity>;
|
||||
@InjectEntityModel(AccountPluginEntity) accountPluginRepo: Repository<AccountPluginEntity>;
|
||||
@@ -53,7 +57,7 @@ export class AdminOpsController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
await this.centerAuthService.requirePerms('center:overview:view', xAdminToken, xApiToken);
|
||||
const plugins = await this.pluginRepo.find();
|
||||
const accounts = await this.accountRepo.find();
|
||||
const admins = (await this.accountRepo
|
||||
@@ -86,7 +90,7 @@ export class AdminOpsController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
await this.centerAuthService.requirePerms('center:stats:view', xAdminToken, xApiToken);
|
||||
const m = this.runtimeRepo.manager;
|
||||
const users: any = (await m.query(
|
||||
`SELECT (SELECT COUNT(*) FROM accounts) AS total,
|
||||
@@ -152,7 +156,7 @@ export class AdminOpsController extends BaseController {
|
||||
@Query('action') action: string = '', @Query('q') q: string = '',
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
await this.centerAuthService.requirePerms('center:audit:list', xAdminToken, xApiToken);
|
||||
const [limit, offset] = pageBounds(page, pageSize);
|
||||
const cond: string[] = [];
|
||||
const args: any[] = [];
|
||||
@@ -180,7 +184,7 @@ export class AdminOpsController extends BaseController {
|
||||
@Query('status') status: string = '', @Query('q') q: string = '',
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
await this.centerAuthService.requirePerms('center:report:list', xAdminToken, xApiToken);
|
||||
const [limit, offset] = pageBounds(page, pageSize);
|
||||
const cond: string[] = [];
|
||||
const args: any[] = [];
|
||||
@@ -216,7 +220,7 @@ export class AdminOpsController extends BaseController {
|
||||
@Query('page') page: number = 1, @Query('page_size') pageSize: number = 20,
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
await this.centerAuthService.requirePerms('center:device:list', xAdminToken, xApiToken);
|
||||
const [limit, offset] = pageBounds(page, pageSize);
|
||||
const m = this.deviceRepo.manager;
|
||||
const total: any = (await m.query('SELECT COUNT(*) AS c FROM devices'))[0];
|
||||
@@ -232,7 +236,7 @@ export class AdminOpsController extends BaseController {
|
||||
async devicesSummary(
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
await this.centerAuthService.requirePerms('center:device:list', xAdminToken, xApiToken);
|
||||
const m = this.deviceRepo.manager;
|
||||
const total: any = (await m.query('SELECT COUNT(*) AS c FROM devices'))[0];
|
||||
const byVersion: any[] = await m.query(
|
||||
@@ -305,11 +309,11 @@ export class AdminOpsController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
const login = await this.centerAuthService.requirePerms('center:device:summary', xAdminToken, xApiToken);
|
||||
version = (version || '').trim();
|
||||
if (!version) throw new ApiError(400, 'version 不能为空');
|
||||
if (!SAFE_NAME_RE.test(version)) throw new ApiError(400, 'version 仅允许字母数字及 . _ -');
|
||||
const content: Buffer = file?.data || (file?.filepath ? fs.readFileSync(file.filepath) : null);
|
||||
const content: Buffer = readUploadFile(file);
|
||||
if (!content || !content.length) throw new ApiError(400, '上传内容为空');
|
||||
if (content.length > 1024 * 1024 * 1024) throw new ApiError(413, '壳子安装包超过大小上限(1GB)');
|
||||
const filename = `setup-37du-host-${version}.exe`;
|
||||
@@ -330,7 +334,7 @@ export class AdminOpsController extends BaseController {
|
||||
@Query('page_size') pageSize: number = 20,
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
await this.centerAuthService.requirePerms('center:fileSource:list', xAdminToken, xApiToken);
|
||||
const qb = this.fileSourceRepo.createQueryBuilder('f');
|
||||
if ((category || '').trim()) qb.where('f.category = :c', { c: category.trim() });
|
||||
const rows = await qb.orderBy('f.id', 'DESC').getMany();
|
||||
@@ -348,7 +352,7 @@ export class AdminOpsController extends BaseController {
|
||||
@Body() b: any,
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
const login = await this.centerAuthService.requirePerms('center:fileSource:list', xAdminToken, xApiToken);
|
||||
const category = (b?.category || '').trim();
|
||||
const version = (b?.version || '').trim();
|
||||
const url = (b?.url || '').trim();
|
||||
@@ -375,7 +379,7 @@ export class AdminOpsController extends BaseController {
|
||||
@Body() b: any, @Param('fid') fid: any,
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
const login = await this.centerAuthService.requirePerms('center:fileSource:list', xAdminToken, xApiToken);
|
||||
const id = Number(fid || 0);
|
||||
if (b?.enabled === undefined && b?.enabled === null && b?.notes === undefined) {
|
||||
throw new ApiError(400, '无更新字段');
|
||||
@@ -398,7 +402,7 @@ export class AdminOpsController extends BaseController {
|
||||
@Param('fid') fid: any,
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
const login = await this.centerAuthService.requirePerms('center:fileSource:list', xAdminToken, xApiToken);
|
||||
const id = Number(fid || 0);
|
||||
const m = this.fileSourceRepo.manager;
|
||||
const r: any = await m.query('DELETE FROM file_sources WHERE id = ?', [id]);
|
||||
@@ -413,7 +417,7 @@ export class AdminOpsController extends BaseController {
|
||||
@Query('page') page: number = 1, @Query('page_size') pageSize: number = 20,
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
await this.centerAuthService.requirePerms('center:creds:list', xAdminToken, xApiToken);
|
||||
const [limit, offset] = pageBounds(page, pageSize);
|
||||
const m = this.clientCredRepo.manager;
|
||||
const total: any = (await m.query('SELECT COUNT(*) AS c FROM client_creds'))[0];
|
||||
@@ -436,7 +440,7 @@ export class AdminOpsController extends BaseController {
|
||||
@Body() b: any,
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
const login = await this.centerAuthService.requirePerms('center:creds:list', xAdminToken, xApiToken);
|
||||
const account = (b?.account || '').trim();
|
||||
if (!account) throw new ApiError(400, 'account 不能为空');
|
||||
const allowed: Record<string, string> = {};
|
||||
@@ -461,7 +465,7 @@ export class AdminOpsController extends BaseController {
|
||||
@Query('limit') limit: number = 15,
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
await this.centerAuthService.requireLogin(xAdminToken, xApiToken);
|
||||
const n = Math.max(1, Math.min(50, Number(limit) || 15));
|
||||
const rows: any[] = await this.notificationRepo.manager.query(
|
||||
`SELECT id, title, content, level, target, account, created_at, expires_at
|
||||
@@ -482,7 +486,7 @@ export class AdminOpsController extends BaseController {
|
||||
@Query('q') q: string = '',
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
await this.centerAuthService.requirePerms('center:notify:list', xAdminToken, xApiToken);
|
||||
const [limit, offset] = pageBounds(page, pageSize);
|
||||
const cond: string[] = [];
|
||||
const args: any[] = [];
|
||||
@@ -507,7 +511,7 @@ export class AdminOpsController extends BaseController {
|
||||
@Body() b: any,
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
const login = await this.centerAuthService.requirePerms('center:notify:list', xAdminToken, xApiToken);
|
||||
const title = (b?.title || '').trim();
|
||||
if (!title) throw new ApiError(400, '标题不能为空');
|
||||
if (!NOTIF_LEVELS.has(b?.level)) throw new ApiError(400, 'level 仅允许 info/warning/important');
|
||||
@@ -525,7 +529,7 @@ export class AdminOpsController extends BaseController {
|
||||
@Param('nid') nid: any, @Query('active') active: string = '',
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
const login = await this.centerAuthService.requirePerms('center:notify:list', xAdminToken, xApiToken);
|
||||
const id = Number(nid || 0);
|
||||
await this.notificationRepo.manager.query('UPDATE notifications SET active = ? WHERE id = ?', [Number(active === 'true'), id]);
|
||||
await this.centerAuthService.audit(login, 'notify-toggle', `通知 #${id} active=${active}`);
|
||||
@@ -537,7 +541,7 @@ export class AdminOpsController extends BaseController {
|
||||
@Param('nid') nid: any,
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
const login = await this.centerAuthService.requirePerms('center:notify:list', xAdminToken, xApiToken);
|
||||
const id = Number(nid || 0);
|
||||
await this.notificationRepo.manager.query('DELETE FROM notifications WHERE id = ?', [id]);
|
||||
await this.centerAuthService.audit(login, 'notify-delete', `通知 #${id}`);
|
||||
@@ -549,7 +553,7 @@ export class AdminOpsController extends BaseController {
|
||||
async fileserverStatus(
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
await this.centerAuthService.requirePerms('center:fileSource:list', xAdminToken, xApiToken);
|
||||
const rows = await this.fileserverRepo.find({ order: { lastSeen: 'DESC' } as any });
|
||||
return {
|
||||
// 契约对齐旧 FastAPI:键名 fileservers;status/offline_notified 布尔;total_size 数值
|
||||
@@ -582,11 +586,11 @@ export class AdminOpsController extends BaseController {
|
||||
account = (account || '').trim();
|
||||
if (!account) throw new ApiError(400, 'account 不能为空');
|
||||
if (!SAFE_NAME_RE.test(account)) throw new ApiError(400, 'account 含非法字符(仅允许字母数字及 . _ -)');
|
||||
if (account !== login) await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
if (account !== login) await this.centerAuthService.requirePerms('center:sys:user', xAdminToken, xApiToken);
|
||||
const filename = (file?.filename || '').toLowerCase();
|
||||
const ext = path.extname(filename);
|
||||
if (!AVATAR_EXT.includes(ext)) throw new ApiError(400, '仅支持图片格式(jpg/png/gif/webp)');
|
||||
const content: Buffer = file?.data || (file?.filepath ? fs.readFileSync(file.filepath) : null);
|
||||
const content: Buffer = readUploadFile(file);
|
||||
if (!content || !content.length || content.length > 2 * 1024 * 1024) throw new ApiError(400, '头像文件为空或超过 2MB');
|
||||
const acc = await this.accountRepo.findOneBy({ account });
|
||||
if (!acc) throw new ApiError(400, `账号 ${account} 不存在`);
|
||||
@@ -599,6 +603,94 @@ export class AdminOpsController extends BaseController {
|
||||
await this.accountRepo.update({ account }, { avatar: fname });
|
||||
return { ok: true, account, avatar: fname };
|
||||
}
|
||||
|
||||
// ==================== 集中日志(运行日志 / 客户端壳日志) ====================
|
||||
/** GET /api/admin/run-logs — 运行日志列表(分页 + 账号/设备/插件/状态/关键字/近N天筛选) */
|
||||
@Get('/run-logs')
|
||||
async runLogs(
|
||||
@Query('page') page: number = 1, @Query('page_size') pageSize: number = 20,
|
||||
@Query('account') account: string = '', @Query('device') device: string = '',
|
||||
@Query('plugin') plugin: string = '', @Query('status') status: string = '',
|
||||
@Query('q') q: string = '', @Query('days') days: number = 0,
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
await this.centerAuthService.requirePerms('center:log:list', xAdminToken, xApiToken);
|
||||
const r = await this.centerLogService.queryRunLogs({ page, pageSize, account, device, plugin, status, q, days });
|
||||
// 关联账号昵称(对齐旧接口)
|
||||
const nick: Record<string, string> = {};
|
||||
for (const a of await this.accountRepo.find()) nick[a.account] = a.nickname || '';
|
||||
return {
|
||||
items: r.items.map((x: any) => ({ ...x, nickname: nick[x.account] || '' })),
|
||||
total: r.total,
|
||||
};
|
||||
}
|
||||
|
||||
/** GET /api/admin/run-logs/:runId — 单次运行日志详情(含日志正文) */
|
||||
@Get('/run-logs/:runId')
|
||||
async runLogDetail(
|
||||
@Param('runId') runId: string,
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
await this.centerAuthService.requirePerms('center:log:list', xAdminToken, xApiToken);
|
||||
const row = await this.centerLogService.getRunLog(runId);
|
||||
if (!row) throw new ApiError(404, '未找到该运行日志');
|
||||
return row;
|
||||
}
|
||||
|
||||
/** GET /api/admin/device-logs — 已回传壳日志的设备列表 */
|
||||
@Get('/device-logs')
|
||||
async deviceLogs(
|
||||
@Query('page') page: number = 1, @Query('page_size') pageSize: number = 20,
|
||||
@Query('account') account: string = '', @Query('q') q: string = '',
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
await this.centerAuthService.requirePerms('center:log:list', xAdminToken, xApiToken);
|
||||
const r = await this.centerLogService.queryDeviceLogs({ page, pageSize, account, q });
|
||||
const nick: Record<string, string> = {};
|
||||
for (const a of await this.accountRepo.find()) nick[a.account] = a.nickname || '';
|
||||
return {
|
||||
items: r.items.map((x: any) => ({ ...x, nickname: nick[x.account] || '' })),
|
||||
total: r.total,
|
||||
};
|
||||
}
|
||||
|
||||
/** GET /api/admin/device-logs/:deviceId — 设备壳日志尾部内容(最多尾部 512KB) */
|
||||
@Get('/device-logs/:deviceId')
|
||||
async deviceLogDetail(
|
||||
@Param('deviceId') deviceId: string,
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
await this.centerAuthService.requirePerms('center:log:list', xAdminToken, xApiToken);
|
||||
const row = await this.centerLogService.getDeviceLog(deviceId);
|
||||
if (!row) throw new ApiError(404, '未找到该设备的壳日志');
|
||||
return row;
|
||||
}
|
||||
|
||||
/** GET /api/admin/device-logs/:deviceId/download — 设备壳日志全文下载 */
|
||||
@Get('/device-logs/:deviceId/download')
|
||||
async deviceLogDownload(
|
||||
@Param('deviceId') deviceId: string,
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
await this.centerAuthService.requirePerms('center:log:list', xAdminToken, xApiToken);
|
||||
const file = this.centerLogService.deviceLogFilePath(deviceId);
|
||||
if (!file) throw new ApiError(404, '未找到该设备的壳日志文件');
|
||||
this.ctx.attachment(`shell-${deviceId}.log`);
|
||||
this.ctx.type = 'text/plain; charset=utf-8';
|
||||
this.ctx.body = fs.createReadStream(file);
|
||||
}
|
||||
|
||||
/** POST /api/admin/logs/cleanup — 手动触发一次保留期清理 */
|
||||
@Post('/logs/cleanup')
|
||||
async logsCleanup(
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
const login = await this.centerAuthService.requirePerms('center:log:list', xAdminToken, xApiToken);
|
||||
const result = await this.centerLogService.cleanupExpired();
|
||||
await this.centerAuthService.audit(login, 'logs-cleanup', 'run-logs',
|
||||
`deleted_run_logs=${result.deleted_run_logs}, deleted_device_logs=${result.deleted_device_logs}`);
|
||||
return { ok: true, ...result };
|
||||
}
|
||||
}
|
||||
|
||||
function versionKey(v: string): number {
|
||||
|
||||
@@ -9,7 +9,7 @@ import * as AdmZip from 'adm-zip';
|
||||
import { PluginEntity, PluginVersionEntity, AccountPluginEntity } from '../../entity/plugin';
|
||||
import { CenterAuthService, ApiError } from '../../service/auth';
|
||||
import { PKG_DIR } from '../../comm/conf';
|
||||
import { pageBounds } from '../../comm/util';
|
||||
import { pageBounds, readUploadFile } from '../../comm/util';
|
||||
|
||||
const SAFE_NAME_RE = /^[A-Za-z0-9._-]+$/;
|
||||
|
||||
@@ -49,7 +49,7 @@ export class AdminPluginController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
await this.centerAuthService.requirePerms('center:plugin:list', xAdminToken, xApiToken);
|
||||
const [limit, offset] = pageBounds(page, pageSize);
|
||||
const cond: string[] = [];
|
||||
const args: any[] = [];
|
||||
@@ -104,7 +104,7 @@ export class AdminPluginController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
const login = await this.centerAuthService.requirePerms('center:plugin:list', xAdminToken, xApiToken);
|
||||
pluginId = (pluginId || '').trim();
|
||||
version = (version || '').trim();
|
||||
name = (name || '').trim() || pluginId;
|
||||
@@ -112,7 +112,7 @@ export class AdminPluginController extends BaseController {
|
||||
if (!SAFE_NAME_RE.test(pluginId) || !SAFE_NAME_RE.test(version)) {
|
||||
throw new ApiError(400, 'plugin_id/version 仅允许字母数字及 . _ -');
|
||||
}
|
||||
const content: Buffer = file?.data || (file?.filepath ? fs.readFileSync(file.filepath) : null);
|
||||
const content: Buffer = readUploadFile(file);
|
||||
if (!content || !content.length) throw new ApiError(400, '上传内容为空');
|
||||
if (content.length > 200 * 1024 * 1024) throw new ApiError(413, '插件包超过大小上限(200MB)');
|
||||
// 校验 zip + 提取 manifest(plugin.json 内 id 与路径 plugin_id 需一致)
|
||||
@@ -138,16 +138,24 @@ export class AdminPluginController extends BaseController {
|
||||
fs.writeFileSync(target, content);
|
||||
const sha256 = crypto.createHash('sha256').update(content).digest('hex');
|
||||
const manifestJson = JSON.stringify(manifest, null, 0) || '{}';
|
||||
// 插件主记录 upsert
|
||||
// 插件主记录 upsert(分类只在首次登记时取 plugin.json,之后以后台手动维护为准,不被新版本覆盖)
|
||||
await this.pluginRepo.manager.query(
|
||||
`INSERT INTO plugins(id, name, latest_version, description, category, icon, manifest)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
ON DUPLICATE KEY UPDATE name = VALUES(name), manifest = VALUES(manifest)
|
||||
${manifest.description !== undefined ? ', description = VALUES(description)' : ''}
|
||||
${manifest.category !== undefined ? ', category = VALUES(category)' : ''}
|
||||
${manifest.icon !== undefined ? ', icon = VALUES(icon)' : ''}`,
|
||||
[pluginId, name, version, manifest.description || '', manifest.category || '', manifest.icon || '', manifestJson]
|
||||
);
|
||||
// plugin.json 自带分类不在字典时自动收录进场景分类字典(幂等,重复项跳过)
|
||||
const cat = String(manifest.category || '').trim();
|
||||
if (cat) {
|
||||
await this.pluginRepo.manager.query(
|
||||
`INSERT IGNORE INTO dict_items(dict_key, label, sort)
|
||||
SELECT 'plugin_category', ?, COALESCE((SELECT MAX(sort) FROM dict_items WHERE dict_key = 'plugin_category'), -1) + 1`,
|
||||
[cat]
|
||||
);
|
||||
}
|
||||
await this.pluginVersionRepo.manager.query(
|
||||
`INSERT INTO plugin_versions(plugin_id, version, filename, uploaded_at, sha256, size_bytes)
|
||||
VALUES (?, ?, ?, NOW(), ?, ?)
|
||||
@@ -181,7 +189,7 @@ export class AdminPluginController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
const login = await this.centerAuthService.requirePerms('center:plugin:list', xAdminToken, xApiToken);
|
||||
const pid = (d?.plugin_id || '').trim();
|
||||
if (!pid) throw new ApiError(400, 'plugin_id 必填');
|
||||
const pl = await this.pluginRepo.findOneBy({ id: pid });
|
||||
@@ -207,13 +215,13 @@ export class AdminPluginController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
await this.centerAuthService.requirePerms('center:plugin:list', xAdminToken, xApiToken);
|
||||
const pid = (pluginId || '').trim();
|
||||
if (!pid) throw new ApiError(400, 'plugin_id 必填');
|
||||
const set: Record<string, any> = {};
|
||||
if (d?.name && String(d.name).trim()) set.name = String(d.name).trim();
|
||||
if (d?.description) set.description = String(d.description).trim();
|
||||
if (d?.category) set.category = String(d.category).trim();
|
||||
if (d?.category !== undefined) set.category = String(d.category ?? '').trim();
|
||||
if (d?.icon) set.icon = String(d.icon).trim();
|
||||
if (['published', 'disabled', 'revoked'].includes(d?.status)) set.status = d.status;
|
||||
if (d?.force_min_version && d?.force_deadline) {
|
||||
@@ -238,7 +246,8 @@ export class AdminPluginController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
await this.centerAuthService.requirePerms(
|
||||
['center:grant:list', 'center:plugin:list'], xAdminToken, xApiToken);
|
||||
const plugins = await this.pluginRepo
|
||||
.createQueryBuilder('p').select(['p.id', 'p.name', 'p.status']).orderBy('p.id', 'ASC').getMany();
|
||||
const accounts = await this.pluginRepo.manager.query(
|
||||
@@ -253,7 +262,8 @@ export class AdminPluginController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
await this.centerAuthService.requirePerms(
|
||||
['center:grant:list', 'center:plugin:list'], xAdminToken, xApiToken);
|
||||
account = (account || '').trim();
|
||||
const grants = await this.accountPluginRepo.findBy({ account });
|
||||
const platforms = await this.pluginRepo.manager.query(
|
||||
@@ -273,7 +283,8 @@ export class AdminPluginController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
await this.centerAuthService.requirePerms(
|
||||
['center:grant:list', 'center:plugin:list'], xAdminToken, xApiToken);
|
||||
pluginId = (pluginId || '').trim();
|
||||
if (!pluginId) throw new ApiError(400, 'plugin_id 不能为空');
|
||||
const pl = await this.pluginRepo.findOneBy({ id: pluginId });
|
||||
@@ -305,7 +316,8 @@ export class AdminPluginController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
const login = await this.centerAuthService.requirePerms(
|
||||
['center:grant:list', 'center:plugin:list'], xAdminToken, xApiToken);
|
||||
const pluginId = String(b?.plugin_id || '').trim();
|
||||
const items: any[] = Array.isArray(b?.items) ? b.items : [];
|
||||
if (!pluginId) throw new ApiError(400, 'plugin_id 不能为空');
|
||||
@@ -349,7 +361,8 @@ export class AdminPluginController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
const login = await this.centerAuthService.requirePerms(
|
||||
['center:grant:list', 'center:plugin:list'], xAdminToken, xApiToken);
|
||||
const pluginId = String(b?.plugin_id || '').trim();
|
||||
const accounts: string[] = Array.isArray(b?.accounts) ? b.accounts.map((a: any) => String(a || '').trim()).filter(Boolean) : [];
|
||||
if (!pluginId) throw new ApiError(400, 'plugin_id 不能为空');
|
||||
@@ -370,7 +383,8 @@ export class AdminPluginController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
await this.centerAuthService.requirePerms(
|
||||
['center:grant:list', 'center:plugin:list'], xAdminToken, xApiToken);
|
||||
const m = this.accountPluginRepo.manager;
|
||||
const plugins: any[] = await m.query(`SELECT id, name, status, latest_version FROM plugins ORDER BY id`);
|
||||
const accounts: any[] = await m.query(
|
||||
|
||||
@@ -18,8 +18,8 @@ import { BaseSysDepartmentEntity } from '../../../base/entity/sys/department';
|
||||
/**
|
||||
* 系统管理(37du 控制台侧自建 RBAC 管理)。
|
||||
*
|
||||
* 身份体系:控制台登录 = accounts + HMAC 管理员票据(requireAdmin),与 cool-admin 的
|
||||
* base_sys_user + JWT 不同体系,故由本层统一出口管理 cool-admin 的 RBAC 表(base_sys_*)。
|
||||
* 身份体系:控制台登录 = base_sys_user + HMAC 管理员票据,接口按角色 perms 拦截。
|
||||
* 本层统一出口管理 cool-admin 的 RBAC 表(base_sys_*)。
|
||||
* 写操作全部委托 base 原生 service(md5 密码 / passwordV 失效旧 token / 授权缓存刷新
|
||||
* 与原生登录链路完全一致),并对内置超管(admin 用户 / admin 角色)加保护。
|
||||
*
|
||||
@@ -68,8 +68,8 @@ export class AdminSysController extends BaseController {
|
||||
@InjectEntityModel(BaseSysDepartmentEntity)
|
||||
baseSysDeptRepo: Repository<BaseSysDepartmentEntity>;
|
||||
|
||||
private async admin(xAdminToken: string, xApiToken: string): Promise<string> {
|
||||
return this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
|
||||
private async admin(perms: string | string[], xAdminToken: string, xApiToken: string): Promise<string> {
|
||||
return this.centerAuthService.requirePerms(perms, xAdminToken, xApiToken);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -99,7 +99,7 @@ export class AdminSysController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
await this.admin(xAdminToken, xApiToken);
|
||||
await this.admin('center:sys:user', xAdminToken, xApiToken);
|
||||
const rows: any[] = await this.baseSysUserRepo.manager.query(
|
||||
`SELECT a.id, a.username, a.name, a.nickName, a.departmentId, b.name AS departmentName,
|
||||
a.status, a.createTime
|
||||
@@ -128,7 +128,7 @@ export class AdminSysController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
await this.admin(xAdminToken, xApiToken);
|
||||
await this.admin('center:sys:role', xAdminToken, xApiToken);
|
||||
const rows: any[] = await this.baseSysUserRepo.manager.query(
|
||||
`SELECT id, name, label, remark, relevance FROM base_sys_role ORDER BY id`
|
||||
);
|
||||
@@ -143,9 +143,9 @@ export class AdminSysController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
await this.admin(xAdminToken, xApiToken);
|
||||
await this.admin(['center:sys:menu', 'center:sys:role'], xAdminToken, xApiToken);
|
||||
const rows: any[] = await this.baseSysUserRepo.manager.query(
|
||||
`SELECT id, parentId, name, router, perms, icon, type, orderNum FROM base_sys_menu ORDER BY orderNum, id`
|
||||
`SELECT id, parentId, name, router, perms, icon, type, orderNum, viewPath, keepAlive, isShow FROM base_sys_menu ORDER BY orderNum, id`
|
||||
);
|
||||
return { items: buildTree(rows) };
|
||||
}
|
||||
@@ -156,7 +156,7 @@ export class AdminSysController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
await this.admin(xAdminToken, xApiToken);
|
||||
await this.admin(['center:sys:dept', 'center:sys:user', 'center:sys:role'], xAdminToken, xApiToken);
|
||||
const rows: any[] = await this.baseSysUserRepo.manager.query(
|
||||
`SELECT id, parentId, name, orderNum, createTime FROM base_sys_department ORDER BY orderNum, id`
|
||||
);
|
||||
@@ -172,7 +172,7 @@ export class AdminSysController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
await this.admin(xAdminToken, xApiToken);
|
||||
await this.admin('center:sys:user', xAdminToken, xApiToken);
|
||||
if (!id) throw err(400, 'id 不能为空');
|
||||
this.prepareDelegation();
|
||||
return this.baseSysUserService.info(id);
|
||||
@@ -185,7 +185,7 @@ export class AdminSysController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
const login = await this.admin(xAdminToken, xApiToken);
|
||||
const login = await this.admin('center:sys:user', xAdminToken, xApiToken);
|
||||
const username = String(b?.username || '').trim();
|
||||
if (!username) throw err(400, 'username 不能为空');
|
||||
if (!b?.password) throw err(400, 'password 不能为空');
|
||||
@@ -209,7 +209,7 @@ export class AdminSysController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
const login = await this.admin(xAdminToken, xApiToken);
|
||||
const login = await this.admin('center:sys:user', xAdminToken, xApiToken);
|
||||
if (!b?.id) throw err(400, 'id 不能为空');
|
||||
const row = await this.baseSysUserRepo.findOneBy({ id: Number(b.id) });
|
||||
if (!row) throw err(404, '用户不存在');
|
||||
@@ -231,7 +231,7 @@ export class AdminSysController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
const login = await this.admin(xAdminToken, xApiToken);
|
||||
const login = await this.admin('center:sys:user', xAdminToken, xApiToken);
|
||||
if (!b?.id) throw err(400, 'id 不能为空');
|
||||
const row = await this.baseSysUserRepo.findOneBy({ id: Number(b.id) });
|
||||
if (!row) throw err(404, '用户不存在');
|
||||
@@ -255,7 +255,7 @@ export class AdminSysController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
await this.admin(xAdminToken, xApiToken);
|
||||
await this.admin('center:sys:role', xAdminToken, xApiToken);
|
||||
if (!id) throw err(400, 'id 不能为空');
|
||||
this.prepareDelegation();
|
||||
return this.baseSysRoleService.info(id);
|
||||
@@ -268,7 +268,7 @@ export class AdminSysController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
const login = await this.admin(xAdminToken, xApiToken);
|
||||
const login = await this.admin('center:sys:role', xAdminToken, xApiToken);
|
||||
const name = String(b?.name || '').trim();
|
||||
if (!name) throw err(400, 'name 不能为空');
|
||||
if (String(b?.label || '').trim().toLowerCase() === 'admin') throw err(400, 'label admin 为内置超管标识,不可使用');
|
||||
@@ -301,7 +301,7 @@ export class AdminSysController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
const login = await this.admin(xAdminToken, xApiToken);
|
||||
const login = await this.admin('center:sys:role', xAdminToken, xApiToken);
|
||||
if (!b?.id) throw err(400, 'id 不能为空');
|
||||
const row = await this.baseSysRoleRepo.findOneBy({ id: Number(b.id) });
|
||||
if (!row) throw err(404, '角色不存在');
|
||||
@@ -344,7 +344,7 @@ export class AdminSysController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
const login = await this.admin(xAdminToken, xApiToken);
|
||||
const login = await this.admin('center:sys:role', xAdminToken, xApiToken);
|
||||
if (!b?.id) throw err(400, 'id 不能为空');
|
||||
const row = await this.baseSysRoleRepo.findOneBy({ id: Number(b.id) });
|
||||
if (!row) throw err(404, '角色不存在');
|
||||
@@ -370,7 +370,7 @@ export class AdminSysController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
const login = await this.admin(xAdminToken, xApiToken);
|
||||
const login = await this.admin('center:sys:menu', xAdminToken, xApiToken);
|
||||
const name = String(b?.name || '').trim();
|
||||
if (!name) throw err(400, 'name 不能为空');
|
||||
const type = Number(b?.type ?? 0);
|
||||
@@ -389,6 +389,11 @@ export class AdminSysController extends BaseController {
|
||||
icon: String(b?.icon || '').trim(),
|
||||
type,
|
||||
orderNum: Number(b?.orderNum || 0) || 0,
|
||||
viewPath: String(b?.viewPath || '').trim(),
|
||||
keepAlive: b?.keepAlive === undefined ? true : !!b.keepAlive,
|
||||
isShow: b?.isShow === undefined ? true : !!b.isShow,
|
||||
createTime: new Date(),
|
||||
updateTime: new Date(),
|
||||
} as any);
|
||||
const id = Number((res as any).identifiers?.[0]?.id || 0);
|
||||
await this.audit(login, 'sys-menu-add', name, { id });
|
||||
@@ -402,7 +407,7 @@ export class AdminSysController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
const login = await this.admin(xAdminToken, xApiToken);
|
||||
const login = await this.admin('center:sys:menu', xAdminToken, xApiToken);
|
||||
if (!b?.id) throw err(400, 'id 不能为空');
|
||||
const row = await this.baseSysMenuRepo.findOneBy({ id: Number(b.id) });
|
||||
if (!row) throw err(404, '菜单不存在');
|
||||
@@ -424,7 +429,11 @@ export class AdminSysController extends BaseController {
|
||||
patch.type = type;
|
||||
}
|
||||
if (b?.orderNum !== undefined) patch.orderNum = Number(b.orderNum) || 0;
|
||||
if (b?.viewPath !== undefined) patch.viewPath = String(b.viewPath).trim();
|
||||
if (b?.keepAlive !== undefined) patch.keepAlive = !!b.keepAlive;
|
||||
if (b?.isShow !== undefined) patch.isShow = !!b.isShow;
|
||||
if (Object.keys(patch).length) {
|
||||
patch.updateTime = new Date();
|
||||
await this.baseSysMenuRepo.update({ id: Number(b.id) }, patch);
|
||||
}
|
||||
await this.audit(login, 'sys-menu-edit', row.name, { id: Number(b.id) });
|
||||
@@ -438,7 +447,7 @@ export class AdminSysController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
const login = await this.admin(xAdminToken, xApiToken);
|
||||
const login = await this.admin('center:sys:menu', xAdminToken, xApiToken);
|
||||
if (!b?.id) throw err(400, 'id 不能为空');
|
||||
const id = Number(b.id);
|
||||
const row = await this.baseSysMenuRepo.findOneBy({ id });
|
||||
@@ -460,7 +469,7 @@ export class AdminSysController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
const login = await this.admin(xAdminToken, xApiToken);
|
||||
const login = await this.admin('center:sys:dept', xAdminToken, xApiToken);
|
||||
const name = String(b?.name || '').trim();
|
||||
if (!name) throw err(400, 'name 不能为空');
|
||||
if (b?.parentId) {
|
||||
@@ -484,7 +493,7 @@ export class AdminSysController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
const login = await this.admin(xAdminToken, xApiToken);
|
||||
const login = await this.admin('center:sys:dept', xAdminToken, xApiToken);
|
||||
if (!b?.id) throw err(400, 'id 不能为空');
|
||||
const row = await this.baseSysDeptRepo.findOneBy({ id: Number(b.id) });
|
||||
if (!row) throw err(404, '部门不存在');
|
||||
@@ -511,7 +520,7 @@ export class AdminSysController extends BaseController {
|
||||
@Headers('X-Admin-Token') xAdminToken: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
const login = await this.admin(xAdminToken, xApiToken);
|
||||
const login = await this.admin('center:sys:dept', xAdminToken, xApiToken);
|
||||
if (!b?.id) throw err(400, 'id 不能为空');
|
||||
const id = Number(b.id);
|
||||
const row = await this.baseSysDeptRepo.findOneBy({ id });
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import { CoolController, BaseController } from '@cool-midway/core';
|
||||
import { Body, Headers, Inject, Post, Provide, Query } from '@midwayjs/core';
|
||||
import { CenterAuthService, ApiError } from '../../service/auth';
|
||||
import { CenterLogService } from '../../service/logstore';
|
||||
import { SHELL_LOG_CHUNK_MAX } from '../../comm/conf';
|
||||
|
||||
/**
|
||||
* 客户端日志回传(对齐旧 FastAPI apis/plugins.py /api/runtime/logs、/api/runtime/shell-log):
|
||||
* - 运行日志:每次运行结束整次回传,按 run_id 幂等 upsert(离线补报安全)
|
||||
* - 壳日志:shell.log 增量字节(O_APPEND 追加落盘 logs/shell/<device_id>.log;reset=1 先截断)
|
||||
*/
|
||||
@Provide()
|
||||
@CoolController('/api')
|
||||
export class ApiLogController extends BaseController {
|
||||
@Inject()
|
||||
ctx: any;
|
||||
|
||||
@Inject()
|
||||
centerAuthService: CenterAuthService;
|
||||
|
||||
@Inject()
|
||||
centerLogService: CenterLogService;
|
||||
|
||||
/** POST /api/runtime/logs */
|
||||
@Post('/runtime/logs')
|
||||
async runtimeLogs(@Body() b: any, @Headers('X-API-Token') xApiToken: string = '') {
|
||||
this.centerAuthService.checkApiToken(xApiToken);
|
||||
if (!b?.run_id) throw new ApiError(400, 'run_id 不能为空');
|
||||
await this.centerLogService.storeRunLog(b);
|
||||
return { ok: true, run_id: b.run_id };
|
||||
}
|
||||
|
||||
/** POST /api/runtime/shell-log — 原始字节体增量回传 */
|
||||
@Post('/runtime/shell-log')
|
||||
async shellLog(
|
||||
@Query('device_id') deviceId: string = '',
|
||||
@Query('account') account: string = '',
|
||||
@Query('hostname') hostname: string = '',
|
||||
@Query('client_version') clientVersion: string = '',
|
||||
@Query('reset') reset: string = '',
|
||||
@Headers('X-API-Token') xApiToken: string = ''
|
||||
) {
|
||||
this.centerAuthService.checkApiToken(xApiToken);
|
||||
deviceId = (deviceId || '').trim();
|
||||
if (!deviceId) throw new ApiError(400, 'device_id 不能为空');
|
||||
const buf = await this.readRawBody();
|
||||
if (buf.length > SHELL_LOG_CHUNK_MAX) {
|
||||
throw new ApiError(413, `单次回传超过大小上限(${Math.floor(SHELL_LOG_CHUNK_MAX / 1024 / 1024)}MB)`);
|
||||
}
|
||||
try {
|
||||
const result = await this.centerLogService.appendShellLog(
|
||||
deviceId, buf,
|
||||
{ account: account || '', hostname: hostname || '', clientVersion: clientVersion || '' },
|
||||
reset === '1' || reset === 'true'
|
||||
);
|
||||
return { ok: true, device_id: result.device_id, size_bytes: result.size_bytes };
|
||||
} catch (e) {
|
||||
if (e instanceof Error) throw new ApiError(400, e.message);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/** 读取原始请求体(无 Content-Type 或 octet-stream 的字节流;koa-bodyparser 不会消费未匹配类型的流) */
|
||||
private async readRawBody(): Promise<Buffer> {
|
||||
const parsed: any = (this.ctx.request as any).body;
|
||||
if (Buffer.isBuffer(parsed)) return parsed;
|
||||
const req = this.ctx.req;
|
||||
// 流已被中间件消费完:回退空(异常路径,不挂起)
|
||||
if (req.readableEnded || req.complete) return Buffer.alloc(0);
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunks: Buffer[] = [];
|
||||
let settled = false;
|
||||
const done = (err?: Error) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
if (err) reject(err);
|
||||
else resolve(Buffer.concat(chunks));
|
||||
};
|
||||
req.on('data', (c: Buffer) => chunks.push(Buffer.isBuffer(c) ? c : Buffer.from(c)));
|
||||
req.on('end', () => done());
|
||||
req.on('error', done);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -53,13 +53,23 @@ export class ApiPluginsController extends BaseController {
|
||||
const rows = await this.accountPluginRepo
|
||||
.createQueryBuilder('ap')
|
||||
.innerJoin(PluginEntity, 'p', 'p.id = ap.pluginId')
|
||||
.select(['p.id AS id', 'p.name AS name', 'p.latestVersion AS version'])
|
||||
.select([
|
||||
'p.id AS id',
|
||||
'p.name AS name',
|
||||
'p.latestVersion AS version',
|
||||
'p.category AS category',
|
||||
])
|
||||
.where('ap.account = :account', { account: acct })
|
||||
.orderBy('p.id', 'ASC')
|
||||
.getRawMany();
|
||||
return {
|
||||
account: acct,
|
||||
plugins: rows.map(r => ({ id: r.id, name: r.name, version: r.version })),
|
||||
plugins: rows.map(r => ({
|
||||
id: r.id,
|
||||
name: r.name,
|
||||
version: r.version,
|
||||
category: r.category || '',
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { Column, Entity, Index, PrimaryGeneratedColumn } from 'typeorm';
|
||||
|
||||
/**
|
||||
* 控制台字典项(现网 dict_items 表):按 dict_key 分组的可维护枚举,
|
||||
* 首个使用方 plugin_category(场景分类),供插件管理页分类下拉与分类维护弹窗使用。
|
||||
*/
|
||||
@Entity('dict_items')
|
||||
@Index('uk_dict_key_label', ['dictKey', 'label'], { unique: true })
|
||||
export class DictItemEntity {
|
||||
@PrimaryGeneratedColumn({ name: 'id', type: 'bigint', unsigned: true, comment: '字典项自增ID' })
|
||||
id: number;
|
||||
|
||||
@Index('idx_dict_key')
|
||||
@Column({ name: 'dict_key', type: 'varchar', length: 64, comment: '字典标识(如 plugin_category)' })
|
||||
dictKey: string;
|
||||
|
||||
@Column({ name: 'label', type: 'varchar', length: 64, comment: '字典项名称' })
|
||||
label: string;
|
||||
|
||||
@Column({ name: 'sort', type: 'int', default: 0, comment: '排序(小在前)' })
|
||||
sort: number;
|
||||
|
||||
@Column({ name: 'created_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', comment: '创建时间' })
|
||||
createdAt: Date;
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import { Column, Entity, Index, PrimaryColumn, PrimaryGeneratedColumn } from 'typeorm';
|
||||
|
||||
/**
|
||||
* 运行上报(现网 runtime_reports 表)
|
||||
*/
|
||||
@@ -143,3 +142,102 @@ export class NotificationEntity {
|
||||
@Column({ name: 'active', type: 'tinyint', width: 1, default: 1, comment: '1=启用 0=停用' })
|
||||
active: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 运行日志(集中留存,客户端回传,按 run_id 幂等 upsert)。
|
||||
* 注意:trigger_by 列原名 trigger(MySQL 保留字),改名避免 TypeORM 自动建表/查询语法错误;
|
||||
* 对外 JSON 字段仍为 trigger(SELECT ... AS trigger)。
|
||||
*/
|
||||
@Entity('run_logs')
|
||||
export class RunLogEntity {
|
||||
@PrimaryGeneratedColumn({ name: 'id', type: 'bigint', unsigned: true, comment: '记录自增ID' })
|
||||
id: number;
|
||||
|
||||
@Index({ unique: true })
|
||||
@Column({ name: 'run_id', type: 'varchar', length: 64, comment: '运行ID(客户端生成 32 位 hex,唯一)' })
|
||||
runId: string;
|
||||
|
||||
@Index()
|
||||
@Column({ name: 'account', type: 'varchar', length: 64, default: '', comment: '运行账号(工号)' })
|
||||
account: string;
|
||||
|
||||
@Index()
|
||||
@Column({ name: 'device_id', type: 'varchar', length: 64, default: '', comment: '执行机设备ID' })
|
||||
deviceId: string;
|
||||
|
||||
@Index()
|
||||
@Column({ name: 'plugin_id', type: 'varchar', length: 64, default: '', comment: '插件ID' })
|
||||
pluginId: string;
|
||||
|
||||
@Column({ name: 'name', type: 'varchar', length: 128, default: '', comment: '插件名称' })
|
||||
name: string;
|
||||
|
||||
@Column({ name: 'version', type: 'varchar', length: 32, default: '', comment: '插件版本号' })
|
||||
version: string;
|
||||
|
||||
@Column({ name: 'trigger_by', type: 'varchar', length: 16, default: 'manual', comment: '触发方式:manual=手动 schedule=定时' })
|
||||
triggerBy: string;
|
||||
|
||||
@Column({ name: 'schedule_id', type: 'varchar', length: 64, default: '', comment: '定时任务ID' })
|
||||
scheduleId: string;
|
||||
|
||||
@Index()
|
||||
@Column({ name: 'status', type: 'varchar', length: 32, default: '', comment: 'running/done/error' })
|
||||
status: string;
|
||||
|
||||
@Column({ name: 'ok', type: 'tinyint', width: 1, default: 0, comment: '是否成功:1=是 0=否' })
|
||||
ok: number;
|
||||
|
||||
@Column({ name: 'error', type: 'text', comment: '错误信息' })
|
||||
error: string;
|
||||
|
||||
@Column({ name: 'summary', type: 'text', comment: '运行结论摘要' })
|
||||
summary: string;
|
||||
|
||||
@Column({ name: 'started', type: 'bigint', unsigned: true, default: 0, comment: '开始时间(epoch 秒)' })
|
||||
started: number;
|
||||
|
||||
@Column({ name: 'finished', type: 'bigint', unsigned: true, default: 0, comment: '结束时间(epoch 秒)' })
|
||||
finished: number;
|
||||
|
||||
@Column({ name: 'duration_sec', type: 'int', unsigned: true, default: 0, comment: '运行时长(秒)' })
|
||||
durationSec: number;
|
||||
|
||||
@Column({ name: 'log_count', type: 'int', unsigned: true, default: 0, comment: '日志条数' })
|
||||
logCount: number;
|
||||
|
||||
@Column({ name: 'logs', type: 'mediumtext', comment: '运行日志全文(JSON 数组 [{t,level,msg}])' })
|
||||
logs: string;
|
||||
|
||||
@Index()
|
||||
@Column({ name: 'uploaded_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', comment: '回传时间' })
|
||||
uploadedAt: Date;
|
||||
}
|
||||
|
||||
/**
|
||||
* 客户端壳日志元数据(内容存 logs/shell/<device_id>.log,增量追加)
|
||||
*/
|
||||
@Entity('device_logs')
|
||||
export class DeviceLogEntity {
|
||||
@PrimaryColumn({ name: 'device_id', type: 'varchar', length: 64, comment: '执行机设备ID(唯一)' })
|
||||
deviceId: string;
|
||||
|
||||
@Index()
|
||||
@Column({ name: 'account', type: 'varchar', length: 64, default: '', comment: '当前登录账号' })
|
||||
account: string;
|
||||
|
||||
@Column({ name: 'hostname', type: 'varchar', length: 128, default: '', comment: '主机名' })
|
||||
hostname: string;
|
||||
|
||||
@Column({ name: 'client_version', type: 'varchar', length: 32, default: '', comment: '客户端(壳子)版本号' })
|
||||
clientVersion: string;
|
||||
|
||||
@Column({ name: 'size_bytes', type: 'bigint', unsigned: true, default: 0, comment: '已回传壳日志累计字节' })
|
||||
sizeBytes: number;
|
||||
|
||||
@Column({ name: 'last_uploaded_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', comment: '最近一次回传时间' })
|
||||
lastUploadedAt: Date;
|
||||
|
||||
@Column({ name: 'updated_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP', comment: '更新时间' })
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
@@ -5,11 +5,12 @@ import { randomBytes } from 'node:crypto';
|
||||
import { AccountEntity, CloudTokenEntity, AuthFailCountEntity } from '../entity/account';
|
||||
import { AuditLogEntity } from '../entity/runtime';
|
||||
import { verifyAdminToken } from './crypto';
|
||||
import { CenterRbacService } from './rbac';
|
||||
|
||||
/**
|
||||
* 业务鉴权(对齐旧 FastAPI core/auth.py):
|
||||
* - X-API-Token:执行机底座→中心机的内部调用凭证
|
||||
* - X-Admin-Token:管理员签名票据(HMAC,12h),管理操作唯一可信身份
|
||||
* - X-Admin-Token:管理台/agent_cli 签名票据(HMAC,12h),身份源 = base_sys_user(cool RBAC)
|
||||
* - Authorization: Bearer <cloud_token>:员工端扫码登录的云端会话(落库 7 天)
|
||||
*/
|
||||
|
||||
@@ -33,6 +34,9 @@ export class CenterAuthService {
|
||||
@InjectEntityModel(AuthFailCountEntity)
|
||||
authFailRepo: Repository<AuthFailCountEntity>;
|
||||
|
||||
@Inject()
|
||||
rbac: CenterRbacService;
|
||||
|
||||
// ==================== 内部凭证 ====================
|
||||
checkApiToken(xApiToken: string = '') {
|
||||
const token = process.env.CONTROLPLANE_TOKEN || '';
|
||||
@@ -47,8 +51,9 @@ export class CenterAuthService {
|
||||
return !!row && !Number(row.status);
|
||||
}
|
||||
|
||||
// ==================== 管理员票据 ====================
|
||||
async requireAdmin(xAdminToken: string = '', xApiToken: string = ''): Promise<string> {
|
||||
// ==================== 管理员票据(身份源 = base_sys_user) ====================
|
||||
/** 仅校验登录态(票据有效 + 账号存在且启用),不要求管理员 */
|
||||
async requireLogin(xAdminToken: string = '', xApiToken: string = ''): Promise<string> {
|
||||
let account = '';
|
||||
try {
|
||||
account = verifyAdminToken(xAdminToken);
|
||||
@@ -56,14 +61,39 @@ export class CenterAuthService {
|
||||
throw new ApiError(401, '登录态无效或已过期,请重新登录');
|
||||
}
|
||||
if (!account) throw new ApiError(401, '缺少有效登录态');
|
||||
return this._adminGate(account);
|
||||
const ctx = await this.rbac.context(account);
|
||||
if (!ctx) throw new ApiError(401, '登录态无效或已过期,请重新登录');
|
||||
if (!Number(ctx.user.status)) throw new ApiError(403, '账号已停用,请联系管理员');
|
||||
return account;
|
||||
}
|
||||
|
||||
private async _adminGate(account: string): Promise<string> {
|
||||
const row = await this.accountRepo.findOneBy({ account });
|
||||
if (!row || !Number(row.isAdmin)) throw new ApiError(403, `账号 ${account} 无管理权限`);
|
||||
if (!Number(row.status)) throw new ApiError(403, '账号已停用,请联系管理员');
|
||||
if (Number(row.mustChangePwd)) throw new ApiError(403, '请先修改初始密码后再执行管理操作');
|
||||
/** 管理员 = 内置 admin 用户,或拥有 label='admin'(超管)角色 */
|
||||
async requireAdmin(xAdminToken: string = '', xApiToken: string = ''): Promise<string> {
|
||||
const account = await this.requireLogin(xAdminToken, xApiToken);
|
||||
const ctx = await this.rbac.context(account);
|
||||
if (!ctx || !ctx.isAdmin) throw new ApiError(403, `账号 ${account} 无管理权限`);
|
||||
return account;
|
||||
}
|
||||
|
||||
/**
|
||||
* 接口级权限校验(第二期:菜单可见 + 接口 403):
|
||||
* 超管直接放行;普通账号校验其角色聚合出的 perms 是否命中(任一即可)。
|
||||
*/
|
||||
async requirePerms(
|
||||
perms: string | string[],
|
||||
xAdminToken: string = '',
|
||||
xApiToken: string = ''
|
||||
): Promise<string> {
|
||||
const account = await this.requireLogin(xAdminToken, xApiToken);
|
||||
const ctx = await this.rbac.context(account);
|
||||
if (!ctx) throw new ApiError(401, '登录态无效或已过期,请重新登录');
|
||||
if (ctx.isAdmin) return account;
|
||||
const need = (Array.isArray(perms) ? perms : [perms]).filter(Boolean);
|
||||
if (!need.length) return account;
|
||||
const owned = await this.rbac.permsOfUser(account);
|
||||
if (!need.some(p => owned.includes(p))) {
|
||||
throw new ApiError(403, `无权限访问:${need.join(' / ')}`);
|
||||
}
|
||||
return account;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
import { Inject, Provide } from '@midwayjs/core';
|
||||
import { InjectEntityModel } from '@midwayjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import { RunLogEntity, DeviceLogEntity } from '../entity/runtime';
|
||||
import { SHELL_LOGS_DIR, LOG_RETENTION_DAYS } from '../comm/conf';
|
||||
|
||||
/**
|
||||
* 中心机集中日志存储(对齐旧 FastAPI core/logstore.py):
|
||||
* - 运行日志(run_logs 表,按 run_id 幂等 upsert;日志正文以 JSON 数组存 MEDIUMTEXT)
|
||||
* - 客户端壳日志(logs/shell/<device_id>.log 文件 + device_logs 元数据表,增量追加)
|
||||
* - 保留策略:LOG_RETENTION_DAYS(默认 30 天),启动 + 周期清理
|
||||
*/
|
||||
|
||||
// 路径安全白名单(杜绝目录穿越)
|
||||
const RUN_ID_RE = /^[A-Za-z0-9_-]{8,64}$/;
|
||||
const DEVICE_ID_RE = /^[A-Za-z0-9_-]{4,64}$/;
|
||||
|
||||
// 管理端展示单次最多读取字节(下载接口给全文)
|
||||
const SHELL_LOG_VIEW_MAX = 512 * 1024;
|
||||
// 后台清理周期(秒)
|
||||
const CLEANUP_INTERVAL = 6 * 3600;
|
||||
|
||||
function safeRunId(runId: string): string {
|
||||
const s = String(runId || '');
|
||||
return RUN_ID_RE.test(s) ? s : '';
|
||||
}
|
||||
function safeDeviceId(deviceId: string): string {
|
||||
const s = String(deviceId || '');
|
||||
return DEVICE_ID_RE.test(s) ? s : '';
|
||||
}
|
||||
|
||||
/** 设备壳日志文件路径;device_id 非法返回空串 */
|
||||
function deviceLogPath(deviceId: string): string {
|
||||
const dev = safeDeviceId(deviceId);
|
||||
if (!dev) return '';
|
||||
fs.mkdirSync(SHELL_LOGS_DIR, { recursive: true });
|
||||
return path.join(SHELL_LOGS_DIR, `${dev}.log`);
|
||||
}
|
||||
|
||||
/** 时间 'YYYY-MM-DD HH:mm:ss' */
|
||||
function nowStr(d: Date = new Date()): string {
|
||||
const p = (n: number) => String(n).padStart(2, '0');
|
||||
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
|
||||
}
|
||||
|
||||
/** 数据库时间值 → 展示串(容错 Date 或 string) */
|
||||
function fmtDb(d: any): string {
|
||||
if (!d) return '';
|
||||
if (d instanceof Date) {
|
||||
const p = (n: number) => String(n).padStart(2, '0');
|
||||
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
|
||||
}
|
||||
return String(d).replace('T', ' ').slice(0, 19);
|
||||
}
|
||||
|
||||
@Provide()
|
||||
export class CenterLogService {
|
||||
@InjectEntityModel(RunLogEntity)
|
||||
runRepo: Repository<RunLogEntity>;
|
||||
|
||||
@InjectEntityModel(DeviceLogEntity)
|
||||
deviceRepo: Repository<DeviceLogEntity>;
|
||||
|
||||
private timer: NodeJS.Timeout | null = null;
|
||||
|
||||
// ==================== 运行日志 ====================
|
||||
/** 幂等存入一次运行日志(按 run_id upsert;重复回传只覆盖不重复)。payload 见客户端 RunLogIn。 */
|
||||
async storeRunLog(payload: any): Promise<void> {
|
||||
const runId = safeRunId(payload?.run_id);
|
||||
if (!runId) return;
|
||||
const logs = Array.isArray(payload?.logs) ? payload.logs : [];
|
||||
const logJson = JSON.stringify(logs);
|
||||
await this.runRepo.manager.query(
|
||||
`INSERT INTO run_logs(run_id, account, device_id, plugin_id, name, version, trigger_by,
|
||||
schedule_id, status, ok, error, summary, started, finished, duration_sec, log_count,
|
||||
logs, uploaded_at)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
account = VALUES(account), device_id = VALUES(device_id), plugin_id = VALUES(plugin_id),
|
||||
name = VALUES(name), version = VALUES(version), trigger_by = VALUES(trigger_by),
|
||||
schedule_id = VALUES(schedule_id), status = VALUES(status), ok = VALUES(ok),
|
||||
error = VALUES(error), summary = VALUES(summary), started = VALUES(started),
|
||||
finished = VALUES(finished), duration_sec = VALUES(duration_sec),
|
||||
log_count = VALUES(log_count), logs = VALUES(logs), uploaded_at = NOW()`,
|
||||
[
|
||||
runId,
|
||||
String(payload?.account || ''),
|
||||
String(payload?.device_id || ''),
|
||||
String(payload?.plugin_id || ''),
|
||||
String(payload?.name || ''),
|
||||
String(payload?.version || ''),
|
||||
String(payload?.trigger || 'manual'),
|
||||
String(payload?.schedule_id || ''),
|
||||
String(payload?.status || ''),
|
||||
Number(!!payload?.ok),
|
||||
String(payload?.error || ''),
|
||||
String(payload?.summary || ''),
|
||||
Number(payload?.started || 0),
|
||||
Number(payload?.finished || 0),
|
||||
Number(payload?.duration_sec || 0),
|
||||
Number(payload?.log_count || logs.length),
|
||||
logJson,
|
||||
nowStr(),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/** 分页查询运行日志(列表不含 logs 正文,避免大列拖慢列表)。 */
|
||||
async queryRunLogs(opts: {
|
||||
page?: number; pageSize?: number; account?: string; device?: string;
|
||||
plugin?: string; status?: string; q?: string; days?: number;
|
||||
}): Promise<{ items: any[]; total: number }> {
|
||||
const page = Math.max(1, Math.floor(opts?.page || 1));
|
||||
const pageSize = Math.max(1, Math.min(1000, Math.floor(opts?.pageSize || 20)));
|
||||
const offset = (page - 1) * pageSize;
|
||||
const cond: string[] = [];
|
||||
const args: any[] = [];
|
||||
if ((opts?.account || '').trim()) { cond.push('account LIKE ?'); args.push(`%${opts.account.trim()}%`); }
|
||||
if ((opts?.device || '').trim()) { cond.push('device_id LIKE ?'); args.push(`%${opts.device.trim()}%`); }
|
||||
if ((opts?.plugin || '').trim()) { cond.push('plugin_id LIKE ?'); args.push(`%${opts.plugin.trim()}%`); }
|
||||
if ((opts?.status || '').trim()) {
|
||||
const vals = String(opts.status).split(',').map((s: string) => s.trim()).filter(Boolean);
|
||||
if (vals.length === 1) { cond.push('status = ?'); args.push(vals[0]); }
|
||||
else if (vals.length > 1) { cond.push(`status IN (${vals.map(() => '?').join(',')})`); args.push(...vals); }
|
||||
}
|
||||
if ((opts?.q || '').trim()) {
|
||||
cond.push('(name LIKE ? OR plugin_id LIKE ? OR account LIKE ? OR device_id LIKE ? OR error LIKE ? OR summary LIKE ?)');
|
||||
const kw = `%${opts.q.trim()}%`;
|
||||
args.push(kw, kw, kw, kw, kw, kw);
|
||||
}
|
||||
if (Number(opts?.days || 0) > 0) { cond.push('uploaded_at >= DATE_SUB(NOW(), INTERVAL ? DAY)'); args.push(Number(opts.days)); }
|
||||
const where = cond.length ? ' WHERE ' + cond.join(' AND ') : '';
|
||||
const m = this.runRepo.manager;
|
||||
const totalRow: any = (await m.query(`SELECT COUNT(*) AS c FROM run_logs${where}`, args))[0];
|
||||
const rows: any[] = await m.query(
|
||||
`SELECT id, run_id, account, device_id, plugin_id, name, version,
|
||||
trigger_by AS \`trigger\`, schedule_id, status, ok, error, summary,
|
||||
started, finished, duration_sec, log_count, uploaded_at
|
||||
FROM run_logs${where} ORDER BY id DESC LIMIT ? OFFSET ?`,
|
||||
[...args, pageSize, offset]
|
||||
);
|
||||
return {
|
||||
items: rows.map((r: any) => ({
|
||||
...r,
|
||||
started: Number(r.started || 0), finished: Number(r.finished || 0),
|
||||
duration_sec: Number(r.duration_sec || 0), log_count: Number(r.log_count || 0),
|
||||
uploaded_at: fmtDb(r.uploaded_at),
|
||||
})),
|
||||
total: Number(totalRow.c || 0),
|
||||
};
|
||||
}
|
||||
|
||||
/** 单次运行详情(含日志正文,解析为数组);不存在返回 null。 */
|
||||
async getRunLog(runId: string): Promise<any | null> {
|
||||
const rid = safeRunId(runId);
|
||||
if (!rid) return null;
|
||||
const rows: any[] = await this.runRepo.manager.query(
|
||||
`SELECT id, run_id, account, device_id, plugin_id, name, version,
|
||||
trigger_by AS \`trigger\`, schedule_id, status, ok, error, summary,
|
||||
started, finished, duration_sec, log_count, logs, uploaded_at
|
||||
FROM run_logs WHERE run_id = ?`,
|
||||
[rid]
|
||||
);
|
||||
if (!rows.length) return null;
|
||||
const r = rows[0];
|
||||
let logsArr: any[] = [];
|
||||
try { logsArr = JSON.parse(r.logs || '[]'); } catch (e) { logsArr = []; }
|
||||
return {
|
||||
id: Number(r.id), run_id: r.run_id, account: r.account || '', device_id: r.device_id || '',
|
||||
plugin_id: r.plugin_id || '', name: r.name || '', version: r.version || '',
|
||||
trigger: r.trigger || '', schedule_id: r.schedule_id || '', status: r.status || '',
|
||||
ok: Number(r.ok || 0), error: r.error || '', summary: r.summary || '',
|
||||
started: Number(r.started || 0), finished: Number(r.finished || 0),
|
||||
duration_sec: Number(r.duration_sec || 0), log_count: Number(r.log_count || 0),
|
||||
logs: Array.isArray(logsArr) ? logsArr : [],
|
||||
uploaded_at: fmtDb(r.uploaded_at),
|
||||
};
|
||||
}
|
||||
|
||||
// ==================== 客户端壳日志(增量追加到文件) ====================
|
||||
/** 追加一段壳日志到 logs/shell/<device_id>.log 并更新元数据;reset=true 先截断。 */
|
||||
async appendShellLog(
|
||||
deviceId: string,
|
||||
data: Buffer,
|
||||
meta: { account?: string; hostname?: string; clientVersion?: string },
|
||||
reset: boolean
|
||||
): Promise<{ device_id: string; size_bytes: number }> {
|
||||
const dev = safeDeviceId(deviceId);
|
||||
if (!dev) throw new Error('device_id 非法');
|
||||
const file = deviceLogPath(dev);
|
||||
if (!file) throw new Error('device_id 非法');
|
||||
const buf = Buffer.isBuffer(data) ? data : Buffer.from(data || []);
|
||||
fs.writeFileSync(file, buf, { flag: reset ? 'w' : 'a' });
|
||||
const delta = buf.length;
|
||||
const m = this.deviceRepo.manager;
|
||||
if (reset) {
|
||||
await m.query(
|
||||
`INSERT INTO device_logs(device_id, account, hostname, client_version, size_bytes, last_uploaded_at)
|
||||
VALUES (?,?,?,?,?,?)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
account = VALUES(account), hostname = VALUES(hostname), client_version = VALUES(client_version),
|
||||
size_bytes = VALUES(size_bytes), last_uploaded_at = VALUES(last_uploaded_at)`,
|
||||
[dev, meta?.account || '', meta?.hostname || '', meta?.clientVersion || '', delta, nowStr()]
|
||||
);
|
||||
} else {
|
||||
await m.query(
|
||||
`INSERT INTO device_logs(device_id, account, hostname, client_version, size_bytes, last_uploaded_at)
|
||||
VALUES (?,?,?,?,?,?)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
account = VALUES(account), hostname = VALUES(hostname), client_version = VALUES(client_version),
|
||||
size_bytes = size_bytes + ?, last_uploaded_at = ?`,
|
||||
[dev, meta?.account || '', meta?.hostname || '', meta?.clientVersion || '', delta, nowStr(), delta, nowStr()]
|
||||
);
|
||||
}
|
||||
return { device_id: dev, size_bytes: delta };
|
||||
}
|
||||
|
||||
/** 分页查询有壳日志回传的设备列表。 */
|
||||
async queryDeviceLogs(opts: { page?: number; pageSize?: number; account?: string; q?: string }): Promise<{ items: any[]; total: number }> {
|
||||
const page = Math.max(1, Math.floor(opts?.page || 1));
|
||||
const pageSize = Math.max(1, Math.min(1000, Math.floor(opts?.pageSize || 20)));
|
||||
const offset = (page - 1) * pageSize;
|
||||
const cond: string[] = [];
|
||||
const args: any[] = [];
|
||||
if ((opts?.account || '').trim()) { cond.push('account LIKE ?'); args.push(`%${opts.account.trim()}%`); }
|
||||
if ((opts?.q || '').trim()) {
|
||||
cond.push('(device_id LIKE ? OR hostname LIKE ? OR account LIKE ?)');
|
||||
const kw = `%${opts.q.trim()}%`;
|
||||
args.push(kw, kw, kw);
|
||||
}
|
||||
const where = cond.length ? ' WHERE ' + cond.join(' AND ') : '';
|
||||
const m = this.deviceRepo.manager;
|
||||
const totalRow: any = (await m.query(`SELECT COUNT(*) AS c FROM device_logs${where}`, args))[0];
|
||||
const rows: any[] = await m.query(
|
||||
`SELECT device_id, account, hostname, client_version, size_bytes, last_uploaded_at, updated_at
|
||||
FROM device_logs${where} ORDER BY updated_at DESC LIMIT ? OFFSET ?`,
|
||||
[...args, pageSize, offset]
|
||||
);
|
||||
return {
|
||||
items: rows.map((r: any) => ({
|
||||
device_id: r.device_id, account: r.account || '', hostname: r.hostname || '',
|
||||
client_version: r.client_version || '', size_bytes: Number(r.size_bytes || 0),
|
||||
last_uploaded_at: fmtDb(r.last_uploaded_at), updated_at: fmtDb(r.updated_at),
|
||||
})),
|
||||
total: Number(totalRow.c || 0),
|
||||
};
|
||||
}
|
||||
|
||||
/** 读取设备壳日志尾部(UTF-8 容错解码)供页面展示;无记录返回 null。 */
|
||||
async getDeviceLog(deviceId: string, viewMax: number = SHELL_LOG_VIEW_MAX): Promise<any | null> {
|
||||
const dev = safeDeviceId(deviceId);
|
||||
if (!dev) return null;
|
||||
const file = deviceLogPath(dev);
|
||||
if (!file || !fs.existsSync(file)) return null;
|
||||
const metaRow: any = (await this.deviceRepo.manager.query(
|
||||
'SELECT account, hostname, client_version, size_bytes, last_uploaded_at FROM device_logs WHERE device_id = ?',
|
||||
[dev]
|
||||
))[0];
|
||||
if (!metaRow) return null;
|
||||
let size = 0;
|
||||
try { size = fs.statSync(file).size; } catch (e) { size = Number(metaRow.size_bytes || 0); }
|
||||
const readLen = Math.min(size, viewMax);
|
||||
let content = '';
|
||||
try {
|
||||
const fd = fs.openSync(file, 'r');
|
||||
const buf = Buffer.alloc(readLen);
|
||||
fs.readSync(fd, buf, 0, readLen, Math.max(0, size - readLen));
|
||||
fs.closeSync(fd);
|
||||
content = buf.toString('utf8');
|
||||
} catch (e) {
|
||||
content = '';
|
||||
}
|
||||
return {
|
||||
device_id: dev, account: metaRow.account || '', hostname: metaRow.hostname || '',
|
||||
client_version: metaRow.client_version || '', size_bytes: size,
|
||||
last_uploaded_at: fmtDb(metaRow.last_uploaded_at), content, truncated: size > viewMax,
|
||||
};
|
||||
}
|
||||
|
||||
/** 设备壳日志文件绝对路径(供下载);不存在或非法返回 ''。 */
|
||||
deviceLogFilePath(deviceId: string): string {
|
||||
const file = deviceLogPath(deviceId);
|
||||
if (!file || !fs.existsSync(file)) return '';
|
||||
return file;
|
||||
}
|
||||
|
||||
// ==================== 保留策略清理 ====================
|
||||
/** 清理超期日志:run_logs(按 uploaded_at)+ 设备壳日志(按 updated_at,含磁盘文件)。 */
|
||||
async cleanupExpired(): Promise<{ deleted_run_logs: number; deleted_device_logs: number; skipped: boolean }> {
|
||||
const result = { deleted_run_logs: 0, deleted_device_logs: 0, skipped: false };
|
||||
const days = Math.max(1, Number(LOG_RETENTION_DAYS) || 30);
|
||||
const cutoff = nowStr(new Date(Date.now() - days * 86400000));
|
||||
try {
|
||||
const r: any = await this.runRepo.manager.query('DELETE FROM run_logs WHERE uploaded_at < ?', [cutoff]);
|
||||
result.deleted_run_logs = Number(r.affectedRows || 0);
|
||||
} catch (e) {
|
||||
console.error('[logstore] run_logs 清理失败', e);
|
||||
}
|
||||
try {
|
||||
const rows: any[] = await this.deviceRepo.manager.query(
|
||||
'SELECT device_id FROM device_logs WHERE updated_at < ?', [cutoff]);
|
||||
for (const row of rows) {
|
||||
const dev = String(row.device_id || '');
|
||||
await this.deviceRepo.manager.query(
|
||||
'DELETE FROM device_logs WHERE device_id = ? AND updated_at < ?', [dev, cutoff]);
|
||||
result.deleted_device_logs += 1;
|
||||
const file = deviceLogPath(dev);
|
||||
if (file) { try { fs.unlinkSync(file); } catch (e) { /* ignore */ } }
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('[logstore] 设备壳日志清理失败', e);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// ==================== 后台周期清理 ====================
|
||||
start(): void {
|
||||
if (this.timer) return;
|
||||
this.cleanupExpired().catch(() => { /* 启动清理失败不阻断 */ });
|
||||
this.timer = setInterval(() => {
|
||||
this.cleanupExpired().catch(() => { /* 周期清理异常不退出,下轮重试 */ });
|
||||
}, CLEANUP_INTERVAL * 1000);
|
||||
this.timer.unref?.();
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
if (this.timer) {
|
||||
clearInterval(this.timer);
|
||||
this.timer = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,530 @@
|
||||
import { Provide } from '@midwayjs/core';
|
||||
import { InjectEntityModel } from '@midwayjs/typeorm';
|
||||
import { In, Repository } from 'typeorm';
|
||||
import * as md5 from 'md5';
|
||||
import { BaseSysUserEntity } from '../../base/entity/sys/user';
|
||||
import { BaseSysRoleEntity } from '../../base/entity/sys/role';
|
||||
import { BaseSysUserRoleEntity } from '../../base/entity/sys/user_role';
|
||||
import { BaseSysRoleMenuEntity } from '../../base/entity/sys/role_menu';
|
||||
import { BaseSysMenuEntity } from '../../base/entity/sys/menu';
|
||||
import { BaseSysDepartmentEntity } from '../../base/entity/sys/department';
|
||||
|
||||
/**
|
||||
* 控制台 RBAC(cool-admin 四表:base_sys_user/user_role/role/role_menu/menu)。
|
||||
*
|
||||
* 身份体系分工(2026-10 拍板):
|
||||
* - base_sys_user = 管理台 / agent_cli 的登录账号体系(本服务负责)
|
||||
* - accounts = 执行机(客户端)业务账号体系(插件授权、平台权限,本服务不碰)
|
||||
*
|
||||
* 职责:登录账号查询、超管判定、权限标识聚合、按角色生成控制台菜单树、启动期幂等种子。
|
||||
* 注意:不 import ./auth(避免循环依赖),错误自带 status 由 api-error 中间件渲染。
|
||||
*/
|
||||
|
||||
/** 控制台菜单节点(前端动态路由结构) */
|
||||
export interface ConsoleMenuNode {
|
||||
path: string;
|
||||
name: string;
|
||||
component: string;
|
||||
meta: {
|
||||
title: string;
|
||||
icon: string;
|
||||
perms: string[];
|
||||
keepAlive?: boolean;
|
||||
isHide?: boolean;
|
||||
};
|
||||
children?: ConsoleMenuNode[];
|
||||
}
|
||||
|
||||
interface MenuSeed {
|
||||
/** 路由地址(子级相对路径,避免前端 validateMenuPaths 报错) */
|
||||
router: string;
|
||||
/** 菜单名称(前端 meta.title) */
|
||||
name: string;
|
||||
/** 视图地址(前端 component) */
|
||||
viewPath: string;
|
||||
icon: string;
|
||||
perms: string;
|
||||
/** 0-目录 1-菜单 */
|
||||
type: number;
|
||||
isShow: boolean;
|
||||
children?: MenuSeed[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 控制台业务菜单种子(原 CONSOLE_MENUS 迁入数据库后的唯一来源)。
|
||||
* 顺序即 orderNum。前端不再硬编码,全部由 /api/admin/me/menus 下发。
|
||||
*/
|
||||
const MENU_SEED: MenuSeed[] = [
|
||||
{ router: '/overview', name: '概览', viewPath: '/overview/index', icon: 'ri:pie-chart-line', perms: 'center:overview:view', type: 1, isShow: true },
|
||||
{ router: '/stats', name: '数据看板', viewPath: '/stats/index', icon: 'ri:bar-chart-2-line', perms: 'center:stats:view', type: 1, isShow: true },
|
||||
{ router: '/plugins', name: '插件管理', viewPath: '/plugins/index', icon: 'ri:box-3-line', perms: 'center:plugin:list', type: 1, isShow: true },
|
||||
{ router: '/accounts', name: '账号管理', viewPath: '/accounts/index', icon: 'ri:user-3-line', perms: 'center:account:list', type: 1, isShow: true },
|
||||
{ router: '/grants', name: '权限授权', viewPath: '/grants/index', icon: 'ri:key-2-line', perms: 'center:grant:list', type: 1, isShow: true },
|
||||
{ router: '/audit', name: '审计报表', viewPath: '/audit/index', icon: 'ri:file-list-3-line', perms: 'center:audit:list', type: 1, isShow: true },
|
||||
{ router: '/reports', name: '运行记录', viewPath: '/reports/index', icon: 'ri:terminal-box-line', perms: 'center:report:list', type: 1, isShow: true },
|
||||
{ router: '/logs', name: '运行日志', viewPath: '/logs/index', icon: 'ri:file-text-line', perms: 'center:log:list', type: 1, isShow: true },
|
||||
{ router: '/devices', name: '执行机设备', viewPath: '/devices/index', icon: 'ri:computer-line', perms: 'center:device:list', type: 1, isShow: true },
|
||||
{ router: '/upgrade', name: '升级进度', viewPath: '/upgrade/index', icon: 'ri:rocket-2-line', perms: 'center:device:summary', type: 1, isShow: true },
|
||||
{ router: '/notify', name: '通知推送', viewPath: '/notify/index', icon: 'ri:notification-3-line', perms: 'center:notify:list', type: 1, isShow: true },
|
||||
{ router: '/creds', name: '敏感凭证', viewPath: '/creds/index', icon: 'ri:shield-keyhole-line', perms: 'center:creds:list', type: 1, isShow: true },
|
||||
{ router: '/file-sources', name: '大文件源', viewPath: '/file-sources/index', icon: 'ri:database-2-line', perms: 'center:fileSource:list', type: 1, isShow: true },
|
||||
{
|
||||
// 嵌套菜单父级必须是布局容器,否则一级带 children 的路由不包 Layout → 空白页
|
||||
router: '/system', name: '系统管理', viewPath: '/index/index', icon: 'ri:settings-3-line', perms: '', type: 0, isShow: true,
|
||||
children: [
|
||||
{ router: 'user', name: '用户管理', viewPath: '/system/user', icon: '', perms: 'center:sys:user', type: 1, isShow: true },
|
||||
{ router: 'role', name: '角色管理', viewPath: '/system/role', icon: '', perms: 'center:sys:role', type: 1, isShow: true },
|
||||
{ router: 'menu', name: '菜单管理', viewPath: '/system/menu', icon: '', perms: 'center:sys:menu', type: 1, isShow: true },
|
||||
{ router: 'department', name: '部门管理', viewPath: '/system/department', icon: '', perms: 'center:sys:dept', type: 1, isShow: true },
|
||||
{ router: 'user-center', name: '个人中心', viewPath: '/system/user-center', icon: '', perms: '', type: 1, isShow: false },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
/** 视图地址 → 前端路由 name(DB 无 name 列;路由 name 必须与前端 router.replace({name}) 对齐) */
|
||||
const ROUTE_NAME_BY_VIEW: Record<string, string> = {
|
||||
'/index/index': 'System',
|
||||
'/overview/index': 'Overview',
|
||||
'/stats/index': 'Stats',
|
||||
'/plugins/index': 'Plugins',
|
||||
'/accounts/index': 'Accounts',
|
||||
'/grants/index': 'Grants',
|
||||
'/audit/index': 'Audit',
|
||||
'/reports/index': 'Reports',
|
||||
'/logs/index': 'Logs',
|
||||
'/devices/index': 'Devices',
|
||||
'/upgrade/index': 'Upgrade',
|
||||
'/notify/index': 'Notify',
|
||||
'/creds/index': 'Creds',
|
||||
'/file-sources/index': 'FileSources',
|
||||
'/system/user': 'SysUser',
|
||||
'/system/role': 'SysRole',
|
||||
'/system/menu': 'SysMenu',
|
||||
'/system/department': 'SysDept',
|
||||
'/system/user-center': 'UserCenter',
|
||||
};
|
||||
|
||||
/** 内置超管用户名 */
|
||||
const SUPER_USERNAME = 'admin';
|
||||
/** 运行期管理员账号(agent_cli 默认账号) */
|
||||
const RUNTIME_ADMIN = { username: 'puddy', password: '123456' };
|
||||
|
||||
function fail(status: number, message: string): Error & { status: number } {
|
||||
const e: any = new Error(message);
|
||||
e.status = status;
|
||||
return e;
|
||||
}
|
||||
|
||||
function pascal(s: string): string {
|
||||
return String(s || '')
|
||||
.split(/[^a-zA-Z0-9]+/)
|
||||
.filter(Boolean)
|
||||
.map(w => w.charAt(0).toUpperCase() + w.slice(1))
|
||||
.join('');
|
||||
}
|
||||
|
||||
function splitPerms(raw: any): string[] {
|
||||
return String(raw || '')
|
||||
.split(',')
|
||||
.map(s => s.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
@Provide()
|
||||
export class CenterRbacService {
|
||||
@InjectEntityModel(BaseSysUserEntity)
|
||||
userRepo: Repository<BaseSysUserEntity>;
|
||||
|
||||
@InjectEntityModel(BaseSysRoleEntity)
|
||||
roleRepo: Repository<BaseSysRoleEntity>;
|
||||
|
||||
@InjectEntityModel(BaseSysUserRoleEntity)
|
||||
userRoleRepo: Repository<BaseSysUserRoleEntity>;
|
||||
|
||||
@InjectEntityModel(BaseSysRoleMenuEntity)
|
||||
roleMenuRepo: Repository<BaseSysRoleMenuEntity>;
|
||||
|
||||
@InjectEntityModel(BaseSysMenuEntity)
|
||||
menuRepo: Repository<BaseSysMenuEntity>;
|
||||
|
||||
@InjectEntityModel(BaseSysDepartmentEntity)
|
||||
deptRepo: Repository<BaseSysDepartmentEntity>;
|
||||
|
||||
// ==================== 查询 ====================
|
||||
|
||||
async getUserByUsername(username: string): Promise<BaseSysUserEntity | null> {
|
||||
const name = String(username || '').trim();
|
||||
if (!name) return null;
|
||||
return this.userRepo.findOneBy({ username: name });
|
||||
}
|
||||
|
||||
async roleIdsOf(userId: number): Promise<number[]> {
|
||||
const rows = await this.userRoleRepo.findBy({ userId: Number(userId) });
|
||||
return rows.map(r => Number(r.roleId));
|
||||
}
|
||||
|
||||
/** 超管:内置 admin 用户,或拥有 label='admin' 的角色 */
|
||||
async isSuperAdmin(user: BaseSysUserEntity, roleIds?: number[]): Promise<boolean> {
|
||||
if (!user) return false;
|
||||
if (user.username === SUPER_USERNAME) return true;
|
||||
const ids = roleIds ?? (await this.roleIdsOf(user.id));
|
||||
if (!ids.length) return false;
|
||||
const roles = await this.roleRepo.findBy({ id: In(ids) });
|
||||
return roles.some(r => String(r.label || '').toLowerCase() === 'admin');
|
||||
}
|
||||
|
||||
/** 账号上下文(登录态校验 + 角色 + 是否超管) */
|
||||
async context(username: string): Promise<{ user: BaseSysUserEntity; roleIds: number[]; isAdmin: boolean } | null> {
|
||||
const user = await this.getUserByUsername(username);
|
||||
if (!user) return null;
|
||||
const roleIds = await this.roleIdsOf(user.id);
|
||||
const isAdmin = await this.isSuperAdmin(user, roleIds);
|
||||
return { user, roleIds, isAdmin };
|
||||
}
|
||||
|
||||
async deptName(departmentId: number): Promise<string> {
|
||||
if (!departmentId) return '';
|
||||
try {
|
||||
const row = await this.deptRepo.findOneBy({ id: Number(departmentId) });
|
||||
return row?.name || '';
|
||||
} catch (e) {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 权限标识 / 菜单树 ====================
|
||||
|
||||
/** 该账号拥有的权限标识(超管 = 全部菜单 perms) */
|
||||
async permsOfUser(username: string): Promise<string[]> {
|
||||
const ctx = await this.context(username);
|
||||
if (!ctx) return [];
|
||||
const all = await this.menuRepo.find();
|
||||
if (ctx.isAdmin) return unique(all.flatMap(m => splitPerms(m.perms)));
|
||||
const granted = await this.grantedMenuIds(ctx.roleIds, all);
|
||||
return unique(all.filter(m => granted.has(Number(m.id))).flatMap(m => splitPerms(m.perms)));
|
||||
}
|
||||
|
||||
/** 按角色生成控制台菜单树 + 权限标识集合 */
|
||||
async menusForUser(username: string): Promise<{
|
||||
account: string;
|
||||
menus: ConsoleMenuNode[];
|
||||
perms: string[];
|
||||
is_admin: boolean;
|
||||
}> {
|
||||
const ctx = await this.context(username);
|
||||
if (!ctx) throw fail(401, '登录态无效或已过期,请重新登录');
|
||||
if (!Number(ctx.user.status)) throw fail(403, '账号已停用,请联系管理员');
|
||||
|
||||
const all = await this.menuRepo.find({ order: { orderNum: 'ASC', id: 'ASC' } });
|
||||
const granted = ctx.isAdmin ? null : await this.grantedMenuIds(ctx.roleIds, all);
|
||||
const visible = all.filter(m => Number(m.type) !== 2 && (granted === null || granted.has(Number(m.id))));
|
||||
const perms = ctx.isAdmin
|
||||
? unique(all.flatMap(m => splitPerms(m.perms)))
|
||||
: unique(all.filter(m => granted!.has(Number(m.id))).flatMap(m => splitPerms(m.perms)));
|
||||
|
||||
return {
|
||||
account: ctx.user.username,
|
||||
menus: buildTree(visible),
|
||||
perms,
|
||||
is_admin: ctx.isAdmin,
|
||||
};
|
||||
}
|
||||
|
||||
/** 角色已授权的菜单 ID(含自动补全的祖先,保证树能挂上) */
|
||||
private async grantedMenuIds(roleIds: number[], all: BaseSysMenuEntity[]): Promise<Set<number>> {
|
||||
const ids = new Set<number>();
|
||||
if (!roleIds.length) return ids;
|
||||
const rows = await this.roleMenuRepo.findBy({ roleId: In(roleIds) });
|
||||
rows.forEach(r => ids.add(Number(r.menuId)));
|
||||
const byId = new Map<number, BaseSysMenuEntity>();
|
||||
all.forEach(m => byId.set(Number(m.id), m));
|
||||
for (const id of [...ids]) {
|
||||
let cur = byId.get(id);
|
||||
let guard = 0;
|
||||
while (cur?.parentId && guard++ < 32) {
|
||||
ids.add(Number(cur.parentId));
|
||||
cur = byId.get(Number(cur.parentId));
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
// ==================== 启动期幂等种子 ====================
|
||||
|
||||
/**
|
||||
* 幂等初始化(生产 initDB=false 不自动灌 cool 种子):
|
||||
* 1. 确保超管角色(label='admin')
|
||||
* 2. 清理 cool demo 菜单(viewPath=modules/*)及其子级
|
||||
* 3. 业务菜单写入 base_sys_menu(已存在只补空字段,不覆盖人工改动)
|
||||
* 4. 确保 puddy 账号(agent_cli 默认账号)并绑定超管角色
|
||||
* 5. 清理测试种子账号 dept_user
|
||||
*/
|
||||
async ensureSeed(): Promise<void> {
|
||||
const superRole = await this.ensureSuperRole();
|
||||
await this.cleanDemoMenus();
|
||||
await this.seedMenus(MENU_SEED, null, 0);
|
||||
await this.ensureRuntimeAdmin(superRole ? Number(superRole.id) : 0);
|
||||
await this.cleanTestUser('dept_user');
|
||||
}
|
||||
|
||||
private async ensureSuperRole(): Promise<BaseSysRoleEntity | null> {
|
||||
let role = await this.roleRepo.findOneBy({ label: 'admin' });
|
||||
if (role) return role;
|
||||
try {
|
||||
await this.roleRepo.insert({
|
||||
userId: '0',
|
||||
name: '超级管理员',
|
||||
label: 'admin',
|
||||
remark: '内置超管角色(全部菜单/接口权限)',
|
||||
relevance: false,
|
||||
menuIdList: [],
|
||||
departmentIdList: [],
|
||||
createTime: new Date(),
|
||||
updateTime: new Date(),
|
||||
} as any);
|
||||
} catch (e) {
|
||||
/* 并发/已存在时忽略 */
|
||||
}
|
||||
role = await this.roleRepo.findOneBy({ label: 'admin' });
|
||||
return role || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理 cool-admin 自带演示菜单,只留业务菜单树。
|
||||
* 识别特征:viewPath 指向 cool 模块页面(cool/modules/*、modules/*)、外链 demo,或路由挂在 /sys、/tutorial 下。
|
||||
* 命中后连同整棵子树一起删(先删角色关联,避免脏授权)。
|
||||
*/
|
||||
private async cleanDemoMenus(): Promise<void> {
|
||||
const demo = await this.menuRepo
|
||||
.createQueryBuilder('m')
|
||||
.where('m.viewPath LIKE :cool', { cool: 'cool/%' })
|
||||
.orWhere('m.viewPath LIKE :mods', { mods: 'modules/%' })
|
||||
.orWhere('m.viewPath LIKE :ext', { ext: 'http%' })
|
||||
.orWhere('m.router = :sys', { sys: '/sys' })
|
||||
.orWhere('m.router LIKE :sysSub', { sysSub: '/sys/%' })
|
||||
.orWhere('m.router = :tutorial', { tutorial: '/tutorial' })
|
||||
.orWhere('m.router LIKE :tutorialSub', { tutorialSub: '/tutorial/%' })
|
||||
.orWhere('m.perms LIKE :basePerm', { basePerm: 'base:%' })
|
||||
.orWhere('m.perms LIKE :spacePerm', { spacePerm: 'space:%' })
|
||||
.getMany();
|
||||
if (demo.length) {
|
||||
const ids = demo.map(m => Number(m.id));
|
||||
await this.deleteMenuTree(ids);
|
||||
}
|
||||
// 残留的空目录(cool 的 type=0 容器:无 router/perms/子级),一并清掉
|
||||
const all = await this.menuRepo.find();
|
||||
const parents = new Set(all.map(m => Number(m.parentId || 0)));
|
||||
const emptyDirs = all
|
||||
.filter(m => Number(m.type) === 0 && !String(m.router || '').trim() && !String(m.perms || '').trim())
|
||||
.filter(m => !parents.has(Number(m.id)))
|
||||
.map(m => Number(m.id));
|
||||
if (emptyDirs.length) await this.deleteMenuTree(emptyDirs);
|
||||
}
|
||||
|
||||
/** 删除菜单及其所有后代(含 base_sys_role_menu 关联) */
|
||||
private async deleteMenuTree(rootIds: number[]): Promise<void> {
|
||||
const all = await this.menuRepo.find();
|
||||
const ids = [...rootIds];
|
||||
let changed = true;
|
||||
while (changed) {
|
||||
changed = false;
|
||||
for (const r of all) {
|
||||
const pid = Number(r.parentId || 0);
|
||||
if (!ids.includes(Number(r.id)) && pid && ids.includes(pid)) {
|
||||
ids.push(Number(r.id));
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
await this.roleMenuRepo
|
||||
.createQueryBuilder()
|
||||
.delete()
|
||||
.where('menuId IN (:...ids)', { ids })
|
||||
.execute();
|
||||
await this.menuRepo
|
||||
.createQueryBuilder()
|
||||
.delete()
|
||||
.where('id IN (:...ids)', { ids })
|
||||
.execute();
|
||||
}
|
||||
|
||||
private async seedMenus(nodes: MenuSeed[], parentId: number | null, startOrder: number): Promise<void> {
|
||||
let order = startOrder;
|
||||
for (const node of nodes) {
|
||||
order += 1;
|
||||
const row = await this.findMenu(parentId, node.router);
|
||||
let id = row ? Number(row.id) : 0;
|
||||
if (!row) {
|
||||
try {
|
||||
const res = await this.menuRepo.insert({
|
||||
parentId: parentId ? Number(parentId) : null,
|
||||
name: node.name,
|
||||
router: node.router,
|
||||
perms: node.perms,
|
||||
type: node.type,
|
||||
icon: node.icon,
|
||||
orderNum: order,
|
||||
viewPath: node.viewPath,
|
||||
keepAlive: true,
|
||||
isShow: node.isShow,
|
||||
createTime: new Date(),
|
||||
updateTime: new Date(),
|
||||
} as any);
|
||||
id = Number((res as any).identifiers?.[0]?.id || 0);
|
||||
} catch (e) {
|
||||
const again = await this.findMenu(parentId, node.router);
|
||||
id = again ? Number(again.id) : 0;
|
||||
}
|
||||
} else {
|
||||
// 已存在:只补空字段,不覆盖管理台人工改动
|
||||
const patch: any = {};
|
||||
if (!row.viewPath) patch.viewPath = node.viewPath;
|
||||
if (!row.icon && node.icon) patch.icon = node.icon;
|
||||
if (!row.perms && node.perms) patch.perms = node.perms;
|
||||
if (!Number(row.orderNum)) patch.orderNum = order;
|
||||
if (Object.keys(patch).length) {
|
||||
try {
|
||||
await this.menuRepo.update({ id }, patch);
|
||||
} catch (e) {
|
||||
/* 忽略 */
|
||||
}
|
||||
}
|
||||
}
|
||||
if (node.children?.length && id) {
|
||||
await this.seedMenus(node.children, id, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async findMenu(parentId: number | null, router: string): Promise<BaseSysMenuEntity | null> {
|
||||
const rows = await this.menuRepo.findBy({ router });
|
||||
const pid = Number(parentId || 0);
|
||||
return rows.find(r => Number(r.parentId || 0) === pid) || null;
|
||||
}
|
||||
|
||||
private async ensureRuntimeAdmin(roleId: number): Promise<void> {
|
||||
let user = await this.getUserByUsername(RUNTIME_ADMIN.username);
|
||||
if (!user) {
|
||||
try {
|
||||
await this.userRepo.insert({
|
||||
username: RUNTIME_ADMIN.username,
|
||||
password: md5(RUNTIME_ADMIN.password),
|
||||
passwordV: 1,
|
||||
name: RUNTIME_ADMIN.username,
|
||||
nickName: RUNTIME_ADMIN.username,
|
||||
status: 1,
|
||||
createTime: new Date(),
|
||||
updateTime: new Date(),
|
||||
} as any);
|
||||
} catch (e) {
|
||||
/* 并发插入忽略 */
|
||||
}
|
||||
user = await this.getUserByUsername(RUNTIME_ADMIN.username);
|
||||
}
|
||||
if (!user || !roleId) return;
|
||||
const exists = await this.userRoleRepo.findOneBy({ userId: user.id, roleId });
|
||||
if (!exists) {
|
||||
try {
|
||||
await this.userRoleRepo.insert({
|
||||
userId: user.id,
|
||||
roleId,
|
||||
createTime: new Date(),
|
||||
updateTime: new Date(),
|
||||
} as any);
|
||||
} catch (e) {
|
||||
/* 忽略 */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async cleanTestUser(username: string): Promise<void> {
|
||||
const user = await this.getUserByUsername(username);
|
||||
if (!user) return;
|
||||
try {
|
||||
await this.userRoleRepo.delete({ userId: user.id });
|
||||
await this.userRepo.delete({ id: user.id });
|
||||
} catch (e) {
|
||||
/* 忽略 */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 去重(保留顺序) */
|
||||
function unique(list: string[]): string[] {
|
||||
const out: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const item of list) {
|
||||
if (!seen.has(item)) {
|
||||
seen.add(item);
|
||||
out.push(item);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 数据库菜单行 → 前端路由节点(name 需与前端命名一致,component 取 viewPath) */
|
||||
function toNode(row: BaseSysMenuEntity, usedNames: Set<string>): ConsoleMenuNode {
|
||||
const isDir = Number(row.type) === 0;
|
||||
const viewPath = String(row.viewPath || '');
|
||||
const router = String(row.router || '');
|
||||
const component = isDir ? viewPath || '/index/index' : viewPath || router;
|
||||
const meta: ConsoleMenuNode['meta'] = {
|
||||
title: String(row.name || router || ''),
|
||||
icon: String(row.icon || ''),
|
||||
perms: splitPerms(row.perms),
|
||||
};
|
||||
if (row.keepAlive === false) meta.keepAlive = false;
|
||||
if (row.isShow === false) meta.isHide = true;
|
||||
return {
|
||||
path: router,
|
||||
name: routeName(viewPath, router, usedNames),
|
||||
component,
|
||||
meta,
|
||||
};
|
||||
}
|
||||
|
||||
function routeName(viewPath: string, router: string, used: Set<string>): string {
|
||||
const key = `/${String(viewPath || '').replace(/^\/+|\/+$/g, '')}`;
|
||||
let base = ROUTE_NAME_BY_VIEW[key] || '';
|
||||
if (!base) {
|
||||
const segs = (viewPath || router).split('/').filter(s => s && s !== 'index');
|
||||
base = pascal(segs[segs.length - 1] || 'menu') || 'Menu';
|
||||
}
|
||||
let name = base;
|
||||
let i = 2;
|
||||
while (used.has(name)) name = `${base}${i++}`;
|
||||
used.add(name);
|
||||
return name;
|
||||
}
|
||||
|
||||
/** 以 parentId 组树;无子级的目录(type=0)不输出 */
|
||||
function buildTree(rows: BaseSysMenuEntity[]): ConsoleMenuNode[] {
|
||||
const used = new Set<string>();
|
||||
const map = new Map<number, { node: ConsoleMenuNode; type: number }>();
|
||||
rows.forEach(r => map.set(Number(r.id), { node: toNode(r, used), type: Number(r.type) }));
|
||||
const roots: ConsoleMenuNode[] = [];
|
||||
rows.forEach(r => {
|
||||
const item = map.get(Number(r.id));
|
||||
if (!item) return;
|
||||
const pid = Number(r.parentId || 0);
|
||||
const parent = pid ? map.get(pid) : null;
|
||||
if (parent) {
|
||||
parent.node.children = parent.node.children || [];
|
||||
parent.node.children.push(item.node);
|
||||
} else {
|
||||
roots.push(item.node);
|
||||
}
|
||||
});
|
||||
const prune = (nodes: ConsoleMenuNode[]): ConsoleMenuNode[] =>
|
||||
nodes.reduce((acc: ConsoleMenuNode[], n) => {
|
||||
const isLayout = n.component === '/index/index';
|
||||
if (n.children?.length) {
|
||||
n.children = prune(n.children);
|
||||
if (n.children.length || !isLayout) acc.push(n);
|
||||
} else if (!isLayout) {
|
||||
acc.push(n);
|
||||
}
|
||||
return acc;
|
||||
}, []);
|
||||
return prune(roots);
|
||||
}
|
||||
Reference in New Issue
Block a user