build(desktop): 升级 electron-shell 版本至 1.6.3 并调整插件执行超时配置

- 插件执行超时默认延长至 6 小时,支持插件单独配置超时时间
- 新增插件根目录迁移逻辑,解决旧版权限问题
- 新增多个服务端实体、DTO、配置模块等基础代码
- 新增插件 UI 模板及相关静态资源
This commit is contained in:
2026-10-15 11:38:45 +08:00
parent 3dcedf95fd
commit f27639777f
717 changed files with 88647 additions and 17543 deletions
@@ -0,0 +1,40 @@
import { BaseLogMiddleware } from './middleware/log';
import { BaseAuthorityMiddleware } from './middleware/authority';
import { ModuleConfig } from '@cool-midway/core';
import { BaseTranslateMiddleware } from './middleware/translate';
/**
* 模块的配置
*/
export default () => {
return {
// 模块名称
name: '权限管理',
// 模块描述
description: '基础的权限管理功能,包括登录,权限校验',
// 中间件
globalMiddlewares: [
BaseTranslateMiddleware,
BaseAuthorityMiddleware,
BaseLogMiddleware,
],
// 模块加载顺序,默认为0,值越大越优先加载
order: 10,
// app参数配置允许读取的key
allowKeys: [],
// jwt 生成解密token的
jwt: {
// 单点登录
sso: false,
// 注意: 最好重新修改,防止破解
secret: 'b4d495aa-a0b0-4275-8a0c-7b34fd88a01a',
// token
token: {
// 2小时过期,需要用刷新token
expire: 2 * 3600,
// 15天内,如果没操作过就需要重新登录
refreshExpire: 24 * 3600 * 15,
},
},
} as ModuleConfig;
};
@@ -0,0 +1,29 @@
import { CoolController, BaseController } from '@cool-midway/core';
import { Body, Get, Inject, Post } from '@midwayjs/core';
import { BaseCodingService } from '../../service/coding';
/**
* Ai编码
*/
@CoolController()
export class AdminCodingController extends BaseController {
@Inject()
baseCodingService: BaseCodingService;
@Get('/getModuleTree', { summary: '获取模块目录结构' })
async getModuleTree() {
return this.ok(await this.baseCodingService.getModuleTree());
}
@Post('/createCode', { summary: '创建代码' })
async createCode(
@Body('codes')
codes: {
path: string;
content: string;
}[]
) {
this.baseCodingService.createCode(codes);
return this.ok();
}
}
@@ -0,0 +1,99 @@
import {
BaseController,
CoolController,
CoolTag,
CoolUrlTag,
TagTypes,
} from '@cool-midway/core';
import { ALL, Body, Get, Inject, Post, Provide } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { PluginService } from '../../../plugin/service/info';
import { BaseSysUserEntity } from '../../entity/sys/user';
import { BaseSysLoginService } from '../../service/sys/login';
import { BaseSysPermsService } from '../../service/sys/perms';
import { BaseSysUserService } from '../../service/sys/user';
/**
* Base 通用接口 一般写不需要权限过滤的接口
*/
@CoolUrlTag()
@Provide()
@CoolController()
export class BaseCommController extends BaseController {
@Inject()
baseSysUserService: BaseSysUserService;
@Inject()
baseSysPermsService: BaseSysPermsService;
@Inject()
baseSysLoginService: BaseSysLoginService;
@Inject()
ctx: Context;
@Inject()
pluginService: PluginService;
/**
* 获得个人信息
*/
@Get('/person', { summary: '个人信息' })
async person() {
return this.ok(
await this.baseSysUserService.person(this.ctx.admin?.userId)
);
}
/**
* 修改个人信息
*/
@Post('/personUpdate', { summary: '修改个人信息' })
async personUpdate(@Body(ALL) user: BaseSysUserEntity) {
await this.baseSysUserService.personUpdate(user);
return this.ok();
}
/**
* 权限菜单
*/
@Get('/permmenu', { summary: '权限与菜单' })
async permmenu() {
return this.ok(
await this.baseSysPermsService.permmenu(this.ctx.admin.roleIds)
);
}
/**
* 文件上传
*/
@Post('/upload', { summary: '文件上传' })
async upload() {
const file = await this.pluginService.getInstance('upload');
return this.ok(await file.upload(this.ctx));
}
/**
* 文件上传模式,本地或者云存储
*/
@Get('/uploadMode', { summary: '文件上传模式' })
async uploadMode() {
const file = await this.pluginService.getInstance('upload');
return this.ok(await file.getMode());
}
/**
* 退出
*/
@Post('/logout', { summary: '退出' })
async logout() {
await this.baseSysLoginService.logout();
return this.ok();
}
@CoolTag(TagTypes.IGNORE_TOKEN)
@Get('/program', { summary: '编程' })
async program() {
return this.ok('Node');
}
}
@@ -0,0 +1,98 @@
import { Provide, Body, Inject, Post, Get, Query } from '@midwayjs/core';
import {
CoolController,
BaseController,
CoolEps,
CoolUrlTag,
CoolTag,
TagTypes,
RESCODE,
} from '@cool-midway/core';
import { LoginDTO } from '../../dto/login';
import { BaseSysLoginService } from '../../service/sys/login';
import { BaseSysParamService } from '../../service/sys/param';
import { Context } from '@midwayjs/koa';
import { Validate } from '@midwayjs/validate';
/**
* 不需要登录的后台接口
*/
@Provide()
@CoolController({ description: '开放接口' })
@CoolUrlTag()
export class BaseOpenController extends BaseController {
@Inject()
baseSysLoginService: BaseSysLoginService;
@Inject()
baseSysParamService: BaseSysParamService;
@Inject()
ctx: Context;
@Inject()
eps: CoolEps;
/**
* 实体信息与路径
* @returns
*/
@CoolTag(TagTypes.IGNORE_TOKEN)
@Get('/eps', { summary: '实体信息与路径' })
public async getEps() {
return this.ok(this.eps.admin);
}
/**
* 根据配置参数key获得网页内容(富文本)
*/
@CoolTag(TagTypes.IGNORE_TOKEN)
@Get('/html', { summary: '获得网页内容的参数值' })
async htmlByKey(@Query('key') key: string) {
this.ctx.body = await this.baseSysParamService.htmlByKey(key);
}
/**
* 登录
* @param login
*/
@CoolTag(TagTypes.IGNORE_TOKEN)
@Post('/login', { summary: '登录' })
@Validate()
async login(@Body() login: LoginDTO) {
return this.ok(await this.baseSysLoginService.login(login));
}
/**
* 获得验证码
*/
@CoolTag(TagTypes.IGNORE_TOKEN)
@Get('/captcha', { summary: '验证码' })
async captcha(
@Query('width') width: number,
@Query('height') height: number,
@Query('color') color: string
) {
return this.ok(
await this.baseSysLoginService.captcha(width, height, color)
);
}
/**
* 刷新token
*/
@CoolTag(TagTypes.IGNORE_TOKEN)
@Get('/refreshToken', { summary: '刷新token' })
async refreshToken(@Query('refreshToken') refreshToken: string) {
try {
const token = await this.baseSysLoginService.refreshToken(refreshToken);
return this.ok(token);
} catch (e) {
this.ctx.status = 401;
this.ctx.body = {
code: RESCODE.COMMFAIL,
message: '登录失效~',
};
}
}
}
@@ -0,0 +1,32 @@
import { ALL, Body, Inject, Post, Provide } from '@midwayjs/core';
import { CoolController, BaseController } from '@cool-midway/core';
import { BaseSysDepartmentEntity } from '../../../entity/sys/department';
import { BaseSysDepartmentService } from '../../../service/sys/department';
/**
* 部门
*/
@Provide()
@CoolController({
api: ['add', 'delete', 'update', 'list'],
entity: BaseSysDepartmentEntity,
service: BaseSysDepartmentService,
insertParam: ctx => {
return {
userId: ctx.admin.userId,
};
},
})
export class BaseDepartmentController extends BaseController {
@Inject()
baseDepartmentService: BaseSysDepartmentService;
/**
* 部门排序
*/
@Post('/order', { summary: '排序' })
async order(@Body(ALL) params: any) {
await this.baseDepartmentService.order(params);
return this.ok();
}
}
@@ -0,0 +1,64 @@
import { Provide, Post, Inject, Body, Get } from '@midwayjs/core';
import { CoolController, BaseController } from '@cool-midway/core';
import { BaseSysLogEntity } from '../../../entity/sys/log';
import { BaseSysUserEntity } from '../../../entity/sys/user';
import { BaseSysConfService } from '../../../service/sys/conf';
import { BaseSysLogService } from '../../../service/sys/log';
/**
* 系统日志
*/
@Provide()
@CoolController({
api: ['page'],
entity: BaseSysLogEntity,
urlTag: {
name: 'a',
url: ['add'],
},
pageQueryOp: {
keyWordLikeFields: ['b.name', 'a.action', 'a.ip'],
select: ['a.*', 'b.name'],
join: [
{
entity: BaseSysUserEntity,
alias: 'b',
condition: 'a.userId = b.id',
type: 'leftJoin',
},
],
},
})
export class BaseSysLogController extends BaseController {
@Inject()
baseSysLogService: BaseSysLogService;
@Inject()
baseSysConfService: BaseSysConfService;
/**
* 清空日志
*/
@Post('/clear', { summary: '清理' })
public async clear() {
await this.baseSysLogService.clear(true);
return this.ok();
}
/**
* 设置日志保存时间
*/
@Post('/setKeep', { summary: '日志保存时间' })
public async setKeep(@Body('value') value: number) {
await this.baseSysConfService.updateVaule('logKeep', value);
return this.ok();
}
/**
* 获得日志保存时间
*/
@Get('/getKeep', { summary: '获得日志保存时间' })
public async getKeep() {
return this.ok(await this.baseSysConfService.getValue('logKeep'));
}
}
@@ -0,0 +1,46 @@
import { Body, Inject, Post, Provide } from '@midwayjs/core';
import { CoolController, BaseController } from '@cool-midway/core';
import { BaseSysMenuEntity } from '../../../entity/sys/menu';
import { BaseSysMenuService } from '../../../service/sys/menu';
/**
* 菜单
*/
@Provide()
@CoolController({
api: ['add', 'delete', 'update', 'info', 'list', 'page'],
entity: BaseSysMenuEntity,
service: BaseSysMenuService,
})
export class BaseSysMenuController extends BaseController {
@Inject()
baseSysMenuService: BaseSysMenuService;
@Post('/parse', { summary: '解析' })
async parse(
@Body('entity') entity: string,
@Body('controller') controller: string,
@Body('module') module: string
) {
return this.ok(
await this.baseSysMenuService.parse(entity, controller, module)
);
}
@Post('/create', { summary: '创建代码' })
async create(@Body() body) {
await this.baseSysMenuService.create(body);
return this.ok();
}
@Post('/export', { summary: '导出' })
async export(@Body('ids') ids: number[]) {
return this.ok(await this.baseSysMenuService.export(ids));
}
@Post('/import', { summary: '导入' })
async import(@Body('menus') menus: any[]) {
await this.baseSysMenuService.import(menus);
return this.ok();
}
}
@@ -0,0 +1,34 @@
import { Get, Inject, Provide, Query } from '@midwayjs/core';
import { CoolController, BaseController } from '@cool-midway/core';
import { BaseSysParamEntity } from '../../../entity/sys/param';
import { BaseSysParamService } from '../../../service/sys/param';
import { Context } from '@midwayjs/koa';
/**
* 参数配置
*/
@Provide()
@CoolController({
api: ['add', 'delete', 'update', 'info', 'page'],
entity: BaseSysParamEntity,
service: BaseSysParamService,
pageQueryOp: {
keyWordLikeFields: ['name', 'keyName'],
fieldEq: ['dataType'],
},
})
export class BaseSysParamController extends BaseController {
@Inject()
baseSysParamService: BaseSysParamService;
@Inject()
ctx: Context;
/**
* 根据配置参数key获得网页内容(富文本)
*/
@Get('/html', { summary: '获得网页内容的参数值' })
async htmlByKey(@Query('key') key: string) {
this.ctx.body = await this.baseSysParamService.htmlByKey(key);
}
}
@@ -0,0 +1,38 @@
import { Provide } from '@midwayjs/core';
import { CoolController, BaseController } from '@cool-midway/core';
import { Context } from 'vm';
import { BaseSysRoleEntity } from '../../../entity/sys/role';
import { BaseSysRoleService } from '../../../service/sys/role';
/**
* 系统角色
*/
@Provide()
@CoolController({
api: ['add', 'delete', 'update', 'info', 'list', 'page'],
entity: BaseSysRoleEntity,
service: BaseSysRoleService,
// 新增的时候插入当前用户ID
insertParam: async (ctx: Context) => {
return {
userId: ctx.admin.userId,
};
},
pageQueryOp: {
keyWordLikeFields: ['a.name', 'a.label'],
where: async (ctx: Context) => {
const { userId, roleIds, username } = ctx.admin;
return [
// 超级管理员的角色不展示
['a.label != :label', { label: 'admin' }],
// 如果不是超管,只能看到自己新建的或者自己有的角色
[
`(a.userId=:userId or a.id in (${roleIds.join(',')}))`,
{ userId },
username !== 'admin',
],
];
},
},
})
export class BaseSysRoleController extends BaseController {}
@@ -0,0 +1,35 @@
import { Body, Inject, Post, Provide } from '@midwayjs/core';
import { CoolController, BaseController } from '@cool-midway/core';
import { BaseSysUserEntity } from '../../../entity/sys/user';
import { BaseSysUserService } from '../../../service/sys/user';
/**
* 系统用户
*/
@Provide()
@CoolController({
api: ['add', 'delete', 'update', 'info', 'list', 'page'],
entity: BaseSysUserEntity,
service: BaseSysUserService,
insertParam: ctx => {
return {
userId: ctx.admin.userId,
};
},
})
export class BaseSysUserController extends BaseController {
@Inject()
baseSysUserService: BaseSysUserService;
/**
* 移动部门
*/
@Post('/move', { summary: '移动部门' })
async move(
@Body('departmentId') departmentId: number,
@Body('userIds') userIds: []
) {
await this.baseSysUserService.move(departmentId, userIds);
return this.ok();
}
}
@@ -0,0 +1 @@
这里写对外的api接口
@@ -0,0 +1,72 @@
import { Provide, Inject, Get, Post, Query, Config } from '@midwayjs/core';
import {
CoolController,
BaseController,
CoolEps,
TagTypes,
CoolUrlTag,
CoolTag,
} from '@cool-midway/core';
import { Context } from '@midwayjs/koa';
import { BaseSysParamService } from '../../service/sys/param';
import { PluginService } from '../../../plugin/service/info';
/**
* 不需要登录的后台接口
*/
@CoolUrlTag()
@Provide()
@CoolController()
export class BaseAppCommController extends BaseController {
@Inject()
pluginService: PluginService;
@Inject()
ctx: Context;
@Config('module.base.allowKeys')
allowKeys: string[];
@Inject()
eps: CoolEps;
@Inject()
baseSysParamService: BaseSysParamService;
@CoolTag(TagTypes.IGNORE_TOKEN)
@Get('/param', { summary: '参数配置' })
async param(@Query('key') key: string) {
if (!this.allowKeys.includes(key)) {
return this.fail('非法操作');
}
return this.ok(await this.baseSysParamService.dataByKey(key));
}
/**
* 实体信息与路径
* @returns
*/
@CoolTag(TagTypes.IGNORE_TOKEN)
@Get('/eps', { summary: '实体信息与路径' })
public async getEps() {
return this.ok(this.eps.app);
}
/**
* 文件上传
*/
@Post('/upload', { summary: '文件上传' })
async upload() {
const file = await this.pluginService.getInstance('upload');
return this.ok(await file.upload(this.ctx));
}
/**
* 文件上传模式,本地或者云存储
*/
@Get('/uploadMode', { summary: '文件上传模式' })
async uploadMode() {
const file = await this.pluginService.getInstance('upload');
return this.ok(await file.getMode());
}
}
@@ -0,0 +1,102 @@
{
"base_sys_param": [
{
"keyName": "rich",
"name": "富文本参数",
"data": "<h3><strong>这是一个富文本</strong></h3><p>xxx</p><p>xxxxxxxxxx</p><p><br></p>",
"dataType": 1,
"remark": null
},
{
"keyName": "json",
"name": "JSON参数",
"data": "{\n \"code\": 111233\n}",
"dataType": 0,
"remark": null
},
{
"keyName": "file",
"name": "文件",
"data": "",
"dataType": 2,
"remark": null
},
{
"keyName": "text",
"name": "测试",
"data": "这是一段字符串",
"dataType": 0,
"remark": null
}
],
"base_sys_conf": [
{
"cKey": "logKeep",
"cValue": "31"
},
{
"cKey": "recycleKeep",
"cValue": "31"
}
],
"base_sys_department": [
{
"id": 1,
"name": "COOL",
"parentId": null,
"orderNum": 0
},
{
"id": 11,
"name": "开发",
"parentId": 12,
"orderNum": 2
},
{
"id": 12,
"name": "测试",
"parentId": 1,
"orderNum": 1
},
{
"id": 13,
"name": "游客",
"parentId": 1,
"orderNum": 3
}
],
"base_sys_role": [
{
"id": 1,
"userId": "1",
"name": "超管",
"label": "admin",
"remark": "最高权限的角色",
"relevance": 1,
"menuIdList": "null",
"departmentIdList": "null"
}
],
"base_sys_user": [
{
"id": 1,
"departmentId": 1,
"name": "超级管理员",
"username": "admin",
"password": "e10adc3949ba59abbe56e057f20f883e",
"passwordV": 7,
"nickName": "管理员",
"phone": "18000000000",
"email": "team@cool-js.com",
"status": 1,
"remark": "拥有最高权限的用户",
"socketId": null
}
],
"base_sys_user_role": [
{
"userId": 1,
"roleId": 1
}
]
}
@@ -0,0 +1,213 @@
import { EventSubscriberModel } from '@midwayjs/typeorm';
import {
DeleteQueryBuilder,
EntitySubscriberInterface,
InsertQueryBuilder,
SelectQueryBuilder,
UpdateQueryBuilder,
} from 'typeorm';
import * as _ from 'lodash';
import {
App,
ASYNC_CONTEXT_KEY,
ASYNC_CONTEXT_MANAGER_KEY,
AsyncContextManager,
Config,
IMidwayApplication,
IMidwayContext,
Inject,
} from '@midwayjs/core';
import { Utils } from '../../../comm/utils';
import { CoolUrlTagData, TagTypes } from '@cool-midway/core';
/**
* 不操作租户
* @param ctx
* @param func
*/
export const noTenant = async (ctx, func) => {
let result;
const tenantId = ctx?.admin?.tenantId;
if (tenantId) {
ctx.admin.tenantId = null;
result = await func();
ctx.admin.tenantId = tenantId;
} else {
result = await func();
}
return result;
};
@EventSubscriberModel()
export class TenantSubscriber implements EntitySubscriberInterface<any> {
@App()
app: IMidwayApplication;
@Inject()
ctx: IMidwayContext;
@Inject()
coolUrlTagData: CoolUrlTagData;
@Config('cool.tenant')
tenant: {
// 是否开启多租户
enable: boolean;
// 需要过滤多租户的url
urls: string[];
};
// 系统接口不过滤
ignoreUrls = [
'/admin/base/open/login',
'/admin/base/comm/person',
'/admin/base/comm/permmenu',
'/admin/dict/info/data',
];
// 不进行租户过滤的用户
ignoreUsername = [];
@Inject()
utils: Utils;
/**
* 获取所有忽略的url
*/
getAllIgnoreUrls() {
const adminIgnoreUrls = this.coolUrlTagData.byKey(
TagTypes.IGNORE_TOKEN,
'admin'
);
const appIgnoreUrls = this.coolUrlTagData.byKey(
TagTypes.IGNORE_TOKEN,
'app'
);
this.ignoreUrls = [
...this.ignoreUrls,
...adminIgnoreUrls,
...appIgnoreUrls,
];
// 去重
this.ignoreUrls = _.uniq(this.ignoreUrls);
return this.ignoreUrls;
}
/**
* 检查是否需要租户
*/
checkHandler() {
const ctx = this.getCtx();
if (!ctx) return false;
const url = ctx?.url;
if (!url) return false;
if (this.tenant?.enable) {
const isNeedTenant = this.tenant.urls.some(pattern =>
this.utils.matchUrl(pattern, url)
);
return isNeedTenant;
}
return false;
}
/**
* 获取ctx
*/
getCtx(): any {
try {
const contextManager: AsyncContextManager = this.app
.getApplicationContext()
.get(ASYNC_CONTEXT_MANAGER_KEY);
return contextManager.active().getValue(ASYNC_CONTEXT_KEY);
} catch (error) {
return null;
}
}
/**
* 从登录的用户中获取租户ID
* @returns string | undefined
*/
getTenantId(): number | undefined {
let ctx, url, tenantId;
ctx = this.getCtx();
if (!ctx || !this.checkHandler()) return undefined;
url = ctx?.url;
// 忽略用户
if (this.ignoreUsername.includes(ctx?.admin?.username)) {
return undefined;
}
// 忽略系统接口
if (
this.getAllIgnoreUrls().some(pattern => this.utils.matchUrl(pattern, url))
) {
return undefined;
}
if (_.startsWith(url, '/admin/')) {
tenantId = ctx?.admin?.tenantId;
} else if (_.startsWith(url, '/app/')) {
tenantId = ctx?.user?.tenantId;
}
if (tenantId && url) {
return tenantId;
}
return undefined;
}
/**
* 查询时添加租户ID条件
* @param queryBuilder
*/
afterSelectQueryBuilder(queryBuilder: SelectQueryBuilder<any>) {
if (!this.tenant?.enable) return;
const tenantId = this.getTenantId();
if (tenantId) {
queryBuilder.andWhere(
`${
queryBuilder.alias ? queryBuilder.alias + '.' : ''
}tenantId = '${tenantId}'`
);
}
}
/**
* 插入时添加租户ID
* @param queryBuilder
*/
afterInsertQueryBuilder(queryBuilder: InsertQueryBuilder<any>) {
if (!this.tenant?.enable) return;
const tenantId = this.getTenantId();
if (tenantId) {
const values = queryBuilder.expressionMap.valuesSet;
if (Array.isArray(values)) {
queryBuilder.values(values.map(item => ({ ...item, tenantId })));
} else if (typeof values === 'object') {
queryBuilder.values({ ...values, tenantId });
}
}
}
/**
* 更新时添加租户ID和条件
* @param queryBuilder
*/
afterUpdateQueryBuilder(queryBuilder: UpdateQueryBuilder<any>) {
if (!this.tenant?.enable) return;
const tenantId = this.getTenantId();
if (tenantId) {
queryBuilder.andWhere(`tenantId = '${tenantId}'`);
}
}
/**
* 删除时添加租户ID和条件
* @param queryBuilder
*/
afterDeleteQueryBuilder(queryBuilder: DeleteQueryBuilder<any>) {
if (!this.tenant?.enable) return;
const tenantId = this.getTenantId();
if (tenantId) {
queryBuilder.andWhere(`tenantId = '${tenantId}'`);
}
}
}
@@ -0,0 +1,21 @@
import { Rule, RuleType } from '@midwayjs/validate';
/**
* 登录参数校验
*/
export class LoginDTO {
// 用户名
@Rule(RuleType.string().required())
username: string;
// 密码
@Rule(RuleType.string().required())
password: string;
// 验证码ID
@Rule(RuleType.string().required())
captchaId: string;
// 验证码
@Rule(RuleType.required())
verifyCode: number;
}
@@ -0,0 +1,65 @@
import { Index, PrimaryGeneratedColumn, Column } from 'typeorm';
import * as moment from 'moment';
import { CoolBaseEntity } from '@cool-midway/core';
/**
* 时间转换器
*/
export const transformerTime = {
to(value) {
return value
? moment(value).format('YYYY-MM-DD HH:mm:ss')
: moment().format('YYYY-MM-DD HH:mm:ss');
},
from(value) {
return value;
},
};
/**
* Json转换器
*/
export const transformerJson = {
to: value => value,
from: value => {
// 确保从数据库返回的是对象
if (typeof value === 'string') {
try {
return JSON.parse(value);
} catch (e) {
return value;
}
}
return value;
},
};
/**
* 实体基类
*/
export abstract class BaseEntity extends CoolBaseEntity {
// 默认自增
@PrimaryGeneratedColumn('increment', {
comment: 'ID',
})
id: number;
@Index()
@Column({
comment: '创建时间',
type: 'varchar',
transformer: transformerTime,
})
createTime: Date;
@Index()
@Column({
comment: '更新时间',
type: 'varchar',
transformer: transformerTime,
})
updateTime: Date;
@Index()
@Column({ comment: '租户ID', nullable: true })
tenantId: number;
}
@@ -0,0 +1,15 @@
import { Column, Index, Entity } from 'typeorm';
import { BaseEntity } from '../base';
/**
* 系统配置
*/
@Entity('base_sys_conf')
export class BaseSysConfEntity extends BaseEntity {
@Index({ unique: true })
@Column({ comment: '配置键' })
cKey: string;
@Column({ comment: '配置值' })
cValue: string;
}
@@ -0,0 +1,23 @@
import { BaseEntity } from '../base';
import { Column, Entity, Index } from 'typeorm';
/**
* 部门
*/
@Entity('base_sys_department')
export class BaseSysDepartmentEntity extends BaseEntity {
@Column({ comment: '部门名称' })
name: string;
@Index()
@Column({ comment: '创建者ID', nullable: true })
userId: number;
@Column({ comment: '上级部门ID', nullable: true })
parentId: number;
@Column({ comment: '排序', default: 0 })
orderNum: number;
// 父菜单名称
parentName: string;
}
@@ -0,0 +1,28 @@
import { BaseEntity, transformerJson } from '../base';
import { Column, Index, Entity } from 'typeorm';
/**
* 系统日志
*/
@Entity('base_sys_log')
export class BaseSysLogEntity extends BaseEntity {
@Index()
@Column({ comment: '用户ID', nullable: true })
userId: number;
@Index()
@Column({ comment: '行为' })
action: string;
@Index()
@Column({ comment: 'ip', nullable: true })
ip: string;
@Column({
comment: '参数',
nullable: true,
type: 'json',
transformer: transformerJson,
})
params: string;
}
@@ -0,0 +1,47 @@
import { BaseEntity } from '../base';
import { Column, Entity } from 'typeorm';
/**
* 菜单
*/
@Entity('base_sys_menu')
export class BaseSysMenuEntity extends BaseEntity {
@Column({ comment: '父菜单ID', nullable: true })
parentId: number;
@Column({ comment: '菜单名称' })
name: string;
@Column({ comment: '菜单地址', nullable: true })
router: string;
@Column({ comment: '权限标识', type: 'text', nullable: true })
perms: string;
@Column({
comment: '类型 0-目录 1-菜单 2-按钮',
default: 0,
})
type: number;
@Column({ comment: '图标', nullable: true })
icon: string;
@Column({ comment: '排序', default: 0 })
orderNum: number;
@Column({ comment: '视图地址', nullable: true })
viewPath: string;
@Column({ comment: '路由缓存', default: true })
keepAlive: boolean;
@Column({ comment: '是否显示', default: true })
isShow: boolean;
// 父菜单名称
parentName: string;
// 子菜单
childMenus: any;
}
@@ -0,0 +1,27 @@
import { BaseEntity } from '../base';
import { Column, Index, Entity } from 'typeorm';
/**
* 参数配置
*/
@Entity('base_sys_param')
export class BaseSysParamEntity extends BaseEntity {
@Index({ unique: true })
@Column({ comment: '键' })
keyName: string;
@Column({ comment: '名称' })
name: string;
@Column({ comment: '数据', type: 'text' })
data: string;
@Column({
comment: '数据类型 0-字符串 1-富文本 2-文件 ',
default: 0,
})
dataType: number;
@Column({ comment: '备注', nullable: true })
remark: string;
}
@@ -0,0 +1,31 @@
import { BaseEntity, transformerJson } from '../base';
import { Column, Index, Entity } from 'typeorm';
/**
* 角色
*/
@Entity('base_sys_role')
export class BaseSysRoleEntity extends BaseEntity {
@Column({ comment: '用户ID' })
userId: string;
@Index({ unique: true })
@Column({ comment: '名称' })
name: string;
@Index({ unique: true })
@Column({ comment: '角色标签', nullable: true, length: 50 })
label: string;
@Column({ comment: '备注', nullable: true })
remark: string;
@Column({ comment: '数据权限是否关联上下级', default: false })
relevance: boolean;
@Column({ comment: '菜单权限', type: 'json', transformer: transformerJson })
menuIdList: number[];
@Column({ comment: '部门权限', type: 'json', transformer: transformerJson })
departmentIdList: number[];
}
@@ -0,0 +1,14 @@
import { BaseEntity } from '../base';
import { Column, Entity } from 'typeorm';
/**
* 角色部门
*/
@Entity('base_sys_role_department')
export class BaseSysRoleDepartmentEntity extends BaseEntity {
@Column({ comment: '角色ID' })
roleId: number;
@Column({ comment: '部门ID' })
departmentId: number;
}
@@ -0,0 +1,14 @@
import { BaseEntity } from '../base';
import { Column, Entity } from 'typeorm';
/**
* 角色菜单
*/
@Entity('base_sys_role_menu')
export class BaseSysRoleMenuEntity extends BaseEntity {
@Column({ comment: '角色ID' })
roleId: number;
@Column({ comment: '菜单ID' })
menuId: number;
}
@@ -0,0 +1,58 @@
import { BaseEntity } from '../base';
import { Column, Index, Entity } from 'typeorm';
/**
* 系统用户
*/
@Entity('base_sys_user')
export class BaseSysUserEntity extends BaseEntity {
@Index()
@Column({ comment: '部门ID', nullable: true })
departmentId: number;
@Index()
@Column({ comment: '创建者ID', nullable: true })
userId: number;
@Column({ comment: '姓名', nullable: true })
name: string;
@Index({ unique: true })
@Column({ comment: '用户名', length: 100 })
username: string;
@Column({ comment: '密码' })
password: string;
@Column({
comment: '密码版本, 作用是改完密码,让原来的token失效',
default: 1,
})
passwordV: number;
@Column({ comment: '昵称', nullable: true })
nickName: string;
@Column({ comment: '头像', nullable: true })
headImg: string;
@Index()
@Column({ comment: '手机', nullable: true, length: 20 })
phone: string;
@Column({ comment: '邮箱', nullable: true })
email: string;
@Column({ comment: '备注', nullable: true })
remark: string;
@Column({ comment: '状态 0-禁用 1-启用', default: 1 })
status: number;
// 部门名称
departmentName: string;
// 角色ID列表
roleIdList: number[];
@Column({ comment: 'socketId', nullable: true })
socketId: string;
}
@@ -0,0 +1,14 @@
import { BaseEntity } from '../base';
import { Column, Entity } from 'typeorm';
/**
* 用户角色
*/
@Entity('base_sys_user_role')
export class BaseSysUserRoleEntity extends BaseEntity {
@Column({ comment: '用户ID' })
userId: number;
@Column({ comment: '角色ID' })
roleId: number;
}
@@ -0,0 +1,45 @@
import { CoolEvent, Event } from '@cool-midway/core';
import { App, ILogger, IMidwayApplication, Inject } from '@midwayjs/core';
/**
* 接收事件
*/
@CoolEvent()
export class BaseAppEvent {
@App()
app: IMidwayApplication;
@Inject()
logger: ILogger;
@Event('onServerReady')
async onServerReady() {
if (!process['pkg']) return;
const port = this.app.getConfig('koa.port') || 8001;
this.logger.info(`Server is running at http://127.0.0.1:${port}`);
const url = `http://127.0.0.1:${port}`;
// 使用 child_process 打开浏览器
const { exec } = require('child_process');
let command;
switch (process.platform) {
case 'darwin': // macOS
command = `open ${url}`;
break;
case 'win32': // Windows
command = `start ${url}`;
break;
default: // Linux
command = `xdg-open ${url}`;
break;
}
console.log('url=>', url);
exec(command, (error: any) => {
if (!error) {
this.logger.info(`Application has opened in browser at ${url}`);
}
});
}
}
@@ -0,0 +1,50 @@
import { CoolEvent, CoolEventManager, Event } from '@cool-midway/core';
import { BaseSysMenuService } from '../service/sys/menu';
import {
App,
ILogger,
IMidwayApplication,
Inject,
Logger,
} from '@midwayjs/core';
import { BaseTranslateService } from '../service/translate';
/**
* 导入菜单
*/
@CoolEvent()
export class BaseMenuEvent {
@Logger()
coreLogger: ILogger;
@Inject()
baseSysMenuService: BaseSysMenuService;
@App()
app: IMidwayApplication;
@Inject()
coolEventManager: CoolEventManager;
@Inject()
baseTranslateService: BaseTranslateService;
@Event('onMenuImport')
async onMenuImport(datas) {
for (const module in datas) {
await this.baseSysMenuService.import(datas[module]);
this.coreLogger.info(
'\x1B[36m [cool:module:base] midwayjs cool module base import [' +
module +
'] module menu success \x1B[0m'
);
}
this.coolEventManager.emit('onMenuInit', {});
this.baseTranslateService.check();
}
@Event('onServerReady')
async onServerReady() {
this.baseTranslateService.loadTranslations();
}
}
@@ -0,0 +1,25 @@
import { Job, IJob } from '@midwayjs/cron';
import { FORMAT, ILogger, Inject } from '@midwayjs/core';
import { BaseSysLogService } from '../service/sys/log';
/**
* 日志定时任务
*/
@Job({
cronTime: FORMAT.CRONTAB.EVERY_DAY,
start: true,
})
export class BaseLogJob implements IJob {
@Inject()
baseSysLogService: BaseSysLogService;
@Inject()
logger: ILogger;
async onTick() {
this.logger.info('清除日志定时任务开始执行');
const startTime = Date.now();
await this.baseSysLogService.clear();
this.logger.info(`清除日志定时任务结束,耗时:${Date.now() - startTime}ms`);
}
}
@@ -0,0 +1,943 @@
[
{
"name": "系统管理",
"router": "/sys",
"perms": null,
"type": 0,
"icon": "icon-set",
"orderNum": 2,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": [
{
"name": "权限管理",
"router": null,
"perms": null,
"type": 0,
"icon": "icon-auth",
"orderNum": 1,
"viewPath": null,
"keepAlive": false,
"isShow": true,
"childMenus": [
{
"name": "菜单列表",
"router": "/sys/menu",
"perms": null,
"type": 1,
"icon": "icon-menu",
"orderNum": 2,
"viewPath": "modules/base/views/menu/index.vue",
"keepAlive": true,
"isShow": true,
"childMenus": [
{
"name": "新增",
"router": null,
"perms": "base:sys:menu:add",
"type": 2,
"icon": null,
"orderNum": 1,
"viewPath": null,
"keepAlive": false,
"isShow": true,
"childMenus": []
},
{
"name": "删除",
"router": null,
"perms": "base:sys:menu:delete",
"type": 2,
"icon": null,
"orderNum": 2,
"viewPath": null,
"keepAlive": false,
"isShow": true,
"childMenus": []
},
{
"name": "查询",
"router": null,
"perms": "base:sys:menu:page,base:sys:menu:list,base:sys:menu:info",
"type": 2,
"icon": null,
"orderNum": 4,
"viewPath": null,
"keepAlive": false,
"isShow": true,
"childMenus": []
},
{
"name": "参数",
"router": "/test/aa",
"perms": null,
"type": 1,
"icon": "icon-goods",
"orderNum": 0,
"viewPath": "modules/base/views/info.vue",
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"name": "编辑",
"router": null,
"perms": "base:sys:menu:info,base:sys:menu:update",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
}
]
},
{
"name": "角色列表",
"router": "/sys/role",
"perms": null,
"type": 1,
"icon": "icon-dept",
"orderNum": 3,
"viewPath": "cool/modules/base/views/role.vue",
"keepAlive": true,
"isShow": true,
"childMenus": [
{
"name": "新增",
"router": null,
"perms": "base:sys:role:add",
"type": 2,
"icon": null,
"orderNum": 1,
"viewPath": null,
"keepAlive": false,
"isShow": true,
"childMenus": []
},
{
"name": "删除",
"router": null,
"perms": "base:sys:role:delete",
"type": 2,
"icon": null,
"orderNum": 2,
"viewPath": null,
"keepAlive": false,
"isShow": true,
"childMenus": []
},
{
"name": "修改",
"router": null,
"perms": "base:sys:role:update",
"type": 2,
"icon": null,
"orderNum": 3,
"viewPath": null,
"keepAlive": false,
"isShow": true,
"childMenus": []
},
{
"name": "查询",
"router": null,
"perms": "base:sys:role:page,base:sys:role:list,base:sys:role:info",
"type": 2,
"icon": null,
"orderNum": 4,
"viewPath": null,
"keepAlive": false,
"isShow": true,
"childMenus": []
}
]
},
{
"name": "用户列表",
"router": "/sys/user",
"perms": null,
"type": 1,
"icon": "icon-user",
"orderNum": 0,
"viewPath": "modules/base/views/user/index.vue",
"keepAlive": true,
"isShow": true,
"childMenus": [
{
"name": "部门列表",
"router": null,
"perms": "base:sys:department:list",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"name": "新增部门",
"router": null,
"perms": "base:sys:department:add",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"name": "更新部门",
"router": null,
"perms": "base:sys:department:update",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"name": "删除部门",
"router": null,
"perms": "base:sys:department:delete",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"name": "部门排序",
"router": null,
"perms": "base:sys:department:order",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"name": "用户转移",
"router": null,
"perms": "base:sys:user:move",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"name": "新增",
"router": null,
"perms": "base:sys:user:add",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"name": "删除",
"router": null,
"perms": "base:sys:user:delete",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"name": "修改",
"router": null,
"perms": "base:sys:user:delete,base:sys:user:update",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"name": "查询",
"router": null,
"perms": "base:sys:user:page,base:sys:user:list,base:sys:user:info",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
}
]
}
]
},
{
"name": "参数配置",
"router": null,
"perms": null,
"type": 0,
"icon": "icon-params",
"orderNum": 3,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": [
{
"name": "参数列表",
"router": "/sys/param",
"perms": null,
"type": 1,
"icon": "icon-menu",
"orderNum": 0,
"viewPath": "cool/modules/base/views/param.vue",
"keepAlive": true,
"isShow": true,
"childMenus": [
{
"name": "新增",
"router": null,
"perms": "base:sys:param:add",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"name": "修改",
"router": null,
"perms": "base:sys:param:info,base:sys:param:update",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"name": "删除",
"router": null,
"perms": "base:sys:param:delete",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"name": "查看",
"router": null,
"perms": "base:sys:param:page,base:sys:param:list,base:sys:param:info",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
}
]
}
]
},
{
"name": "监控管理",
"router": null,
"perms": null,
"type": 0,
"icon": "icon-monitor",
"orderNum": 9,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": [
{
"name": "请求日志",
"router": "/sys/log",
"perms": null,
"type": 1,
"icon": "icon-log",
"orderNum": 1,
"viewPath": "cool/modules/base/views/log.vue",
"keepAlive": true,
"isShow": true,
"childMenus": [
{
"name": "权限",
"router": null,
"perms": "base:sys:log:page,base:sys:log:clear,base:sys:log:getKeep,base:sys:log:setKeep",
"type": 2,
"icon": null,
"orderNum": 1,
"viewPath": null,
"keepAlive": false,
"isShow": true,
"childMenus": []
}
]
}
]
},
{
"name": "任务管理",
"router": null,
"perms": null,
"type": 0,
"icon": "icon-activity",
"orderNum": 9,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": [
{
"name": "任务列表",
"router": "/task/list",
"perms": null,
"type": 1,
"icon": "icon-menu",
"orderNum": 0,
"viewPath": "modules/task/views/list.vue",
"keepAlive": true,
"isShow": true,
"childMenus": [
{
"name": "权限",
"router": null,
"perms": "task:info:page,task:info:list,task:info:info,task:info:add,task:info:delete,task:info:update,task:info:stop,task:info:start,task:info:once,task:info:log",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
}
]
}
]
}
]
},
{
"name": "框架教程",
"router": "/tutorial",
"perms": null,
"type": 0,
"icon": "icon-task",
"orderNum": 98,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": [
{
"name": "文档官网",
"router": "/tutorial/doc",
"perms": null,
"type": 1,
"icon": "icon-log",
"orderNum": 0,
"viewPath": "https://admin.cool-js.com",
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"name": "crud 示例",
"router": "/demo/crud",
"perms": null,
"type": 1,
"icon": "icon-favor",
"orderNum": 1,
"viewPath": "modules/demo/views/crud/index.vue",
"keepAlive": true,
"isShow": true,
"childMenus": []
}
]
},
{
"name": "通用",
"router": null,
"perms": null,
"type": 0,
"icon": "icon-radioboxfill",
"orderNum": 99,
"viewPath": null,
"keepAlive": true,
"isShow": false,
"childMenus": [
{
"name": "图片上传",
"router": null,
"perms": "space:info:page,space:info:list,space:info:info,space:info:add,space:info:delete,space:info:update,space:type:page,space:type:list,space:type:info,space:type:add,space:type:delete,space:type:update",
"type": 2,
"icon": null,
"orderNum": 1,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
}
]
},
{
"name": "首页",
"router": "/",
"perms": null,
"type": 1,
"icon": null,
"orderNum": 0,
"viewPath": "modules/demo/views/home/index.vue",
"keepAlive": true,
"isShow": false,
"childMenus": []
},
{
"name": "数据管理",
"router": null,
"perms": null,
"type": 0,
"icon": "icon-data",
"orderNum": 7,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": [
{
"name": "字典管理",
"router": "/dict/list",
"perms": null,
"type": 1,
"icon": "icon-dict",
"orderNum": 3,
"viewPath": "modules/dict/views/list.vue",
"keepAlive": true,
"isShow": true,
"childMenus": [
{
"name": "删除",
"router": null,
"perms": "dict:info:delete",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"name": "修改",
"router": null,
"perms": "dict:info:update,dict:info:info",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"name": "获得字典数据",
"router": null,
"perms": "dict:info:data",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"name": "单个信息",
"router": null,
"perms": "dict:info:info",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"name": "列表查询",
"router": null,
"perms": "dict:info:list",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"name": "分页查询",
"router": null,
"perms": "dict:info:page",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"name": "新增",
"router": null,
"perms": "dict:info:add",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"name": "组权限",
"router": null,
"perms": "dict:type:list,dict:type:update,dict:type:delete,dict:type:add",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"name": "字典类型",
"router": null,
"perms": "dict:type:delete,dict:type:update,dict:type:info,dict:type:list,dict:type:page,dict:type:add",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
}
]
},
{
"name": "数据回收站",
"router": "/recycle/data",
"perms": null,
"type": 1,
"icon": "icon-delete",
"orderNum": 6,
"viewPath": "modules/recycle/views/data.vue",
"keepAlive": true,
"isShow": true,
"childMenus": [
{
"name": "恢复数据",
"router": null,
"perms": "recycle:data:restore",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"name": "单个信息",
"router": null,
"perms": "recycle:data:info",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"name": "分页查询",
"router": null,
"perms": "recycle:data:page",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
}
]
},
{
"name": "文件管理",
"router": "/upload/list",
"perms": null,
"type": 1,
"icon": "icon-log",
"orderNum": 5,
"viewPath": "modules/space/views/list.vue",
"keepAlive": true,
"isShow": true,
"childMenus": [
{
"name": "权限",
"router": null,
"perms": "space:type:delete,space:type:update,space:type:info,space:type:list,space:type:page,space:type:add,space:info:getConfig,space:info:delete,space:info:update,space:info:info,space:info:list,space:info:page,space:info:add",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
}
]
}
]
},
{
"name": "用户管理",
"router": null,
"perms": null,
"type": 0,
"icon": "icon-user",
"orderNum": 11,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": [
{
"name": "用户列表",
"router": "/user/list",
"perms": null,
"type": 1,
"icon": "icon-menu",
"orderNum": 1,
"viewPath": "modules/user/views/list.vue",
"keepAlive": true,
"isShow": true,
"childMenus": [
{
"name": "删除",
"router": null,
"perms": "user:info:delete",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"name": "修改",
"router": null,
"perms": "user:info:update,user:info:info",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"name": "单个信息",
"router": null,
"perms": "user:info:info",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"name": "列表查询",
"router": null,
"perms": "user:info:list",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"name": "分页查询",
"router": null,
"perms": "user:info:page",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"name": "新增",
"router": null,
"perms": "user:info:add",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
}
]
}
]
},
{
"name": "扩展管理",
"router": null,
"perms": null,
"type": 0,
"icon": "icon-favor",
"orderNum": 8,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": [
{
"tenantId": null,
"name": "插件列表",
"router": "/helper/plugins",
"perms": null,
"type": 1,
"icon": "icon-list",
"orderNum": 1,
"viewPath": "modules/helper/views/plugins.vue",
"keepAlive": true,
"isShow": true,
"childMenus": [
{
"tenantId": null,
"name": "删除",
"router": null,
"perms": "plugin:info:delete",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"tenantId": null,
"name": "分页查询",
"router": null,
"perms": "plugin:info:page",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"tenantId": null,
"name": "单个信息",
"router": null,
"perms": "plugin:info:info",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"tenantId": null,
"name": "安装插件",
"router": null,
"perms": "plugin:info:install",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"tenantId": null,
"name": "修改",
"router": null,
"perms": "plugin:info:update",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"tenantId": null,
"name": "列表查询",
"router": null,
"perms": "plugin:info:list",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
},
{
"tenantId": null,
"name": "新增",
"router": null,
"perms": "plugin:info:add",
"type": 2,
"icon": null,
"orderNum": 0,
"viewPath": null,
"keepAlive": true,
"isShow": true,
"childMenus": []
}
]
}
]
}
]
@@ -0,0 +1,134 @@
import { App, Config, Inject, Middleware } from '@midwayjs/core';
import * as _ from 'lodash';
import { CoolCommException, CoolUrlTagData, TagTypes } from '@cool-midway/core';
import * as jwt from 'jsonwebtoken';
import { NextFunction, Context } from '@midwayjs/koa';
import {
IMiddleware,
IMidwayApplication,
Init,
InjectClient,
} from '@midwayjs/core';
import { CachingFactory, MidwayCache } from '@midwayjs/cache-manager';
import { Utils } from '../../../comm/utils';
/**
* 权限校验
*/
@Middleware()
export class BaseAuthorityMiddleware
implements IMiddleware<Context, NextFunction>
{
@Config('koa.globalPrefix')
prefix;
@Config('module.base')
jwtConfig;
@InjectClient(CachingFactory, 'default')
midwayCache: MidwayCache;
@Inject()
coolUrlTagData: CoolUrlTagData;
@App()
app: IMidwayApplication;
@Inject()
utils: Utils;
ignoreUrls: string[] = [];
@Init()
async init() {
this.ignoreUrls = this.coolUrlTagData.byKey(TagTypes.IGNORE_TOKEN, 'admin');
}
resolve() {
return async (ctx: Context, next: NextFunction) => {
let statusCode = 200;
let { url } = ctx;
url = url.replace(this.prefix, '').split('?')[0];
const token = ctx.get('Authorization');
const adminUrl = '/admin/';
// 路由地址为 admin前缀的 需要权限校验
if (_.startsWith(url, adminUrl)) {
try {
ctx.admin = jwt.verify(token, this.jwtConfig.jwt.secret);
if (ctx.admin.isRefresh) {
ctx.status = 401;
throw new CoolCommException('登录失效~', ctx.status);
}
} catch (error) {}
// 使用matchUrl方法来检查URL是否应该被忽略
const isIgnored = this.ignoreUrls.some(pattern =>
this.utils.matchUrl(pattern, url)
);
if (isIgnored) {
await next();
return;
}
if (ctx.admin) {
const rToken = await this.midwayCache.get(
`admin:token:${ctx.admin.userId}`
);
// 判断密码版本是否正确
const passwordV = await this.midwayCache.get(
`admin:passwordVersion:${ctx.admin.userId}`
);
if (passwordV != ctx.admin.passwordVersion) {
throw new CoolCommException('登录失效~', 401);
}
// 超管拥有所有权限
if (ctx.admin.username == 'admin' && !ctx.admin.isRefresh) {
if (rToken !== token && this.jwtConfig.jwt.sso) {
throw new CoolCommException('登录失效~', 401);
} else {
await next();
return;
}
}
// 要登录每个人都有权限的接口
if (
new RegExp(`^${adminUrl}?.*/comm/`).test(url) ||
// 字典接口
url == '/admin/dict/info/data'
) {
await next();
return;
}
// 如果传的token是refreshToken则校验失败
if (ctx.admin.isRefresh) {
throw new CoolCommException('登录失效~', 401);
}
if (!rToken) {
throw new CoolCommException('登录失效或无权限访问~', 401);
}
if (rToken !== token && this.jwtConfig.jwt.sso) {
statusCode = 401;
} else {
let perms: string[] = await this.midwayCache.get(
`admin:perms:${ctx.admin.userId}`
);
if (!_.isEmpty(perms)) {
perms = perms.map(e => {
return e.replace(/:/g, '/');
});
if (!perms.includes(url.split('?')[0].replace('/admin/', ''))) {
statusCode = 403;
}
} else {
statusCode = 403;
}
}
} else {
statusCode = 401;
}
if (statusCode > 200) {
throw new CoolCommException('登录失效或无权限访问~', statusCode);
}
}
await next();
};
}
}
@@ -0,0 +1,26 @@
import { Middleware } from '@midwayjs/core';
import * as _ from 'lodash';
import { NextFunction, Context } from '@midwayjs/koa';
import { IMiddleware } from '@midwayjs/core';
import { BaseSysLogService } from '../service/sys/log';
/**
* 日志中间件
*/
@Middleware()
export class BaseLogMiddleware implements IMiddleware<Context, NextFunction> {
resolve() {
return async (ctx: Context, next: NextFunction) => {
const baseSysLogService = await ctx.requestContext.getAsync(
BaseSysLogService
);
baseSysLogService.record(
ctx,
ctx.url,
ctx.req.method === 'GET' ? ctx.request.query : ctx.request.body,
ctx.admin ? ctx.admin.userId : null
);
await next();
};
}
}
@@ -0,0 +1,119 @@
import { Config, ILogger, Middleware } from '@midwayjs/core';
import { NextFunction, Context } from '@midwayjs/koa';
import { IMiddleware, Inject } from '@midwayjs/core';
import { BaseTranslateService } from '../service/translate';
import * as _ from 'lodash';
import { RESCODE } from '@cool-midway/core';
/**
* 翻译中间件
*/
@Middleware()
export class BaseTranslateMiddleware
implements IMiddleware<Context, NextFunction>
{
@Inject()
baseTranslateService: BaseTranslateService;
@Inject()
logger: ILogger;
@Config('cool.i18n')
config: {
/** 是否开启 */
enable: boolean;
/** 语言 */
languages: string[];
/** 翻译服务 */
serviceUrl?: string;
};
resolve() {
return async (ctx, next: NextFunction) => {
const url = ctx.url;
const language = ctx.get('language');
let data;
try {
data = await next();
} catch (error) {
this.logger.error(error);
// 处理翻译消息
if (error.name == 'CoolCommException') {
if (error.message && error.message !== 'success') {
ctx.status = error.statusCode || 200;
ctx.body = {
code: RESCODE.COMMFAIL,
message: await this.baseTranslateService.translate(
'msg',
language,
error.message
),
};
return;
}
}
ctx.status = 200;
ctx.body = {
code: RESCODE.COMMFAIL,
message: error.message,
};
return;
}
if (!this.config.enable) {
return;
}
// 处理菜单翻译
if (url == '/admin/base/comm/permmenu') {
for (const menu of data.data.menus) {
if (menu.name) {
menu.name = await this.baseTranslateService.translate(
'menu',
language,
menu.name
);
}
}
}
if (url == '/admin/base/sys/menu/list') {
for (const menu of data.data) {
if (menu.name) {
menu.name = await this.baseTranslateService.translate(
'menu',
language,
menu.name
);
}
}
}
// 处理字典翻译
if (url == '/admin/dict/info/list') {
for (const dict of data.data) {
dict.name = await this.baseTranslateService.translate(
'dict:info',
language,
dict.name
);
}
}
if (url == '/admin/dict/type/page') {
for (const dict of data.data.list) {
dict.name = await this.baseTranslateService.translate(
'dict:type',
language,
dict.name
);
}
}
if (url == '/admin/dict/info/data' || url == '/app/dict/info/data') {
for (const key in data.data) {
for (const item of data.data[key]) {
item.name = await this.baseTranslateService.translate(
'dict:info',
language,
item.name
);
}
}
}
};
}
}
@@ -0,0 +1,79 @@
import { App, IMidwayApplication, Init, Inject, Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import * as fs from 'fs';
import * as path from 'path';
/**
* Ai编码
*/
@Provide()
export class BaseCodingService extends BaseService {
@App()
app: IMidwayApplication;
/**
* 获得模块目录结构
*/
async getModuleTree() {
if (this.app.getEnv() !== 'local') {
return [];
}
const moduleDir = await this.app.getBaseDir();
const modulesPath = path.join(moduleDir, 'modules');
// 返回modules下有多少个模块
const modules = fs.readdirSync(modulesPath);
return modules.filter(module => module !== '.DS_Store');
}
/**
* 创建代码
* @param codes 代码
*/
async createCode(
codes: {
path: string;
content: string;
}[]
) {
if (this.app.getEnv() !== 'local') {
throw new Error('只能在开发环境下创建代码');
}
const moduleDir = this.app.getAppDir();
for (const code of codes) {
// 格式化代码内容
const formattedContent = await this.formatContent(code.content);
// 获取完整的文件路径
const filePath = path.join(moduleDir, code.path);
// 确保目录存在
const dirPath = path.dirname(filePath);
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
}
// 写入文件
fs.writeFileSync(filePath, formattedContent, 'utf8');
}
}
/**
* 格式化内容
* @param content
*/
async formatContent(content: string) {
// 使用prettier格式化内容
const prettier = require('prettier');
return prettier.format(content, {
parser: 'typescript',
singleQuote: true,
trailingComma: 'all',
bracketSpacing: true,
arrowParens: 'avoid',
printWidth: 80,
});
}
}
@@ -0,0 +1,39 @@
import { Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { BaseSysConfEntity } from '../../entity/sys/conf';
/**
* 系统配置
*/
@Provide()
export class BaseSysConfService extends BaseService {
@InjectEntityModel(BaseSysConfEntity)
baseSysConfEntity: Repository<BaseSysConfEntity>;
/**
* 获得配置参数值
* @param key
*/
async getValue(key) {
const conf = await this.baseSysConfEntity.findOneBy({ cKey: key });
if (conf) {
return conf.cValue;
}
}
/**
* 更新配置参数
* @param cKey
* @param cValue
*/
async updateVaule(cKey, cValue) {
await this.baseSysConfEntity
.createQueryBuilder()
.update()
.where({ cKey })
.set({ cKey, cValue })
.execute();
}
}
@@ -0,0 +1,10 @@
import { DataSource } from 'typeorm';
export class TempDataSource extends DataSource {
/**
* 重新构造元数据
*/
async buildMetadatas() {
await super.buildMetadatas();
}
}
@@ -0,0 +1,126 @@
import { Inject, Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { In, Repository } from 'typeorm';
import { BaseSysDepartmentEntity } from '../../entity/sys/department';
import * as _ from 'lodash';
import { BaseSysRoleDepartmentEntity } from '../../entity/sys/role_department';
import { BaseSysPermsService } from './perms';
import { BaseSysUserEntity } from '../../entity/sys/user';
/**
* 描述
*/
@Provide()
export class BaseSysDepartmentService extends BaseService {
@InjectEntityModel(BaseSysDepartmentEntity)
baseSysDepartmentEntity: Repository<BaseSysDepartmentEntity>;
@InjectEntityModel(BaseSysUserEntity)
baseSysUserEntity: Repository<BaseSysUserEntity>;
@InjectEntityModel(BaseSysRoleDepartmentEntity)
baseSysRoleDepartmentEntity: Repository<BaseSysRoleDepartmentEntity>;
@Inject()
baseSysPermsService: BaseSysPermsService;
@Inject()
ctx;
/**
* 获得部门菜单
*/
async list() {
// 部门权限
const permsDepartmentArr = await this.baseSysPermsService.departmentIds(
this.ctx.admin.userId
);
// 过滤部门权限
const find = this.baseSysDepartmentEntity.createQueryBuilder('a');
if (this.ctx.admin.username !== 'admin') {
find.andWhere('a.id in (:...ids)', {
ids: !_.isEmpty(permsDepartmentArr) ? permsDepartmentArr : [null],
});
find.orWhere('a.userId = :userId', { userId: this.ctx.admin.userId });
}
find.addOrderBy('a.orderNum', 'ASC');
const departments: BaseSysDepartmentEntity[] = await find.getMany();
if (!_.isEmpty(departments)) {
departments.forEach(e => {
const parentMenu = departments.filter(m => {
e.parentId = parseInt(e.parentId + '');
if (e.parentId == m.id) {
return m.name;
}
});
if (!_.isEmpty(parentMenu)) {
e.parentName = parentMenu[0].name;
}
});
}
return departments;
}
/**
* 根据多个ID获得部门权限信息
* @param {[]} roleIds 数组
* @param isAdmin 是否超管
*/
async getByRoleIds(roleIds: number[], isAdmin) {
if (!_.isEmpty(roleIds)) {
if (isAdmin) {
const result = await this.baseSysDepartmentEntity.find();
return result.map(e => {
return e.id;
});
}
const result = await this.baseSysRoleDepartmentEntity
.createQueryBuilder('a')
.where('a.roleId in (:...roleIds)', { roleIds })
.getMany();
if (!_.isEmpty(result)) {
return _.uniq(
result.map(e => {
return e.departmentId;
})
);
}
}
return [];
}
/**
* 部门排序
* @param params
*/
async order(params) {
for (const e of params) {
await this.baseSysDepartmentEntity.update(e.id, e);
}
}
/**
* 删除
*/
async delete(ids: number[]) {
const { deleteUser } = this.ctx.request.body;
await super.delete(ids);
if (deleteUser) {
await this.baseSysUserEntity.delete({ departmentId: In(ids) });
} else {
const topDepartment = await this.baseSysDepartmentEntity
.createQueryBuilder('a')
.where('a.parentId is null')
.getOne();
if (topDepartment) {
await this.baseSysUserEntity.update(
{ departmentId: In(ids) },
{ departmentId: topDepartment.id }
);
}
}
}
}
@@ -0,0 +1,62 @@
import { Inject, Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { LessThan, Repository } from 'typeorm';
import * as _ from 'lodash';
import { BaseSysLogEntity } from '../../entity/sys/log';
import * as moment from 'moment';
import { Utils } from '../../../../comm/utils';
import { BaseSysConfService } from './conf';
import { Context } from '@midwayjs/koa';
/**
* 描述
*/
@Provide()
export class BaseSysLogService extends BaseService {
@Inject()
ctx;
@Inject()
utils: Utils;
@InjectEntityModel(BaseSysLogEntity)
baseSysLogEntity: Repository<BaseSysLogEntity>;
@Inject()
baseSysConfService: BaseSysConfService;
/**
* 记录
* @param url URL地址
* @param params 参数
* @param userId 用户ID
*/
async record(context: Context, url, params, userId) {
const ip = await this.utils.getReqIP(context);
const sysLog = new BaseSysLogEntity();
sysLog.userId = userId;
sysLog.ip = typeof ip === 'string' ? ip : ip.join(',');
sysLog.action = url.split('?')[0];
sysLog.params = params;
await this.baseSysLogEntity.insert(sysLog);
}
/**
* 日志
* @param isAll 是否清除全部
*/
async clear(isAll?) {
if (isAll) {
await this.baseSysLogEntity.clear();
return;
}
const keepDay = await this.baseSysConfService.getValue('logKeep');
if (keepDay) {
const beforeDate = moment().add(-keepDay, 'days').startOf('day').format('YYYY-MM-DD HH:mm:ss');
await this.baseSysLogEntity.createQueryBuilder().delete().where('createTime < :beforeDate', { beforeDate }).execute();
} else {
await this.baseSysLogEntity.clear();
}
}
}
@@ -0,0 +1,243 @@
import { Inject, Provide, Config, InjectClient } from '@midwayjs/core';
import { BaseService, CoolCommException } from '@cool-midway/core';
import { LoginDTO } from '../../dto/login';
import { v1 as uuid } from 'uuid';
import { BaseSysUserEntity } from '../../entity/sys/user';
import { Repository } from 'typeorm';
import { InjectEntityModel } from '@midwayjs/typeorm';
import * as md5 from 'md5';
import { BaseSysRoleService } from './role';
import * as _ from 'lodash';
import { BaseSysMenuService } from './menu';
import { BaseSysDepartmentService } from './department';
import * as jwt from 'jsonwebtoken';
import { Context } from '@midwayjs/koa';
import { CachingFactory, MidwayCache } from '@midwayjs/cache-manager';
import { Utils } from '../../../../comm/utils';
import * as svgCaptcha from 'svg-captcha';
/**
* 登录
*/
@Provide()
export class BaseSysLoginService extends BaseService {
@InjectClient(CachingFactory, 'default')
midwayCache: MidwayCache;
@InjectEntityModel(BaseSysUserEntity)
baseSysUserEntity: Repository<BaseSysUserEntity>;
@Inject()
baseSysRoleService: BaseSysRoleService;
@Inject()
baseSysMenuService: BaseSysMenuService;
@Inject()
baseSysDepartmentService: BaseSysDepartmentService;
@Inject()
ctx: Context;
@Inject()
utils: Utils;
@Config('module.base')
coolConfig;
/**
* 登录
* @param login
*/
async login(login: LoginDTO) {
const { username, captchaId, verifyCode, password } = login;
// 校验验证码
const checkV = await this.captchaCheck(captchaId, verifyCode);
if (checkV) {
const user = await this.baseSysUserEntity.findOneBy({ username });
// 校验用户
if (user) {
// 校验用户状态及密码
if (user.status === 0 || user.password !== md5(password)) {
throw new CoolCommException('账户或密码不正确~');
}
} else {
throw new CoolCommException('账户或密码不正确~');
}
// 校验角色
const roleIds = await this.baseSysRoleService.getByUser(user.id);
if (_.isEmpty(roleIds)) {
throw new CoolCommException('该用户未设置任何角色,无法登录~');
}
// 生成token
const { expire, refreshExpire } = this.coolConfig.jwt.token;
const result = {
expire,
token: await this.generateToken(user, roleIds, expire),
refreshExpire,
refreshToken: await this.generateToken(
user,
roleIds,
refreshExpire,
true
),
};
// 将用户相关信息保存到缓存
const perms = await this.baseSysMenuService.getPerms(roleIds);
const departments = await this.baseSysDepartmentService.getByRoleIds(
roleIds,
user.username === 'admin'
);
await this.midwayCache.set(`admin:department:${user.id}`, departments);
await this.midwayCache.set(`admin:perms:${user.id}`, perms);
await this.midwayCache.set(`admin:token:${user.id}`, result.token);
await this.midwayCache.set(
`admin:token:refresh:${user.id}`,
result.token
);
return result;
} else {
throw new CoolCommException('验证码不正确');
}
}
/**
* 验证码
* @param width 宽
* @param height 高
*/
async captcha(width = 150, height = 50, color = '#fff') {
const svg = svgCaptcha.create({
// ignoreChars: 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM',
width,
height,
noise: 3,
});
const result = {
captchaId: uuid(),
data: svg.data.replace(/"/g, "'"),
};
// 文字变白
const rpList = [
'#111',
'#222',
'#333',
'#444',
'#555',
'#666',
'#777',
'#888',
'#999',
];
rpList.forEach(rp => {
result.data = result.data['replaceAll'](rp, color);
});
// Convert SVG to base64
const base64Data = Buffer.from(result.data).toString('base64');
result.data = `data:image/svg+xml;base64,${base64Data}`;
// 半小时过期
await this.midwayCache.set(
`verify:img:${result.captchaId}`,
svg.text.toLowerCase(),
1800 * 1000
);
return result;
}
/**
* 退出登录
*/
async logout() {
if (!this.coolConfig.jwt.sso) return;
const { userId } = this.ctx.admin;
await this.midwayCache.del(`admin:department:${userId}`);
await this.midwayCache.del(`admin:perms:${userId}`);
await this.midwayCache.del(`admin:token:${userId}`);
await this.midwayCache.del(`admin:token:refresh:${userId}`);
await this.midwayCache.del(`admin:passwordVersion:${userId}`);
}
/**
* 检验图片验证码
* @param captchaId 验证码ID
* @param value 验证码
*/
async captchaCheck(captchaId, value) {
const rv = await this.midwayCache.get(`verify:img:${captchaId}`);
if (!rv || !value || value.toLowerCase() !== rv) {
return false;
} else {
this.midwayCache.del(`verify:img:${captchaId}`);
return true;
}
}
/**
* 生成token
* @param user 用户对象
* @param roleIds 角色集合
* @param expire 过期
* @param isRefresh 是否是刷新
*/
async generateToken(user, roleIds, expire, isRefresh?) {
await this.midwayCache.set(
`admin:passwordVersion:${user.id}`,
user.passwordV
);
const tokenInfo = {
isRefresh: false,
roleIds,
username: user.username,
userId: user.id,
passwordVersion: user.passwordV,
tenantId: user['tenantId'],
};
if (isRefresh) {
tokenInfo.isRefresh = true;
}
return jwt.sign(tokenInfo, this.coolConfig.jwt.secret, {
expiresIn: expire,
});
}
/**
* 刷新token
* @param token
*/
async refreshToken(token: string) {
const decoded = jwt.verify(token, this.coolConfig.jwt.secret);
if (decoded && decoded['isRefresh']) {
delete decoded['exp'];
delete decoded['iat'];
const { expire, refreshExpire } = this.coolConfig.jwt.token;
decoded['isRefresh'] = false;
const result = {
expire,
token: jwt.sign(decoded, this.coolConfig.jwt.secret, {
expiresIn: expire,
}),
refreshExpire,
refreshToken: '',
};
decoded['isRefresh'] = true;
result.refreshToken = jwt.sign(decoded, this.coolConfig.jwt.secret, {
expiresIn: refreshExpire,
});
await this.midwayCache.set(
`admin:passwordVersion:${decoded['userId']}`,
decoded['passwordVersion']
);
await this.midwayCache.set(
`admin:token:${decoded['userId']}`,
result.token
);
return result;
}
}
}
@@ -0,0 +1,463 @@
import { App, IMidwayApplication, Scope, ScopeEnum } from '@midwayjs/core';
import { ALL, Config, Inject, Provide } from '@midwayjs/core';
import { BaseService, CoolCommException } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { In, Repository } from 'typeorm';
import { BaseSysMenuEntity } from '../../entity/sys/menu';
import * as _ from 'lodash';
import { BaseSysPermsService } from './perms';
import { Context } from '@midwayjs/koa';
import { TempDataSource } from './data';
// eslint-disable-next-line node/no-unpublished-import
import * as ts from 'typescript';
import * as fs from 'fs';
import * as pathUtil from 'path';
import { BaseSysRoleMenuEntity } from '../../entity/sys/role_menu';
import { BaseSysUserRoleEntity } from '../../entity/sys/user_role';
/**
* 菜单
*/
@Scope(ScopeEnum.Request, { allowDowngrade: true })
@Provide()
export class BaseSysMenuService extends BaseService {
@Inject()
ctx: Context;
@InjectEntityModel(BaseSysMenuEntity)
baseSysMenuEntity: Repository<BaseSysMenuEntity>;
@InjectEntityModel(BaseSysRoleMenuEntity)
baseSysRoleMenuEntity: Repository<BaseSysRoleMenuEntity>;
@Inject()
baseSysPermsService: BaseSysPermsService;
@Config(ALL)
config;
@App()
app: IMidwayApplication;
/**
* 获得所有菜单
*/
async list() {
const menus = await this.getMenus(
this.ctx.admin.roleIds,
this.ctx.admin.username === 'admin'
);
if (!_.isEmpty(menus)) {
menus.forEach((e: any) => {
const parentMenu = menus.filter(m => {
e.parentId = parseInt(e.parentId);
if (e.parentId == m.id) {
return m.name;
}
});
if (!_.isEmpty(parentMenu)) {
e.parentName = parentMenu[0].name;
}
});
}
return menus;
}
/**
* 修改之后
* @param param
*/
async modifyAfter(param) {
if (param.id) {
await this.refreshPerms(param.id);
}
}
/**
* 根据角色获得权限信息
* @param {[]} roleIds 数组
*/
async getPerms(roleIds) {
let perms = [];
if (!_.isEmpty(roleIds)) {
const find = await this.baseSysMenuEntity.createQueryBuilder('a');
if (!roleIds.includes(1)) {
find.innerJoinAndSelect(
BaseSysRoleMenuEntity,
'b',
'a.id = b.menuId AND b.roleId in (:...roleIds)',
{ roleIds }
);
}
find.where('a.perms is not NULL');
const result = await find.getMany();
if (result) {
result.forEach(d => {
if (d.perms) {
perms = perms.concat(d.perms.split(','));
}
});
}
perms = _.uniq(perms);
perms = _.remove(perms, n => {
return !_.isEmpty(n);
});
}
return _.uniq(perms);
}
/**
* 获得用户菜单信息
* @param roleIds
* @param isAdmin 是否是超管
*/
async getMenus(roleIds, isAdmin) {
const find = this.baseSysMenuEntity.createQueryBuilder('a');
if (!isAdmin) {
find.innerJoinAndSelect(
BaseSysRoleMenuEntity,
'b',
'a.id = b.menuId AND b.roleId in (:...roleIds)',
{ roleIds }
);
}
find.orderBy('a.orderNum', 'ASC');
const list = await find.getMany();
return _.uniqBy(list, 'id');
}
/**
* 删除
* @param ids
*/
async delete(ids) {
let idArr;
if (ids instanceof Array) {
idArr = ids;
} else {
idArr = ids.split(',');
}
for (const id of idArr) {
await this.baseSysMenuEntity.delete({ id });
await this.delChildMenu(id);
}
}
/**
* 删除子菜单
* @param id
*/
private async delChildMenu(id) {
await this.refreshPerms(id);
const delMenu = await this.baseSysMenuEntity.findBy({ parentId: id });
if (_.isEmpty(delMenu)) {
return;
}
const delMenuIds = delMenu.map(e => {
return e.id;
});
await this.baseSysMenuEntity.delete(delMenuIds);
for (const menuId of delMenuIds) {
await this.delChildMenu(menuId);
}
}
/**
* 更新权限
* @param menuId
*/
async refreshPerms(menuId) {
const find = this.baseSysRoleMenuEntity.createQueryBuilder('a');
find.leftJoinAndSelect(BaseSysUserRoleEntity, 'b', 'a.roleId = b.roleId');
find.where('a.menuId = :menuId', { menuId: menuId });
find.select('b.userId', 'userId');
const users = await find.getRawMany();
// 刷新admin权限
await this.baseSysPermsService.refreshPerms(1);
if (!_.isEmpty(users)) {
// 刷新其他权限
for (const user of _.uniqBy(users, 'userId')) {
await this.baseSysPermsService.refreshPerms(user.userId);
}
}
}
/**
* 解析实体和Controller
* @param entityString
* @param controller
* @param module
*/
async parse(entityString: string, controller: string, module: string) {
const tempDataSource = new TempDataSource({
...this.config.typeorm.dataSource.default,
entities: [],
});
// 连接数据库
await tempDataSource.initialize();
const { newCode, className, oldTableName } = this.parseCode(entityString);
const code = ts.transpile(
`${newCode}
tempDataSource.options.entities.push(${className})
`,
{
emitDecoratorMetadata: true,
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2018,
removeComments: true,
experimentalDecorators: true,
noImplicitThis: true,
noUnusedLocals: true,
stripInternal: true,
skipLibCheck: true,
pretty: true,
declaration: true,
noImplicitAny: false,
}
);
eval(code);
await tempDataSource.buildMetadatas();
const meta = tempDataSource.getMetadata(className);
const columnArr = meta.columns;
await tempDataSource.destroy();
const commColums = [];
const columns = _.filter(
columnArr.map(e => {
return {
propertyName: e.propertyName,
type: typeof e.type == 'string' ? e.type : e.type.name.toLowerCase(),
length: e.length,
comment: e.comment,
nullable: e.isNullable,
};
}),
o => {
if (['createTime', 'updateTime'].includes(o.propertyName)) {
commColums.push(o);
}
return o && !['createTime', 'updateTime'].includes(o.propertyName);
}
).concat(commColums);
if (!controller) {
const tableNames = oldTableName.split('_');
const fileName = tableNames[tableNames.length - 1];
return {
columns,
className: className.replace('TEMP', ''),
tableName: oldTableName,
fileName,
path: `/admin/${module}/${fileName}`,
};
}
const fileName = await this.fileName(controller);
return {
columns,
path: `/admin/${module}/${fileName}`,
};
}
/**
* 解析Entity类名
* @param code
* @returns
*/
parseCode(code: string) {
try {
const oldClassName = code
.match('class(.*)extends')[1]
.replace(/\s*/g, '');
const oldTableStart = code.indexOf('@Entity(');
const oldTableEnd = code.indexOf(')');
const oldTableName = code
.substring(oldTableStart + 9, oldTableEnd - 1)
.replace(/\s*/g, '')
// eslint-disable-next-line no-useless-escape
.replace(/\"/g, '')
// eslint-disable-next-line no-useless-escape
.replace(/\'/g, '');
const className = `${oldClassName}TEMP`;
return {
newCode: code
.replace(oldClassName, className)
.replace(oldTableName, `func_${oldTableName}`),
className,
tableName: `func_${oldTableName}`,
oldTableName,
};
} catch (err) {
throw new CoolCommException('代码结构不正确,请检查');
}
}
/**
* 创建代码
* @param body body
*/
async create(body) {
const { module, entity, controller, service, fileName } = body;
const basePath = this.app.getBaseDir();
const modulePath = pathUtil.join(basePath, '..', 'src', 'modules', module);
// 生成Entity
const entityPath = pathUtil.join(modulePath, 'entity', `${fileName}.ts`);
// 生成Controller
const controllerPath = pathUtil.join(
modulePath,
'controller',
'admin',
`${fileName}.ts`
);
// 生成Service
const servicePath = pathUtil.join(modulePath, 'service', `${fileName}.ts`);
this.createConfigFile(module);
this.createFile(entityPath, entity);
this.createFile(controllerPath, controller);
this.createFile(servicePath, service);
}
/**
* 创建配置文件
* @param module
*/
async createConfigFile(module: string) {
const basePath = this.app.getBaseDir();
const configFilePath = pathUtil.join(
basePath,
'..',
'src',
'modules',
module,
'config.ts'
);
if (!fs.existsSync(configFilePath)) {
const data = `import { ModuleConfig } from '@cool-midway/core';
/**
* 模块配置
*/
export default () => {
return {
// 模块名称
name: 'xxx',
// 模块描述
description: 'xxx',
// 中间件,只对本模块有效
middlewares: [],
// 中间件,全局有效
globalMiddlewares: [],
// 模块加载顺序,默认为0,值越大越优先加载
order: 0,
} as ModuleConfig;
};
`;
await this.createFile(configFilePath, data);
}
}
/**
* 找到文件名
* @param controller
* @returns
*/
async fileName(controller: string) {
const regex = /import\s*{\s*\w+\s*}\s*from\s*'[^']*\/([\w-]+)';/;
const match = regex.exec(controller);
if (match && match.length > 1) {
return match[1];
}
return null;
}
/**
* 创建文件
* @param filePath
* @param content
*/
async createFile(filePath: string, content: string) {
const folderPath = pathUtil.dirname(filePath);
if (!fs.existsSync(folderPath)) {
fs.mkdirSync(folderPath, { recursive: true });
}
fs.writeFileSync(filePath, content);
}
/**
* 导出菜单
* @param ids
* @returns
*/
async export(ids: number[]) {
const result: any[] = [];
const menus = await this.baseSysMenuEntity.findBy({ id: In(ids) });
// 递归取出子菜单
const getChildMenus = (parentId: number): any[] => {
const children = _.remove(menus, e => e.parentId == parentId);
children.forEach(child => {
child.childMenus = getChildMenus(child.id);
// 删除不需要的字段
delete child.id;
delete child.createTime;
delete child.updateTime;
delete child.parentId;
});
return children;
};
// lodash取出父级菜单(parentId为 null), 并从menus 删除
const parentMenus = _.remove(menus, e => {
return e.parentId == null;
});
// 对于每个父级菜单,获取它的子菜单
parentMenus.forEach(parent => {
parent.childMenus = getChildMenus(parent.id);
// 删除不需要的字段
delete parent.id;
delete parent.createTime;
delete parent.updateTime;
delete parent.parentId;
result.push(parent);
});
return result;
}
/**
* 导入
* @param menus
*/
async import(menus: any[]) {
// 递归保存子菜单
const saveChildMenus = async (parentMenu: any, parentId: number | null) => {
const children = parentMenu.childMenus || [];
for (let child of children) {
const childData = { ...child, parentId: parentId }; // 保持与数据库的parentId字段的一致性
delete childData.childMenus; // 删除childMenus属性,因为我们不想将它保存到数据库中
// 保存子菜单并获取其ID,以便为其子菜单设置parentId
const savedChild = await this.baseSysMenuEntity.save(childData);
if (!_.isEmpty(child.childMenus)) {
await saveChildMenus(child, savedChild.id);
}
}
};
for (let menu of menus) {
const menuData = { ...menu };
delete menuData.childMenus; // 删除childMenus属性,因为我们不想将它保存到数据库中
// 保存主菜单并获取其ID
const savedMenu = await this.baseSysMenuEntity.save(menuData);
if (menu.childMenus && menu.childMenus.length > 0) {
await saveChildMenus(menu, savedMenu.id);
}
}
}
}
@@ -0,0 +1,110 @@
import { InjectClient, Provide } from '@midwayjs/core';
import { BaseService, CoolCommException } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Not, Repository } from 'typeorm';
import { BaseSysParamEntity } from '../../entity/sys/param';
import { CachingFactory, MidwayCache } from '@midwayjs/cache-manager';
/**
* 参数配置
*/
@Provide()
export class BaseSysParamService extends BaseService {
@InjectEntityModel(BaseSysParamEntity)
baseSysParamEntity: Repository<BaseSysParamEntity>;
@InjectClient(CachingFactory, 'default')
midwayCache: MidwayCache;
/**
* 根据key获得对应的参数
* @param key
*/
async dataByKey(key) {
let result: any = await this.midwayCache.get(`param:${key}`);
if (!result) {
result = await this.baseSysParamEntity.findOneBy({ keyName: key });
this.midwayCache.set(`param:${key}`, result);
}
if (result) {
if (result.dataType == 0) {
try {
return JSON.parse(result.data);
} catch (error) {
return result.data;
}
}
if (result.dataType == 1) {
return result.data;
}
if (result.dataType == 2) {
return result.data.split(',');
}
}
return;
}
/**
* 信息
* @param id
* @param infoIgnoreProperty
* @returns
*/
async info(id: any, infoIgnoreProperty?: string[]): Promise<any> {
const info = await super.info(id, infoIgnoreProperty);
try {
info.data = JSON.parse(info.data.replace(/{/g, '[').replace(/}/g, ']'));
} catch (error) {
info.data = info.data;
}
return info;
}
/**
* 根据key获得对应的网页数据
* @param key
*/
async htmlByKey(key) {
let html = '<html><title>@title</title><body>@content</body></html>';
let result: any = await this.midwayCache.get(`param:${key}`);
if (result) {
html = html
.replace('@content', result.data)
.replace('@title', result.name);
} else {
html = html.replace('@content', 'key notfound');
}
return html;
}
/**
* 添加或者修改
* @param param
*/
async addOrUpdate(param: any, type): Promise<void> {
if (type == 2) {
param.data = JSON.stringify(param.data.replace());
}
const find = {
keyName: param.keyName,
};
if (param.id) {
find['id'] = Not(param.id);
}
const check = await this.baseSysParamEntity.findOneBy(find);
if (check) {
throw new CoolCommException('存在相同的keyName');
}
await super.addOrUpdate(param, type);
}
/**
* 重新初始化缓存
*/
async modifyAfter() {
const params = await this.baseSysParamEntity.find();
for (const param of params) {
await this.midwayCache.set(`param:${param.keyName}`, param);
}
}
}
@@ -0,0 +1,91 @@
import { Inject, InjectClient, Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { BaseSysMenuService } from './menu';
import { BaseSysRoleService } from './role';
import { BaseSysDepartmentService } from './department';
import { Context } from '@midwayjs/koa';
import { CachingFactory, MidwayCache } from '@midwayjs/cache-manager';
import { BaseSysRoleEntity } from '../../entity/sys/role';
import { In, Repository } from 'typeorm';
import { InjectEntityModel } from '@midwayjs/typeorm';
/**
* 权限
*/
@Provide()
export class BaseSysPermsService extends BaseService {
@InjectClient(CachingFactory, 'default')
midwayCache: MidwayCache;
@Inject()
baseSysMenuService: BaseSysMenuService;
@Inject()
baseSysRoleService: BaseSysRoleService;
@Inject()
baseSysDepartmentService: BaseSysDepartmentService;
@InjectEntityModel(BaseSysRoleEntity)
baseSysRoleEntity: Repository<BaseSysRoleEntity>;
@Inject()
ctx: Context;
base: any;
/**
* 刷新权限
* @param userId 用户ID
*/
async refreshPerms(userId) {
await this.midwayCache.del(`admin:token:${userId}`);
const roleIds = await this.baseSysRoleService.getByUser(userId);
const perms = await this.baseSysMenuService.getPerms(roleIds);
await this.midwayCache.set(`admin:perms:${userId}`, perms);
// 更新部门权限
const departments = await this.baseSysDepartmentService.getByRoleIds(
roleIds,
await this.isAdmin(roleIds)
);
await this.midwayCache.set(`admin:department:${userId}`, departments);
}
/**
* 根据角色判断是不是超管
* @param roleIds
*/
async isAdmin(roleIds: number[]) {
const roles = await this.baseSysRoleEntity.findBy({ id: In(roleIds) });
const roleLabels = roles.map(item => item.label);
return roleLabels.includes('admin');
}
/**
* 获得权限菜单
* @param roleIds
*/
async permmenu(roleIds: number[]) {
const perms = await this.baseSysMenuService.getPerms(roleIds);
const menus = await this.baseSysMenuService.getMenus(
roleIds,
this.ctx.admin.username === 'admin'
);
return { perms, menus };
}
/**
* 根据用户ID获得部门权限
* @param userId
* @return 部门ID数组
*/
async departmentIds(userId: number) {
const department: any = await this.midwayCache.get(
`admin:department:${userId}`
);
if (department) {
return department;
} else {
return [];
}
}
}
@@ -0,0 +1,136 @@
import { Inject, Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { BaseSysRoleEntity } from '../../entity/sys/role';
import { BaseSysUserRoleEntity } from '../../entity/sys/user_role';
import * as _ from 'lodash';
import { BaseSysRoleMenuEntity } from '../../entity/sys/role_menu';
import { BaseSysRoleDepartmentEntity } from '../../entity/sys/role_department';
import { BaseSysPermsService } from './perms';
import { Brackets } from 'typeorm';
/**
* 角色
*/
@Provide()
export class BaseSysRoleService extends BaseService {
@InjectEntityModel(BaseSysRoleEntity)
baseSysRoleEntity: Repository<BaseSysRoleEntity>;
@InjectEntityModel(BaseSysUserRoleEntity)
baseSysUserRoleEntity: Repository<BaseSysUserRoleEntity>;
@InjectEntityModel(BaseSysRoleMenuEntity)
baseSysRoleMenuEntity: Repository<BaseSysRoleMenuEntity>;
@InjectEntityModel(BaseSysRoleDepartmentEntity)
baseSysRoleDepartmentEntity: Repository<BaseSysRoleDepartmentEntity>;
@Inject()
baseSysPermsService: BaseSysPermsService;
@Inject()
ctx;
/**
* 根据用户ID获得所有用户角色
* @param userId
*/
async getByUser(userId: number): Promise<number[]> {
const userRole = await this.baseSysUserRoleEntity.findBy({ userId });
if (!_.isEmpty(userRole)) {
return userRole.map(e => {
return e.roleId;
});
}
return [];
}
/**
*
* @param param
*/
async modifyAfter(param) {
if (param.id) {
this.updatePerms(param.id, param.menuIdList, param.departmentIdList);
}
}
/**
* 更新权限
* @param roleId
* @param menuIdList
* @param departmentIds
*/
async updatePerms(roleId, menuIdList?, departmentIds = []) {
// 更新菜单权限
await this.baseSysRoleMenuEntity.delete({ roleId });
await Promise.all(
menuIdList.map(async e => {
return await this.baseSysRoleMenuEntity.save({ roleId, menuId: e });
})
);
// 更新部门权限
await this.baseSysRoleDepartmentEntity.delete({ roleId });
await Promise.all(
departmentIds.map(async e => {
return await this.baseSysRoleDepartmentEntity.save({
roleId,
departmentId: e,
});
})
);
// 刷新权限
const userRoles = await this.baseSysUserRoleEntity.findBy({ roleId });
for (const userRole of userRoles) {
await this.baseSysPermsService.refreshPerms(userRole.userId);
}
}
/**
* 角色信息
* @param id
*/
async info(id) {
const info = await this.baseSysRoleEntity.findOneBy({ id });
if (info) {
const menus = await this.baseSysRoleMenuEntity.findBy(
id !== 1 ? { roleId: id } : {}
);
const menuIdList = menus.map(e => {
return parseInt(e.menuId + '');
});
const departments = await this.baseSysRoleDepartmentEntity.findBy(
id !== 1 ? { roleId: id } : {}
);
const departmentIdList = departments.map(e => {
return parseInt(e.departmentId + '');
});
return {
...info,
menuIdList,
departmentIdList,
};
}
return {};
}
async list() {
return this.baseSysRoleEntity
.createQueryBuilder('a')
.where(
new Brackets(qb => {
qb.where('a.id !=:id', { id: 1 }); // 超级管理员的角色不展示
// 如果不是超管,只能看到自己新建的或者自己有的角色
if (this.ctx.admin.username !== 'admin') {
qb.andWhere('(a.userId=:userId or a.id in (:...roleId))', {
userId: this.ctx.admin.userId,
roleId: this.ctx.admin.roleIds,
});
}
})
)
.getMany();
}
}
@@ -0,0 +1,237 @@
import { Inject, InjectClient, Provide } from '@midwayjs/core';
import { BaseService, CoolCommException } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Equal, In, Repository } from 'typeorm';
import { BaseSysUserEntity } from '../../entity/sys/user';
import { BaseSysPermsService } from './perms';
import * as _ from 'lodash';
import { BaseSysUserRoleEntity } from '../../entity/sys/user_role';
import * as md5 from 'md5';
import { BaseSysDepartmentEntity } from '../../entity/sys/department';
import { CachingFactory, MidwayCache } from '@midwayjs/cache-manager';
import { BaseSysRoleEntity } from '../../entity/sys/role';
/**
* 系统用户
*/
@Provide()
export class BaseSysUserService extends BaseService {
@InjectEntityModel(BaseSysUserEntity)
baseSysUserEntity: Repository<BaseSysUserEntity>;
@InjectEntityModel(BaseSysUserRoleEntity)
baseSysUserRoleEntity: Repository<BaseSysUserRoleEntity>;
@InjectEntityModel(BaseSysDepartmentEntity)
baseSysDepartmentEntity: Repository<BaseSysDepartmentEntity>;
@InjectClient(CachingFactory, 'default')
midwayCache: MidwayCache;
@Inject()
baseSysPermsService: BaseSysPermsService;
@Inject()
ctx;
/**
* 分页查询
* @param query
*/
async page(query) {
const { keyWord, status, departmentIds = [] } = query;
const userId = this.ctx.admin.userId;
const permsDepartmentArr = await this.baseSysPermsService.departmentIds(
userId
); // 部门权限
const sql = `
SELECT
a.id,a.name,a.nickName,a.headImg,a.email,a.remark,a.status,a.createTime,a.updateTime,a.username,a.phone,a.departmentId,
b.name as "departmentName"
FROM
base_sys_user a
LEFT JOIN base_sys_department b on a.departmentId = b.id
WHERE 1 = 1
${this.setSql(
!_.isEmpty(departmentIds),
'and a.departmentId in (?)',
[departmentIds]
)}
${this.setSql(status, 'and a.status = ?', [status])}
${this.setSql(keyWord, 'and (a.name LIKE ? or a.username LIKE ?)', [
`%${keyWord}%`,
`%${keyWord}%`,
])}
${this.setSql(true, 'and a.username != ?', ['admin'])}
${this.setSql(
this.ctx.admin.username !== 'admin',
`and (a.departmentId in (?) or a.userId = ${userId})`,
[!_.isEmpty(permsDepartmentArr) ? permsDepartmentArr : [null]]
)} `;
const result = await this.sqlRenderPage(sql, query);
// 匹配角色
if (!_.isEmpty(result.list)) {
const userIds = result.list.map(e => e.id);
const roles: BaseSysRoleEntity[] = await this.nativeQuery(
'SELECT b.name, a.userId FROM base_sys_user_role a LEFT JOIN base_sys_role b ON a.roleId = b.id WHERE a.userId in (?) ',
[userIds]
);
result.list.forEach(e => {
const arr = roles.filter(a => a.userId == e.id);
e['roleIds'] = arr.map(a => a.userId);
e['roleName'] = arr.map(a => a.name).join(',');
});
}
return result;
}
/**
* 移动部门
* @param departmentId
* @param userIds
*/
async move(departmentId, userIds) {
await this.baseSysUserEntity.update({ id: In(userIds) }, { departmentId });
}
/**
* 获得个人信息
*/
async person(userId) {
const info = await this.baseSysUserEntity.findOneBy({
id: Equal(userId),
});
delete info?.password;
return info;
}
/**
* 更新用户角色关系
* @param user
*/
async updateUserRole(user) {
if (_.isEmpty(user.roleIdList)) {
return;
}
if (user.username === 'admin') {
throw new CoolCommException('非法操作~');
}
await this.baseSysUserRoleEntity.delete({ userId: user.id });
if (user.roleIdList) {
for (const roleId of user.roleIdList) {
await this.baseSysUserRoleEntity.save({ userId: user.id, roleId });
}
}
await this.baseSysPermsService.refreshPerms(user.id);
}
/**
* 新增
* @param param
*/
async add(param) {
const exists = await this.baseSysUserEntity.findOneBy({
username: param.username,
});
if (!_.isEmpty(exists)) {
throw new CoolCommException('用户名已经存在~');
}
param.password = md5(param.password);
await super.add(param);
await this.updateUserRole(param);
return param.id;
}
/**
* 根据ID获得信息
* @param id
*/
public async info(id) {
const info = await this.baseSysUserEntity.findOneBy({ id });
const userRoles = await this.nativeQuery(
'select a.roleId from base_sys_user_role a where a.userId = ?',
[id]
);
const department = await this.baseSysDepartmentEntity.findOneBy({
id: info.departmentId,
});
if (info) {
delete info.password;
if (userRoles) {
info.roleIdList = userRoles.map(e => {
return parseInt(e.roleId);
});
}
}
delete info.password;
if (department) {
info.departmentName = department.name;
}
return info;
}
/**
* 修改个人信息
* @param param
*/
public async personUpdate(param) {
param.id = this.ctx.admin.userId;
if (!_.isEmpty(param.password)) {
param.password = md5(param.password);
const oldPassword = md5(param.oldPassword);
const userInfo = await this.baseSysUserEntity.findOneBy({ id: param.id });
if (!userInfo) {
throw new CoolCommException('用户不存在');
}
if (oldPassword !== userInfo.password) {
throw new CoolCommException('原密码错误');
}
param.passwordV = userInfo.passwordV + 1;
await this.midwayCache.set(
`admin:passwordVersion:${param.id}`,
param.passwordV
);
} else {
delete param.password;
}
await this.baseSysUserEntity.save(param);
}
/**
* 修改
* @param param 数据
*/
async update(param) {
if (param.id && param.username === 'admin') {
throw new CoolCommException('非法操作~');
}
if (!_.isEmpty(param.password)) {
param.password = md5(param.password);
const userInfo = await this.baseSysUserEntity.findOneBy({ id: param.id });
if (!userInfo) {
throw new CoolCommException('用户不存在');
}
param.passwordV = userInfo.passwordV + 1;
await this.midwayCache.set(
`admin:passwordVersion:${param.id}`,
param.passwordV
);
} else {
delete param.password;
}
if (param.status === 0) {
await this.forbidden(param.id);
}
await this.baseSysUserEntity.save(param);
await this.updateUserRole(param);
}
/**
* 禁用用户
* @param userId
*/
async forbidden(userId) {
await this.midwayCache.del(`admin:token:${userId}`);
}
}
@@ -0,0 +1,588 @@
import { I18N } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { BaseSysMenuEntity } from '../entity/sys/menu';
import {
App,
Config,
ILogger,
IMidwayApplication,
Inject,
Provide,
Scope,
ScopeEnum,
} from '@midwayjs/core';
import * as path from 'path';
import * as fs from 'fs';
import axios from 'axios';
import { DictInfoEntity } from '../../dict/entity/info';
import { DictTypeEntity } from '../../dict/entity/type';
/**
* 翻译服务
*/
@Provide()
@Scope(ScopeEnum.Singleton)
export class BaseTranslateService {
@InjectEntityModel(BaseSysMenuEntity)
baseSysMenuEntity: Repository<BaseSysMenuEntity>;
@InjectEntityModel(DictInfoEntity)
dictInfoEntity: Repository<DictInfoEntity>;
@InjectEntityModel(DictTypeEntity)
dictTypeEntity: Repository<DictTypeEntity>;
// 基础路径
basePath: string;
@App()
app: IMidwayApplication;
@Inject()
logger: ILogger;
@Config('cool.i18n')
config: {
/** 是否开启 */
enable: boolean;
/** 语言 */
languages: string[];
/** 翻译服务 */
serviceUrl?: string;
};
menuMap: Record<string, string> = {};
msgMap: Record<string, string> = {};
commMap: Record<string, string> = {};
// 添加字典映射
dictMap: Record<string, string> = {};
/**
* 检查是否存在锁文件
*/
private checkLockFile(type: 'menu' | 'msg' | 'comm'): boolean {
const lockFile = path.join(this.basePath, type, '.lock');
return fs.existsSync(lockFile);
}
/**
* 创建锁文件
*/
private createLockFile(type: 'menu' | 'msg' | 'comm'): void {
const lockFile = path.join(this.basePath, type, '.lock');
fs.writeFileSync(lockFile, new Date().toISOString());
}
/**
* 加载翻译文件到内存
*/
async loadTranslations() {
if (!this.config?.enable) {
return;
}
if (!this.basePath) {
this.basePath = path.join(this.app.getBaseDir(), '..', 'src', 'locales');
}
// 清空现有映射
this.menuMap = {};
this.msgMap = {};
this.dictMap = {};
this.commMap = {};
// 加载菜单翻译
await this.loadTypeTranslations('menu', this.menuMap);
// 加载消息翻译
await this.loadTypeTranslations('msg', this.msgMap);
// 加载通用消息翻译
await this.loadTypeTranslations('comm', this.commMap);
// 加载字典翻译
await this.loadDictTranslations();
}
/**
* 加载指定类型的翻译
* @param type 翻译类型
* @param map 映射对象
*/
private async loadTypeTranslations(
type: 'menu' | 'msg' | 'comm',
map: Record<string, string>
) {
const dirPath = path.join(this.basePath, type);
if (fs.existsSync(dirPath)) {
const files = fs.readdirSync(dirPath);
for (const file of files) {
if (file.endsWith('.json')) {
const language = file.replace('.json', '');
const content = fs.readFileSync(path.join(dirPath, file), 'utf-8');
const translations = JSON.parse(content);
for (const [key, value] of Object.entries(translations)) {
map[`${language}:${key}`] = value as string;
}
}
}
}
}
/**
* 加载字典翻译
*/
private async loadDictTranslations() {
const dictTypes = ['info', 'type'];
for (const dictType of dictTypes) {
const dirPath = path.join(this.basePath, 'dict', dictType);
if (fs.existsSync(dirPath)) {
const files = fs.readdirSync(dirPath);
for (const file of files) {
if (file.endsWith('.json')) {
const language = file.replace('.json', '');
const content = fs.readFileSync(path.join(dirPath, file), 'utf-8');
const translations = JSON.parse(content);
for (const [key, value] of Object.entries(translations)) {
this.dictMap[`${language}:dict:${dictType}:${key}`] =
value as string;
}
}
}
}
}
}
/**
* 更新翻译映射
* @param type 类型 menu | msg
* @param language 语言
*/
async updateTranslationMap(type: 'menu' | 'msg', language: string) {
const dirPath = path.join(this.basePath, type);
const file = path.join(dirPath, `${language}.json`);
if (fs.existsSync(file)) {
const content = fs.readFileSync(file, 'utf-8');
const translations = JSON.parse(content);
const map = type === 'menu' ? this.menuMap : this.msgMap;
for (const [key, value] of Object.entries(translations)) {
map[`${language}:${key}`] = value as string;
}
}
}
/**
* 翻译
* @param type 类型 menu | msg | dict
* @param language 语言
* @param text 原文
* @returns 翻译后的文本
*/
translate(
type: 'menu' | 'msg' | 'dict:info' | 'dict:type' | 'comm',
language: string,
text: string
): string {
// 处理字典翻译
if (type === 'dict:info' || type === 'dict:type') {
const key = `${language}:${type}:${text}`;
return this.dictMap[key] || text.split(':').pop() || text;
}
// 处理菜单和消息翻译
const map = type === 'menu' ? this.menuMap : this.msgMap;
const key = `${language}:${text}`;
return map[key] || text;
}
/**
* 检查翻译
*/
async check() {
if (this.config?.enable && this.app.getEnv() == 'local') {
this.basePath = path.join(this.app.getBaseDir(), '..', 'src', 'locales');
const menuLockExists = this.checkLockFile('menu');
const msgLockExists = this.checkLockFile('msg');
const commLockExists = this.checkLockFile('comm');
const dictLockExists = this.checkDictLockFile();
if (
!menuLockExists ||
!msgLockExists ||
!dictLockExists ||
!commLockExists
) {
const tasks = [];
if (!msgLockExists) {
tasks.push(this.genBaseMsg());
}
if (!menuLockExists) {
tasks.push(this.genBaseMenu());
}
if (!dictLockExists) {
tasks.push(this.genBaseDict());
}
if (!commLockExists) {
tasks.push(this.genCommMsg());
}
// 启动旋转动画
const spinner = ['|', '/', '-', '\\'];
let index = 0;
const interval = setInterval(() => {
process.stdout.write(`\r${spinner[index++]} i18n translate...`);
index %= spinner.length;
}, 200);
try {
await Promise.all(tasks);
} finally {
clearInterval(interval);
// 加载翻译文件到内存
await this.loadTranslations();
await this.loadDictTranslations();
process.stdout.write('\r✅ i18n translate success!!!\n');
}
} else {
this.logger.debug('Translation lock files exist, skipping translation');
// 直接加载翻译文件到内存
await this.loadTranslations();
await this.loadDictTranslations();
}
}
}
/**
* 检查字典锁文件
*/
private checkDictLockFile(): boolean {
const lockFile = path.join(this.basePath, 'dict', '.lock');
return fs.existsSync(lockFile);
}
/**
* 创建字典锁文件
*/
private createDictLockFile(): void {
const lockFile = path.join(this.basePath, 'dict', '.lock');
fs.writeFileSync(lockFile, new Date().toISOString());
}
/**
* 生成基础字典
*/
async genBaseDict() {
try {
// 检查是否存在锁文件
if (this.checkDictLockFile()) {
this.logger.debug('Dictionary lock file exists, skipping translation');
return;
}
const infos = await this.dictInfoEntity.find();
const types = await this.dictTypeEntity.find();
// 确保目录存在
const infoDir = path.join(this.basePath, 'dict', 'info');
const typeDir = path.join(this.basePath, 'dict', 'type');
fs.mkdirSync(infoDir, { recursive: true });
fs.mkdirSync(typeDir, { recursive: true });
// 生成中文基础文件
const infoContent = {};
const typeContent = {};
for (const info of infos) {
infoContent[info.name] = info.name;
}
for (const type of types) {
typeContent[type.name] = type.name;
}
const infoFile = path.join(infoDir, 'zh-cn.json');
const typeFile = path.join(typeDir, 'zh-cn.json');
const infoText = JSON.stringify(infoContent, null, 2);
const typeText = JSON.stringify(typeContent, null, 2);
fs.writeFileSync(infoFile, infoText);
fs.writeFileSync(typeFile, typeText);
this.logger.debug('Base dictionary files generated successfully');
// 翻译其他语言
if (this.config?.enable && this.config.languages) {
const translatePromises = [];
for (const language of this.config.languages) {
if (language !== 'zh-cn') {
// 翻译 info 字典
translatePromises.push(
this.invokeTranslate(infoText, language, infoDir, 'dict')
);
// 翻译 type 字典
translatePromises.push(
this.invokeTranslate(typeText, language, typeDir, 'dict')
);
}
}
await Promise.all(translatePromises);
this.logger.debug('Dictionary translations completed successfully');
}
// 创建锁文件
this.createDictLockFile();
// 更新翻译映射
await this.loadDictTranslations();
} catch (error) {
this.logger.error('Failed to generate dictionary:', error);
throw error;
}
}
/**
* 更新字典翻译映射
* @param language 语言
*/
async updateDictTranslationMap(language: string) {
const infoFile = path.join(
this.basePath,
'dict',
'info',
`${language}.json`
);
const typeFile = path.join(
this.basePath,
'dict',
'type',
`${language}.json`
);
if (fs.existsSync(infoFile)) {
const content = fs.readFileSync(infoFile, 'utf-8');
const translations = JSON.parse(content);
for (const [key, value] of Object.entries(translations)) {
this.dictMap[`${language}:dict:info:${key}`] = value as string;
}
}
if (fs.existsSync(typeFile)) {
const content = fs.readFileSync(typeFile, 'utf-8');
const translations = JSON.parse(content);
for (const [key, value] of Object.entries(translations)) {
this.dictMap[`${language}:dict:type:${key}`] = value as string;
}
}
}
/**
* 生成基础菜单
*/
async genBaseMenu() {
const menus = await this.baseSysMenuEntity.find();
const file = path.join(this.basePath, 'menu', 'zh-cn.json');
const content = {};
for (const menu of menus) {
content[menu.name] = menu.name;
}
// 确保目录存在
const msgDir = path.dirname(file);
if (!fs.existsSync(msgDir)) {
fs.mkdirSync(msgDir, { recursive: true });
}
const text = JSON.stringify(content, null, 2);
fs.writeFileSync(file, text);
this.logger.debug('base menu generate success');
const translatePromises = [];
for (const language of this.config.languages) {
if (language !== 'zh-cn') {
translatePromises.push(
this.invokeTranslate(
text,
language,
path.join(this.basePath, 'menu'),
'menu'
)
);
}
}
await Promise.all(translatePromises);
this.createLockFile('menu');
}
/**
* 生成基础消息
*/
async genBaseMsg() {
const file = path.join(this.basePath, 'msg', 'zh-cn.json');
const scanPath = path.join(this.app.getBaseDir(), '..', 'src', 'modules');
const messages = {};
// 递归扫描目录
const scanDir = (dir: string) => {
const files = fs.readdirSync(dir);
for (const file of files) {
const fullPath = path.join(dir, file);
const stat = fs.statSync(fullPath);
if (stat.isDirectory()) {
scanDir(fullPath);
} else if (file.endsWith('.ts')) {
const content = fs.readFileSync(fullPath, 'utf-8');
const matches = content.match(
/throw new CoolCommException\((['"])(.*?)\1\)/g
);
if (matches) {
matches.forEach(match => {
const message = match.match(/(['"])(.*?)\1/)[2];
messages[message] = message;
});
}
}
}
};
// 开始扫描
scanDir(scanPath);
// 确保目录存在
const msgDir = path.dirname(file);
if (!fs.existsSync(msgDir)) {
fs.mkdirSync(msgDir, { recursive: true });
}
// 写入文件
const text = JSON.stringify(messages, null, 2);
fs.writeFileSync(file, text);
this.logger.debug('base msg generate success');
const translatePromises = [];
for (const language of this.config.languages) {
if (language !== 'zh-cn') {
translatePromises.push(
this.invokeTranslate(
text,
language,
path.join(this.basePath, 'msg'),
'msg'
)
);
}
}
await Promise.all(translatePromises);
this.createLockFile('msg');
}
/**
* 生成通用消息
*/
async genCommMsg() {
const file = path.join(this.basePath, 'comm', 'zh-cn.json');
const scanPath = path.join(this.app.getBaseDir(), '..', 'src', 'modules');
const messages = {};
// 递归扫描目录
const scanDir = (dir: string) => {
const files = fs.readdirSync(dir);
for (const file of files) {
const fullPath = path.join(dir, file);
const stat = fs.statSync(fullPath);
if (stat.isDirectory()) {
scanDir(fullPath);
} else if (file.endsWith('.ts')) {
const content = fs.readFileSync(fullPath, 'utf-8');
const matches = content.match(
/this.translate.comm\((['"])(.*?)\1\)/g
);
if (matches) {
matches.forEach(match => {
const message = match.match(/(['"])(.*?)\1/)[2];
messages[message] = message;
});
}
}
}
};
// 开始扫描
scanDir(scanPath);
// 确保目录存在
const msgDir = path.dirname(file);
if (!fs.existsSync(msgDir)) {
fs.mkdirSync(msgDir, { recursive: true });
}
// 写入文件
const text = JSON.stringify(messages, null, 2);
fs.writeFileSync(file, text);
this.logger.debug('base comm generate success');
const translatePromises = [];
for (const language of this.config.languages) {
if (language !== 'zh-cn') {
translatePromises.push(
this.invokeTranslate(
text,
language,
path.join(this.basePath, 'comm'),
'comm'
)
);
}
}
await Promise.all(translatePromises);
this.createLockFile('comm');
}
/**
* 通用消息翻译
* @param text 文本
* @returns 翻译后的文本对象,包含各语言的翻译
*/
comm(text: string) {
const translations = {};
for (const lang of this.config.languages) {
const langFile = path.join(this.basePath, 'comm', `${lang}.json`);
if (fs.existsSync(langFile)) {
const content = JSON.parse(fs.readFileSync(langFile, 'utf-8'));
translations[lang] = content[text] || text;
}
}
return translations;
}
/**
* 调用翻译
* @param text 文本
* @param language 语言
* @param dirPath 目录
* @param type 类型
* @returns
*/
async invokeTranslate(
text: string,
language: string,
dirPath: string,
type: 'menu' | 'msg' | 'dict' | 'comm' = 'msg'
) {
this.logger.debug(`${type} ${language} translate start`);
const response = await axios.post(I18N.DEFAULT_SERVICE_URL, {
label: 'i18n-node',
params: {
text,
language,
},
stream: false,
});
const file = path.join(dirPath, `${language}.json`);
fs.writeFileSync(file, response.data.data.result.data);
this.logger.debug(`${type} ${language} translate success`);
}
}
@@ -0,0 +1,58 @@
import * as path from 'path';
import * as os from 'os';
import * as fs from 'fs';
import { loadEnvFile } from './env';
// 进程启动即加载本模块 .env(server/.env,不覆盖已有环境变量)
loadEnvFile();
/**
* 中心机业务配置(与旧 FastAPI controlplane/config.py 对齐)
* - CENTER_DATA_DIR 可经环境变量指向现网真实目录(packages/shell/avatars 与旧后端共用)
*/
export const CENTER_DATA_DIR =
process.env.CENTER_DATA_DIR || path.join(os.homedir(), '.cool-admin', '37du-center');
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');
/** 离线授权票据有效期(天):执行机最多离线该天数 */
export const LICENSE_TTL_DAYS = 7;
/**
* 钉钉扫码自动建号的初始密码(对齐 config._dingtalk_default_password):
* 优先 DINGTALK_DEFAULT_PASSWORD 环境变量;未配置时首次生成随机密码并持久化到
* CENTER_DATA_DIR/.dingtalk_default_pwd(重启复用,保证未改密用户拿到的初始密码稳定)。
*/
export function dingtalkDefaultPassword(): string {
const env = (process.env.DINGTALK_DEFAULT_PASSWORD || '').trim();
if (env) return env;
const f = path.join(CENTER_DATA_DIR, '.dingtalk_default_pwd');
try {
if (fs.existsSync(f)) {
const saved = fs.readFileSync(f, 'utf8').trim();
if (saved) return saved;
}
} catch (e) {
/* fallthrough */
}
const pwd = require('crypto').randomBytes(9).toString('base64url'); // 约 12 位,无易混淆字符
try {
fs.mkdirSync(CENTER_DATA_DIR, { recursive: true });
fs.writeFileSync(f, pwd, 'utf8');
} catch (e) {
/* 持久化失败不阻断 */
}
return pwd;
}
/** 内网文件服务器离线监控参数(对齐 config.py:超时 180s / 扫描间隔 30s) */
export const FILESERVER_HEARTBEAT_TIMEOUT = Number(process.env.FILESERVER_HEARTBEAT_TIMEOUT || 180) || 180;
export const FILESERVER_MONITOR_INTERVAL = Number(process.env.FILESERVER_MONITOR_INTERVAL || 30) || 30;
/** 格式化时间 'YYYY-MM-DD HH:mm:ss'(对齐 Python strftime("%Y-%m-%d %H:%M:%S")) */
export function fmtNow(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())}`;
}
@@ -0,0 +1,40 @@
import * as fs from 'fs';
import * as path from 'path';
/**
* 轻量 .env 加载器(对齐老 controlplane/.env 语义,不引入 dotenv 依赖):
* - 只读取本模块目录(server/)下的 .env,禁止读取/改写其它模块的 .env;
* - 已存在的进程环境变量优先(不覆盖),便于部署平台直接注入;
* - 支持 KEY=VALUE、#注释、单双引号包裹、行内注释(带空格的 #)。
*/
export function loadEnvFile(filePath?: string): void {
const f = filePath || path.join(process.cwd(), '.env');
let text = '';
try {
text = fs.readFileSync(f, 'utf8');
} catch (e) {
return; // 无 .env 静默跳过
}
for (const rawLine of text.split(/\r?\n/)) {
const line = rawLine.trim();
if (!line || line.startsWith('#')) continue;
const eq = line.indexOf('=');
if (eq <= 0) continue;
const key = line.slice(0, eq).trim();
let value = line.slice(eq + 1).trim();
// 行内注释:仅当值未加引号时截断 " #"
const quoted =
(value.startsWith('"') && value.endsWith('"') && value.length >= 2) ||
(value.startsWith("'") && value.endsWith("'") && value.length >= 2);
if (!quoted) {
const hash = value.indexOf(' #');
if (hash >= 0) value = value.slice(0, hash).trim();
} else {
value = value.slice(1, -1);
}
if (!key) continue;
if (process.env[key] === undefined || process.env[key] === '') {
process.env[key] = value;
}
}
}
@@ -0,0 +1,10 @@
/**
* 统一分页边界(对齐 core/paging.py page_bounds 的换算;返回 [limit, offset])。
* 注意:调用方均按 `LIMIT ? OFFSET ?` / `slice(offset, offset + limit)` 消费,
* 因此首元素必须是每页条数(limit),次元素是起始偏移(offset)。
*/
export function pageBounds(page: number, pageSize: number): [number, number] {
const p = Math.max(1, Math.floor(page || 1));
const s = Math.max(1, Math.min(1000, Math.floor(pageSize || 20)));
return [s, (p - 1) * s];
}
@@ -0,0 +1,20 @@
import { ModuleConfig } from '@cool-midway/core';
import { ApiErrorMiddleware } from './middleware/api-error';
/**
* 37du 中心机业务模块配置
*/
export default () => {
return {
// 模块名称
name: '中心机业务',
// 模块描述
description: '插件管理、账号、授权、上报、审计、下载票据等业务(映射现网 37du 库)',
// 中间件,只对本模块有效
middlewares: [],
// 全局有效中间件:契约错误渲染(/api/* 输出 {detail})
globalMiddlewares: [ApiErrorMiddleware],
// 模块加载顺序
order: 0,
} as ModuleConfig;
};
@@ -0,0 +1,253 @@
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 { AccountEntity } from '../../entity/account';
import { PluginEntity, AccountPluginEntity, AccountPlatformEntity } from '../../entity/plugin';
import { CenterAuthService, ApiError } from '../../service/auth';
import { hashPassword } from '../../service/crypto';
import { pageBounds } from '../../comm/util';
/**
* 账号管理与授权(对齐旧 FastAPI apis/admin.py 账号 CRUD + 授权接口)
* 鉴权:requireAdmin(管理员票据;X-Admin-Token 或 X-API-Token 体系保持)
*/
@Provide()
@CoolController('/api/admin')
export class AdminAccountController extends BaseController {
@Inject()
centerAuthService: CenterAuthService;
@InjectEntityModel(AccountEntity)
accountRepo: Repository<AccountEntity>;
@InjectEntityModel(PluginEntity)
pluginRepo: Repository<PluginEntity>;
@InjectEntityModel(AccountPluginEntity)
accountPluginRepo: Repository<AccountPluginEntity>;
@InjectEntityModel(AccountPlatformEntity)
accountPlatformRepo: Repository<AccountPlatformEntity>;
/** GET /api/admin/accounts — 账号列表(分页 + 搜索 q) */
@Get('/accounts')
async accounts(
@Query('page') page: number = 1,
@Query('page_size') pageSize: number = 20,
@Query('q') q: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const [limit, offset] = pageBounds(page, pageSize);
const cond: string[] = [];
const args: any[] = [];
if ((q || '').trim()) {
cond.push('(account LIKE ? OR nickname LIKE ? OR dept LIKE ?)');
args.push(`%${q.trim()}%`, `%${q.trim()}%`, `%${q.trim()}%`);
}
const where = cond.length ? ' WHERE ' + cond.join(' AND ') : '';
const m = this.accountRepo.manager;
const total: any = (await m.query(`SELECT COUNT(*) AS c FROM accounts${where}`, args))[0];
const rows: any[] = await m.query(
`SELECT id, account, is_admin, dept, nickname, dingtalk_uid, must_change_pwd,
avatar, status, created_at
FROM accounts${where} ORDER BY id LIMIT ? OFFSET ?`,
[...args, limit, offset]
);
const items = [];
for (const r of rows) {
const grants: any[] = await m.query(
'SELECT plugin_id, can_download, can_run FROM account_plugins WHERE account = ?', [r.account]);
const platforms: any[] = await m.query(
'SELECT platform_id FROM account_platforms WHERE account = ? ORDER BY platform_id', [r.account]);
items.push({
id: r.id,
account: r.account,
is_admin: !!Number(r.is_admin),
dept: r.dept || '',
nickname: r.nickname || '',
dingtalk_uid: r.dingtalk_uid || '',
must_change_pwd: !!Number(r.must_change_pwd),
avatar: r.avatar || '',
status: Number(r.status),
created_at: fmtStr(r.created_at),
plugins: grants.map((g: any) => g.plugin_id),
grants: grants.map((g: any) => ({ plugin_id: g.plugin_id, can_download: !!Number(g.can_download), can_run: !!Number(g.can_run) })),
platforms: platforms.map((p: any) => p.platform_id),
});
}
return { items, total: Number(total.c || 0) };
}
/** POST /api/admin/account — 新建账号 */
@Post('/account')
async accountCreate(
@Body() a: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(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 位');
const exists = await this.accountRepo.findOneBy({ account });
if (exists) throw new ApiError(400, `账号 ${account} 已存在`);
const { hash, salt } = hashPassword(a.password);
await this.accountRepo.insert({
account,
passwordHash: hash,
salt,
isAdmin: Number(!!a.is_admin),
dept: (a?.dept || '').trim(),
nickname: (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 };
}
/** POST /api/admin/account/update */
@Post('/account/update')
async accountUpdate(
@Body() a: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const account = (a?.account || '').trim();
if (!account) throw new ApiError(400, 'account 必填');
const exists = await this.accountRepo.findOneBy({ account });
if (!exists) throw new ApiError(400, `账号 ${account} 不存在`);
const set: Record<string, any> = {};
if (a?.dept !== undefined && a?.dept !== null) set.dept = String(a.dept || '').trim();
if (a?.nickname !== undefined && a?.nickname !== null) set.nickname = String(a.nickname || '').trim();
if (a?.is_admin !== undefined && a?.is_admin !== null) {
if (a.is_admin) set.isAdmin = 1;
else await this.accountRepo.manager.query('UPDATE accounts SET is_admin = 0 WHERE account = ? AND account <> ?', [account, login]);
}
if (a?.status !== undefined && a?.status !== null) {
if (!a.status && account === login) throw new ApiError(400, '不能停用当前登录的账号');
set.status = Number(!!a.status);
}
if (Object.keys(set).length) {
await this.accountRepo.update({ account }, set);
}
if (a?.status !== undefined && a?.status !== null && !a.status) {
await this.centerAuthService.revokeAccountTokens(account);
}
await this.centerAuthService.audit(login, 'account-update', account,
`dept=${a?.dept !== undefined}, nickname=${a?.nickname !== undefined}, is_admin=${a?.is_admin !== undefined}, status=${a?.status !== undefined}`);
return { ok: true, account };
}
/** POST /api/admin/account/reset_pwd */
@Post('/account/reset_pwd')
async accountResetPwd(
@Body() r: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(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 位');
const exists = await this.accountRepo.findOneBy({ account });
if (!exists) throw new ApiError(400, `账号 ${account} 不存在`);
const { hash, salt } = hashPassword(r.new_password);
await this.accountRepo.manager.query(
'UPDATE accounts SET password_hash = ?, salt = ?, must_change_pwd = 1 WHERE account = ?',
[hash, salt, account]
);
await this.centerAuthService.audit(login, 'account-reset-pwd', account);
return { ok: true, account };
}
/** POST /api/admin/account/delete */
@Post('/account/delete')
async accountDelete(
@Body() d: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const account = (d?.account || '').trim();
if (!account) throw new ApiError(400, 'account 必填');
if (account === login) throw new ApiError(400, '不能删除当前登录的账号');
const exists = await this.accountRepo.findOneBy({ account });
if (!exists) throw new ApiError(400, `账号 ${account} 不存在`);
await this.accountRepo.manager.query('DELETE FROM accounts WHERE account = ?', [account]);
await this.centerAuthService.revokeAccountTokens(account);
await this.centerAuthService.audit(login, 'account-delete', account);
return { ok: true, account };
}
/** POST /api/admin/account_plugins — 授权/撤销插件 */
@Post('/account_plugins')
async grant(
@Body() g: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const account = (g?.account || '').trim();
const pluginId = (g?.plugin_id || '').trim();
if (!account || !pluginId) throw new ApiError(400, 'account 与 plugin_id 不能为空');
if (g.granted) {
const acc = await this.accountRepo.findOneBy({ account });
if (!acc) throw new ApiError(400, `账号 ${account} 不存在,请先建号`);
const pl = await this.pluginRepo.findOneBy({ id: pluginId });
if (!pl) throw new ApiError(400, `插件 ${pluginId} 不存在,请先上传发布`);
await this.accountPluginRepo.manager.query(
`INSERT INTO account_plugins(account, plugin_id, can_download, can_run) VALUES (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE can_download = VALUES(can_download), can_run = VALUES(can_run)`,
[account, pluginId, Number(!!g.can_download), Number(!!g.can_run)]
);
} else {
await this.accountPluginRepo.manager.query(
'DELETE FROM account_plugins WHERE account = ? AND plugin_id = ?', [account, pluginId]
);
}
await this.centerAuthService.audit(login, g.granted ? 'grant' : 'revoke-grant', pluginId,
`account=${account},can_download=${!!g.can_download},can_run=${!!g.can_run}`);
return { ok: true, account, plugin_id: pluginId, granted: !!g.granted };
}
/** POST /api/admin/account_platforms — 授权/撤销平台 */
@Post('/account_platforms')
async platformGrant(
@Body() g: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const account = (g?.account || '').trim();
const platformId = (g?.platform_id || '').trim();
if (!account || !platformId) throw new ApiError(400, 'account 与 platform_id 不能为空');
if (g.granted) {
const acc = await this.accountRepo.findOneBy({ account });
if (!acc) throw new ApiError(400, `账号 ${account} 不存在,请先建号`);
await this.accountPlatformRepo.manager.query(
'INSERT IGNORE INTO account_platforms(account, platform_id) VALUES (?, ?)', [account, platformId]
);
} else {
await this.accountPlatformRepo.manager.query(
'DELETE FROM account_platforms WHERE account = ? AND platform_id = ?', [account, platformId]
);
}
await this.centerAuthService.audit(login, g.granted ? 'grant-platform' : 'revoke-platform', platformId, account);
return { ok: true, account, platform_id: platformId, granted: !!g.granted };
}
}
function fmt(d: Date | null): string {
if (!d) return '';
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())}`;
}
function fmtStr(d: any): string {
if (!d) return '';
if (d instanceof Date) return fmt(d);
return String(d).replace('T', ' ').slice(0, 19);
}
@@ -0,0 +1,137 @@
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 { AccountEntity } from '../../entity/account';
import { CenterAuthService, ApiError } from '../../service/auth';
import { hashPassword, verifyPassword, signAdminToken } from '../../service/crypto';
/**
* 管理面登录/身份(对齐旧 FastAPI apis/auth.py + 壳子 server.js 代理)
* - POST /api/admin/auth:账号密码登录(公开入口)→ 签发 X-Admin-Token + 云令牌
* - GET /api/admin/me:当前账号信息
* - POST /api/admin/password:自助改密(旧密码校验)
* - POST /api/admin/logout:退出(壳子代理调用,简单返回 ok)
* - GET /api/admin/platforms:可授权平台列表(管理员)
*/
const CONTROLPLANE_PLATFORMS = [
{ id: 'hr', label: 'HR 系统' },
{ id: 'oa', label: 'OA 系统' },
];
@Provide()
@CoolController('/api/admin')
export class AdminAuthController extends BaseController {
@Inject()
centerAuthService: CenterAuthService;
@InjectEntityModel(AccountEntity)
accountRepo: Repository<AccountEntity>;
/** POST /api/admin/auth — 统一账户登录 */
@Post('/auth')
async auth(
@Body() a: any,
@Headers('X-API-Token') xApiToken: string = ''
) {
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)) {
await this.centerAuthService.authFail(account);
throw new ApiError(401, '账号或密码错误');
}
if (!Number(row.status)) throw new ApiError(403, '账号已停用,请联系管理员');
await this.centerAuthService.authReset(account);
const nickname = row.nickname || '';
return {
ok: true,
account,
is_admin: !!Number(row.isAdmin),
dept: row.dept || '',
nickname,
avatar: row.avatar || '',
must_change_pwd: !!Number(row.mustChangePwd),
token: signAdminToken(account),
cloud_token: await this.centerAuthService.issueCloudToken(account, nickname),
};
}
/** GET /api/admin/me */
@Get('/me')
async me(
@Headers('Authorization') authorization: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = '',
@Headers('X-Admin-User') xAdminUser: string = ''
) {
let account = '';
try {
account = await this.centerAuthService.identity(authorization, xAdminToken, xApiToken, xAdminUser);
} catch (e) {
account = '';
}
// 无效身份 → 401(触发前端自动登出回登录页,避免 200-空被误判为已登录)
if (!account) throw new ApiError(401, '登录态无效或已过期,请重新登录');
const row = await this.accountRepo.findOneBy({ account });
if (!row || !Number(row.status)) throw new ApiError(401, '登录态无效或已过期,请重新登录');
return {
account,
is_admin: !!Number(row.isAdmin),
dept: row.dept || '',
nickname: row.nickname || '',
avatar: row.avatar || '',
must_change_pwd: !!Number(row.mustChangePwd),
};
}
/** POST /api/admin/password — 自助改密 */
@Post('/password')
async password(
@Body() p: any,
@Headers('Authorization') authorization: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = '',
@Headers('X-Admin-User') xAdminUser: string = ''
) {
let login = '';
try {
login = await this.centerAuthService.identity(authorization, xAdminToken, xApiToken, xAdminUser);
} catch (e) {
throw new ApiError(401, '登录态无效或已过期,请重新登录');
}
if (!(p?.account || '').trim() || !p?.new_password) {
throw new ApiError(400, 'account 与新密码不能为空');
}
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 });
if (!row) throw new ApiError(401, '账号不存在');
if (!row.salt || !verifyPassword(p.old_password || '', row.salt, row.passwordHash)) {
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]
);
return { ok: true, account: login };
}
/** POST /api/admin/logout */
@Post('/logout')
async logout() {
return { ok: true };
}
/** GET /api/admin/platforms — 可授权平台列表 */
@Get('/platforms')
async platforms(
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
return { platforms: CONTROLPLANE_PLATFORMS };
}
}
@@ -0,0 +1,132 @@
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';
/**
* 控制台业务菜单(RBAC 驱动)。
* - GET /api/admin/me/menus:返回当前操作者的业务菜单树 + 权限标识集合。
* 管理员(is_admin=1)返回全量;非管理员按 cool-admin 角色权限过滤(预留,2F 用户体系落地后生效)。
* - 前端据此驱动动态路由与按钮权限("菜单要权限"落点)。
*/
interface MenuNode {
path: string;
name: string;
component: string;
meta: {
title: string;
icon: string;
perms: string[];
roles?: string[];
};
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'] },
},
{
path: '/system', name: 'System', component: '/system/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'] } },
],
},
];
/** 全部权限标识集合(供按钮级 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>;
/** GET /api/admin/me/menus */
@Get('/me/menus')
async meMenus(
@Headers('Authorization') authorization: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = '',
@Headers('X-Admin-User') xAdminUser: string = ''
) {
let account = '';
try {
account = await this.centerAuthService.identity(authorization, xAdminToken, xApiToken, xAdminUser);
} catch (e) {
account = '';
}
// 无效身份 → 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 };
}
}
@@ -0,0 +1,547 @@
import { CoolController, BaseController } from '@cool-midway/core';
import { Body, Del, File, Get, Headers, Inject, Param, Post, Provide, Put, Query } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import * as crypto from 'crypto';
import * as fs from 'fs';
import * as path from 'path';
import {
PluginEntity, PluginVersionEntity, AccountPluginEntity,
} from '../../entity/plugin';
import { AccountEntity } from '../../entity/account';
import { AuditLogEntity, RuntimeReportEntity, DeviceEntity, NotificationEntity } from '../../entity/runtime';
import { FileSourceEntity, FileserverStatusEntity } from '../../entity/resource';
import { ClientCredEntity } from '../../entity/account';
import { CenterAuthService, ApiError } from '../../service/auth';
import { rsaEncrypt } from '../../service/crypto';
import { PKG_DIR, SHELL_DIR, AVATAR_DIR } from '../../comm/conf';
import { pageBounds } 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._-]+$/;
const AVATAR_EXT = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
const NOTIF_LEVELS = new Set(['info', 'warning', 'important']);
const NOTIF_TARGETS = new Set(['all', 'account']);
/**
* 管理面运维/看板/文件源/凭证/通知(对齐旧 FastAPI apis/admin.py + file_sources.py + config_push.py 管理侧)
*/
@Provide()
@CoolController('/api/admin')
export class AdminOpsController extends BaseController {
@Inject()
ctx: any;
@Inject()
centerAuthService: CenterAuthService;
@InjectEntityModel(PluginEntity) pluginRepo: Repository<PluginEntity>;
@InjectEntityModel(PluginVersionEntity) pluginVersionRepo: Repository<PluginVersionEntity>;
@InjectEntityModel(AccountPluginEntity) accountPluginRepo: Repository<AccountPluginEntity>;
@InjectEntityModel(AccountEntity) accountRepo: Repository<AccountEntity>;
@InjectEntityModel(AuditLogEntity) auditRepo: Repository<AuditLogEntity>;
@InjectEntityModel(RuntimeReportEntity) runtimeRepo: Repository<RuntimeReportEntity>;
@InjectEntityModel(DeviceEntity) deviceRepo: Repository<DeviceEntity>;
@InjectEntityModel(NotificationEntity) notificationRepo: Repository<NotificationEntity>;
@InjectEntityModel(FileSourceEntity) fileSourceRepo: Repository<FileSourceEntity>;
@InjectEntityModel(FileserverStatusEntity) fileserverRepo: Repository<FileserverStatusEntity>;
@InjectEntityModel(ClientCredEntity) clientCredRepo: Repository<ClientCredEntity>;
/** GET /api/admin/overview */
@Get('/overview')
async overview(
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const plugins = await this.pluginRepo.find();
const accounts = await this.accountRepo.find();
const admins = (await this.accountRepo
.createQueryBuilder('a').select('a.account').where('a.isAdmin = 1').orderBy('a.account', 'ASC').getRawMany())
.map((r: any) => r.account);
const pluginOut = [];
for (const p of plugins) {
let m: any = {};
try { m = p.manifest ? JSON.parse(p.manifest) : {}; } catch (e) { /* ignore */ }
const versions = await this.pluginVersionRepo.findBy({ pluginId: p.id });
pluginOut.push({
id: p.id, name: p.name, description: p.description || '', category: p.category || '',
icon: p.icon || '', status: p.status, latest_version: p.latestVersion,
force_min_version: p.forceMinVersion, force_deadline: p.forceDeadline,
manifest: m, capabilities: m.capabilities || [], permissions: m.permissions || {},
field_count: Object.keys((m.fields || {}).properties || {}).length,
versions: versions.map(v => ({ version: v.version, filename: v.filename, sha256: v.sha256, uploaded_at: fmt(v.uploadedAt) })),
});
}
const accountOut = accounts.map(a => ({
id: a.id, account: a.account, is_admin: !!Number(a.isAdmin), dept: a.dept || '',
nickname: a.nickname || '', avatar: a.avatar || '', status: Number(a.status), created_at: fmt(a.createdAt),
}));
return { plugins: pluginOut, accounts: accountOut, admins };
}
/** GET /api/admin/stats — 数据看板 */
@Get('/stats')
async stats(
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const m = this.runtimeRepo.manager;
const users: any = (await m.query(
`SELECT (SELECT COUNT(*) FROM accounts) AS total,
(SELECT COUNT(*) FROM accounts WHERE is_admin = 1) AS admins,
(SELECT COUNT(DISTINCT account) FROM account_plugins) AS authorized`))[0];
const plugins: any = (await m.query(
`SELECT (SELECT COUNT(*) FROM plugins) AS total,
(SELECT COUNT(*) FROM plugins WHERE status='published') AS published,
(SELECT COUNT(*) FROM plugins WHERE status='disabled') AS disabled,
(SELECT COUNT(*) FROM plugins WHERE status='revoked') AS revoked`))[0];
const runs: any = (await m.query(
`SELECT (SELECT COUNT(*) FROM runtime_reports WHERE status='start') AS started,
(SELECT COUNT(*) FROM runtime_reports WHERE status IN ('done','success')) AS success,
(SELECT COUNT(*) FROM runtime_reports WHERE status IN ('error','failed')) AS failed,
(SELECT COALESCE(SUM(duration_sec),0) FROM runtime_reports) AS duration_sec,
(SELECT COUNT(DISTINCT account) FROM runtime_reports WHERE account <> '') AS active_users,
(SELECT COUNT(DISTINCT plugin_id) FROM runtime_reports WHERE plugin_id <> '') AS active_plugins`))[0];
const trendRows: any[] = await m.query(
`SELECT LEFT(at,10) AS day,
SUM(CASE WHEN status='start' THEN 1 ELSE 0 END) AS runs,
SUM(CASE WHEN status IN ('done','success') THEN 1 ELSE 0 END) AS success,
SUM(CASE WHEN status IN ('error','failed') THEN 1 ELSE 0 END) AS failed
FROM runtime_reports WHERE at >= CURDATE() - INTERVAL 13 DAY GROUP BY day ORDER BY day`);
const trendMap: Record<string, any> = {};
for (const r of trendRows) trendMap[r.day] = r;
const trend = [];
const d = new Date();
for (let i = 13; i >= 0; i--) {
const day = new Date(d.getTime() - i * 86400000);
const key = `${day.getFullYear()}-${String(day.getMonth() + 1).padStart(2, '0')}-${String(day.getDate()).padStart(2, '0')}`;
const r = trendMap[key];
trend.push({ day: key.slice(5), runs: Number(r?.runs || 0), success: Number(r?.success || 0), failed: Number(r?.failed || 0) });
}
const topPlugins: any[] = await m.query(
`SELECT plugin_id AS pluginId, COUNT(*) AS runs,
SUM(CASE WHEN status='start' THEN 1 ELSE 0 END) AS triggered,
SUM(CASE WHEN status IN ('done','success') THEN 1 ELSE 0 END) AS success,
SUM(CASE WHEN status IN ('error','failed') THEN 1 ELSE 0 END) AS failed,
COALESCE(SUM(duration_sec),0) AS durationSec
FROM runtime_reports GROUP BY plugin_id ORDER BY triggered DESC LIMIT 8`);
const pnames: Record<string, string> = {};
for (const p of await this.pluginRepo.find()) pnames[p.id] = p.name;
const topUsers: any[] = await m.query(
`SELECT account, COUNT(*) AS runs FROM runtime_reports
WHERE status='start' AND account <> '' GROUP BY account ORDER BY runs DESC LIMIT 8`);
const nick: Record<string, string> = {};
for (const a of await this.accountRepo.find()) nick[a.account] = a.nickname || '';
return {
users: { total: Number(users.total || 0), admins: Number(users.admins || 0), authorized: Number(users.authorized || 0) },
plugins: { total: Number(plugins.total || 0), published: Number(plugins.published || 0), disabled: Number(plugins.disabled || 0), revoked: Number(plugins.revoked || 0) },
runs: { total: Number(runs.started || 0), success: Number(runs.success || 0), failed: Number(runs.failed || 0), durationSec: Number(runs.duration_sec || 0), activeUsers: Number(runs.active_users || 0), activePlugins: Number(runs.active_plugins || 0) },
trend,
topPlugins: topPlugins.map((tp: any) => ({ ...tp, name: pnames[tp.pluginId] || tp.pluginId, runs: Number(tp.triggered || 0) })),
topUsers: topUsers.map((tu: any) => ({ account: tu.account, runs: Number(tu.runs || 0), nickname: nick[tu.account] || '' })),
today: d.toISOString().slice(0, 10),
};
}
/** GET /api/admin/audit */
@Get('/audit')
async audit(
@Query('page') page: number = 1, @Query('page_size') pageSize: number = 20,
@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);
const [limit, offset] = pageBounds(page, pageSize);
const cond: string[] = [];
const args: any[] = [];
if ((action || '').trim()) { cond.push('action = ?'); args.push(action.trim()); }
if ((q || '').trim()) { cond.push('(account LIKE ? OR target LIKE ? OR detail LIKE ?)'); args.push(`%${q.trim()}%`, `%${q.trim()}%`, `%${q.trim()}%`); }
const where = cond.length ? ' WHERE ' + cond.join(' AND ') : '';
const m = this.auditRepo.manager;
const total: any = (await m.query(`SELECT COUNT(*) AS c FROM audit_logs${where}`, args))[0];
const today: any = (await m.query(`SELECT COUNT(*) AS c FROM audit_logs WHERE at >= CURDATE()`))[0];
const rows: any[] = await m.query(
`SELECT id, account, action, target, detail, at FROM audit_logs${where} ORDER BY id DESC LIMIT ? OFFSET ?`,
[...args, limit, offset]);
const nick: Record<string, string> = {};
for (const a of await this.accountRepo.find()) nick[a.account] = a.nickname || '';
return {
items: rows.map((r: any) => ({ ...r, nickname: nick[r.account] || '', at: fmtStr(r.at) })),
total: Number(total.c || 0), today: Number(today.c || 0),
};
}
/** GET /api/admin/reports */
@Get('/reports')
async reports(
@Query('page') page: number = 1, @Query('page_size') pageSize: number = 20,
@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);
const [limit, offset] = pageBounds(page, pageSize);
const cond: string[] = [];
const args: any[] = [];
if ((status || '').trim()) {
const vals = 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 ((q || '').trim()) {
cond.push('(account LIKE ? OR device_id LIKE ? OR plugin_id LIKE ? OR msg LIKE ?)');
args.push(`%${q.trim()}%`, `%${q.trim()}%`, `%${q.trim()}%`, `%${q.trim()}%`);
}
const where = cond.length ? ' WHERE ' + cond.join(' AND ') : '';
const m = this.runtimeRepo.manager;
const total: any = (await m.query(`SELECT COUNT(*) AS c FROM runtime_reports${where}`, args))[0];
const today: any = (await m.query('SELECT COUNT(*) AS c FROM runtime_reports WHERE at >= CURDATE()'))[0];
const failed: any = (await m.query(`SELECT COUNT(*) AS c FROM runtime_reports WHERE status IN ('error','failed')`))[0];
const rows: any[] = await m.query(
`SELECT id, account, device_id AS deviceId, plugin_id AS pluginId, version, status, msg,
duration_sec AS durationSec, at
FROM runtime_reports${where} ORDER BY id DESC LIMIT ? OFFSET ?`, [...args, limit, offset]);
const nick: Record<string, string> = {};
for (const a of await this.accountRepo.find()) nick[a.account] = a.nickname || '';
return {
items: rows.map((r: any) => ({ ...r, nickname: nick[r.account] || '', at: fmtStr(r.at) })),
total: Number(total.c || 0), today: Number(today.c || 0), failed: Number(failed.c || 0),
};
}
/** GET /api/admin/devices */
@Get('/devices')
async devices(
@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);
const [limit, offset] = pageBounds(page, pageSize);
const m = this.deviceRepo.manager;
const total: any = (await m.query('SELECT COUNT(*) AS c FROM devices'))[0];
const rows: any[] = await m.query(
`SELECT device_id, account, hostname, os, ip, chrome_installed, chrome_version, chrome_ok,
last_seen, status, created_at, updated_at
FROM devices ORDER BY last_seen DESC LIMIT ? OFFSET ?`, [limit, offset]);
return { items: rows.map((r: any) => ({ ...r, last_seen: fmtStr(r.last_seen), created_at: fmtStr(r.created_at), updated_at: fmtStr(r.updated_at) })), total: Number(total.c || 0) };
}
/** GET /api/admin/devices/summary */
@Get('/devices/summary')
async devicesSummary(
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const m = this.deviceRepo.manager;
const total: any = (await m.query('SELECT COUNT(*) AS c FROM devices'))[0];
const byAccount: any[] = await m.query(
'SELECT account, COUNT(*) AS device_count, MAX(last_seen) AS last_seen FROM devices GROUP BY account ORDER BY account');
const nick: Record<string, [string, string]> = {};
for (const a of await this.accountRepo.find()) nick[a.account] = [a.nickname || '', a.dept || ''];
return {
total: Number(total.c || 0),
by_version: [],
by_account: byAccount.map((r: any) => ({ ...r, nickname: nick[r.account]?.[0] || '', dept: nick[r.account]?.[1] || '' })),
};
}
/** POST /api/admin/shell-release — 发布壳子新版 */
@Post('/shell-release')
async shellRelease(
@File() file: any,
@Query('version') version: string = '',
@Query('notes') notes: string = '',
@Query('sha256') sha256: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(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);
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`;
fs.mkdirSync(SHELL_DIR, { recursive: true });
fs.writeFileSync(path.join(SHELL_DIR, filename), content);
const sha = sha256 || crypto.createHash('sha256').update(content).digest('hex');
fs.writeFileSync(path.join(SHELL_DIR, 'version.json'), JSON.stringify({
version, filename, sha256: sha, notes: notes || '',
}, null, 2), 'utf8');
await this.centerAuthService.audit(login, 'shell-release', filename);
return { ok: true, version, filename, sha256: sha };
}
/** file-sources 管理端 CRUD */
@Get('/file-sources')
async fileSourcesList(
@Query('category') category: string = '', @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);
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();
const [limit, offset] = pageBounds(page, pageSize);
const sliced = rows.sort((a, b) => (versionKey(b.version) - versionKey(a.version)) || (b.id - a.id)).slice(offset, offset + limit);
return {
category: category || '',
items: sliced.map(r => ({ id: r.id, category: r.category, version: r.version, filename: r.filename, url: r.url, sha256: r.sha256, notes: r.notes, enabled: !!Number(r.enabled), updated_at: fmt(r.updatedAt) })),
total: rows.length,
};
}
@Post('/file-sources')
async fileSourcesUpsert(
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const category = (b?.category || '').trim();
const version = (b?.version || '').trim();
const url = (b?.url || '').trim();
if (!category) throw new ApiError(400, 'category 不能为空');
if (!url) throw new ApiError(400, 'url 不能为空');
const m = this.fileSourceRepo.manager;
const row: any = (await m.query('SELECT id FROM file_sources WHERE category = ? AND version = ?', [category, version]))[0];
let fid: number;
if (row) {
await m.query('UPDATE file_sources SET filename=?, url=?, sha256=?, notes=?, enabled=?, updated_at=NOW() WHERE id=?',
[(b?.filename || '').trim(), url, (b?.sha256 || '').trim(), (b?.notes || '').trim(), Number(!!b?.enabled), row.id]);
fid = row.id;
} else {
const r: any = await m.query('INSERT INTO file_sources(category, version, filename, url, sha256, notes, enabled, updated_at) VALUES (?,?,?,?,?,?,?,NOW())',
[category, version, (b?.filename || '').trim(), url, (b?.sha256 || '').trim(), (b?.notes || '').trim(), Number(!!b?.enabled)]);
fid = r.insertId;
}
await this.centerAuthService.audit(login, 'file-source-upsert', `${category}@${version}`, url);
return { ok: true, id: fid, category, version };
}
@Put('/file-sources/:fid')
async fileSourcesPatch(
@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 id = Number(fid || 0);
if (b?.enabled === undefined && b?.enabled === null && b?.notes === undefined) {
throw new ApiError(400, '无更新字段');
}
const m = this.fileSourceRepo.manager;
if (b?.enabled !== undefined && b?.enabled !== null) {
await m.query('UPDATE file_sources SET enabled = ?, updated_at = NOW() WHERE id = ?', [Number(!!b.enabled), id]);
}
if (b?.notes !== undefined && b?.notes !== null) {
await m.query('UPDATE file_sources SET notes = ?, updated_at = NOW() WHERE id = ?', [String(b.notes).trim(), id]);
}
const chk: any = (await m.query('SELECT id FROM file_sources WHERE id = ?', [id]))[0];
if (!chk) throw new ApiError(404, '记录不存在');
await this.centerAuthService.audit(login, 'file-source-patch', String(id));
return { ok: true, id };
}
@Del('/file-sources/:fid')
async fileSourcesDelete(
@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 id = Number(fid || 0);
const m = this.fileSourceRepo.manager;
const r: any = await m.query('DELETE FROM file_sources WHERE id = ?', [id]);
if (!r.affectedRows) throw new ApiError(404, '记录不存在');
await this.centerAuthService.audit(login, 'file-source-delete', String(id));
return { ok: true, id };
}
/** creds 管理(manage 列表 / seed 明文源) */
@Get('/creds/manage')
async credsManage(
@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);
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];
const rows: any[] = await m.query(
'SELECT c.account, c.pubkey_pem, c.creds, c.updated_at, a.nickname FROM client_creds c LEFT JOIN accounts a ON a.account = c.account ORDER BY c.account LIMIT ? OFFSET ?',
[limit, offset]);
return {
items: rows.map((r: any) => {
let creds: any = {};
try { creds = JSON.parse(r.creds || '{}'); } catch (e) { /* ignore */ }
return { account: r.account, nickname: r.nickname || '', has_pubkey: !!r.pubkey_pem, creds, updated_at: fmtStr(r.updated_at) };
}),
total: Number(total.c || 0),
allowed_keys: ALLOWED_CREDS_KEYS,
};
}
@Post('/creds/seed')
async credsSeed(
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const account = (b?.account || '').trim();
if (!account) throw new ApiError(400, 'account 不能为空');
const allowed: Record<string, string> = {};
for (const [k, v] of Object.entries(b?.values || {})) {
if (ALLOWED_CREDS_KEYS.includes(k)) allowed[k] = String(v);
}
const m = this.clientCredRepo.manager;
const row: any = (await m.query('SELECT pubkey_pem FROM client_creds WHERE account = ?', [account]))[0];
if (row) {
await m.query('UPDATE client_creds SET creds = ?, updated_at = NOW() WHERE account = ?', [JSON.stringify(allowed), account]);
} else {
await m.query('INSERT INTO client_creds(account, pubkey_pem, creds, updated_at) VALUES (?, ?, ?, NOW())',
[account, '', JSON.stringify(allowed)]);
}
await this.centerAuthService.audit(login, 'creds-seed', account, `keys=${Object.keys(allowed).sort()}`);
return { ok: true, account, seeded_keys: Object.keys(allowed).sort() };
}
/** 通知管理 CRUD */
@Get('/notifications')
async notifList(
@Query('page') page: number = 1, @Query('page_size') pageSize: number = 20,
@Query('q') q: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const [limit, offset] = pageBounds(page, pageSize);
const cond: string[] = [];
const args: any[] = [];
if ((q || '').trim()) {
cond.push('(title LIKE ? OR content LIKE ? OR account LIKE ?)');
args.push(`%${q.trim()}%`, `%${q.trim()}%`, `%${q.trim()}%`);
}
const where = cond.length ? ' WHERE ' + cond.join(' AND ') : '';
const m = this.notificationRepo.manager;
const total: any = (await m.query(`SELECT COUNT(*) AS c FROM notifications${where}`, args))[0];
const rows: any[] = await m.query(
`SELECT id, title, content, level, target, account, created_at, expires_at, active
FROM notifications${where} ORDER BY id DESC LIMIT ? OFFSET ?`, [...args, limit, offset]);
return {
items: rows.map((r: any) => ({ id: r.id, title: r.title, content: r.content, level: r.level, target: r.target, account: r.account, created_at: fmtStr(r.created_at), expires_at: r.expires_at ? fmtStr(r.expires_at) : null, active: Number(r.active) })),
total: Number(total.c || 0),
};
}
@Post('/notifications')
async notifCreate(
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(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');
if (!NOTIF_TARGETS.has(b?.target)) throw new ApiError(400, 'target 仅允许 all/account');
if (b?.target === 'account' && !(b?.account || '').trim()) throw new ApiError(400, 'target=account 时必须指定 account');
const r: any = await this.notificationRepo.manager.query(
'INSERT INTO notifications(title, content, level, target, account, expires_at) VALUES (?,?,?,?,?,?)',
[title, (b?.content || '').trim(), b?.level, b?.target, (b?.account || '').trim(), b?.expires_at ? String(b.expires_at).replace('T', ' ').slice(0, 19) : null]);
await this.centerAuthService.audit(login, 'notify-create', `通知 #${r.insertId} ${title} → ${b?.target}`);
return { ok: true, id: r.insertId, title, target: b?.target, pushed: 0 };
}
@Put('/notifications/:nid')
async notifToggle(
@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 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}`);
return { ok: true, id, active: active === 'true' };
}
@Del('/notifications/:nid')
async notifDelete(
@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 id = Number(nid || 0);
await this.notificationRepo.manager.query('DELETE FROM notifications WHERE id = ?', [id]);
await this.centerAuthService.audit(login, 'notify-delete', `通知 #${id}`);
return { ok: true, id };
}
/** GET /api/admin/fileserver/status */
@Get('/fileserver/status')
async fileserverStatus(
@Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const rows = await this.fileserverRepo.find({ order: { lastSeen: 'DESC' } as any });
return {
// 契约对齐旧 FastAPI:键名 fileservers;status/offline_notified 布尔;total_size 数值
fileservers: rows.map(r => ({
id: r.id, host: r.host, base_url: r.baseUrl, hostname: r.hostname, ip: r.ip,
port: r.port, file_count: r.fileCount, total_size: Number(r.totalSize),
version: r.version, uptime_sec: r.uptimeSec, last_seen: fmt(r.lastSeen),
status: !!Number(r.status), last_status_change: fmt(r.lastStatusChange),
offline_notified: !!Number(r.offlineNotified), created_at: fmt(r.createdAt),
})),
};
}
/** POST /api/admin/avatar — 上传头像 */
@Post('/avatar')
async avatarUpload(
@File() file: any,
@Query('account') account: string = '',
@Headers('Authorization') authorization: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = '',
@Headers('X-Admin-User') xAdminUser: string = ''
) {
let login = '';
try {
login = await this.centerAuthService.identity(authorization, xAdminToken, xApiToken, xAdminUser);
} catch (e) {
throw new ApiError(401, '登录态无效或已过期,请重新登录');
}
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);
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);
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} 不存在`);
fs.mkdirSync(AVATAR_DIR, { recursive: true });
const fname = `${account}${ext}`;
fs.writeFileSync(path.join(AVATAR_DIR, fname), content);
if (acc.avatar && acc.avatar !== fname) {
try { fs.unlinkSync(path.join(AVATAR_DIR, acc.avatar)); } catch (e) { /* ignore */ }
}
await this.accountRepo.update({ account }, { avatar: fname });
return { ok: true, account, avatar: fname };
}
}
function versionKey(v: string): number {
return Number(String(v || '').split('.').map(s => s.padStart(4, '0')).join('')) || 0;
}
function fmt(d: Date | null): string {
if (!d) return '';
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())}`;
}
function fmtStr(d: any): string {
if (!d) return '';
if (d instanceof Date) return fmt(d);
return String(d).replace('T', ' ').slice(0, 19);
}
@@ -0,0 +1,277 @@
import { CoolController, BaseController } from '@cool-midway/core';
import { Body, File, Get, Headers, Inject, Post, Provide, Query } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import * as crypto from 'crypto';
import * as fs from 'fs';
import * as path from 'path';
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';
const SAFE_NAME_RE = /^[A-Za-z0-9._-]+$/;
/** 版本号数值键("1.10" > "1.9") */
function versionKey(v: string): number[] {
return String(v || '').split('.').map(s => parseInt(s, 10) || 0);
}
/**
* 插件管理(对齐旧 FastAPI apis/admin.py 插件部分)
* - GET /api/admin/plugins:插件列表(分页 + 搜索 + 版本历史 + 授权账号)
* - POST /api/admin/pkg:上传发布插件包(校验 zip + manifest + sha256 + 保留最近 3 版)
* - POST /api/admin/plugin/delete、/api/admin/plugin/patch
* - GET /api/admin/grant_data、/api/admin/account_grants
*/
@Provide()
@CoolController('/api/admin')
export class AdminPluginController extends BaseController {
@Inject()
centerAuthService: CenterAuthService;
@InjectEntityModel(PluginEntity)
pluginRepo: Repository<PluginEntity>;
@InjectEntityModel(PluginVersionEntity)
pluginVersionRepo: Repository<PluginVersionEntity>;
@InjectEntityModel(AccountPluginEntity)
accountPluginRepo: Repository<AccountPluginEntity>;
/** GET /api/admin/plugins */
@Get('/plugins')
async plugins(
@Query('page') page: number = 1,
@Query('page_size') pageSize: number = 20,
@Query('q') q: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const [limit, offset] = pageBounds(page, pageSize);
const cond: string[] = [];
const args: any[] = [];
if ((q || '').trim()) {
cond.push('(id LIKE ? OR name LIKE ?)');
args.push(`%${q.trim()}%`, `%${q.trim()}%`);
}
const where = cond.length ? ' WHERE ' + cond.join(' AND ') : '';
const m = this.pluginRepo.manager;
const total: any = (await m.query(`SELECT COUNT(*) AS c FROM plugins${where}`, args))[0];
const rows: any[] = await m.query(
`SELECT id, name, description, category, icon, status, latest_version,
force_min_version, force_deadline, manifest
FROM plugins${where} ORDER BY id LIMIT ? OFFSET ?`,
[...args, limit, offset]
);
const items = [];
for (const p of rows) {
let manifest: any = {};
try { manifest = p.manifest ? JSON.parse(p.manifest) : {}; } catch (e) { /* ignore */ }
const versions: any[] = await m.query(
'SELECT version, filename, sha256, uploaded_at FROM plugin_versions WHERE plugin_id = ? ORDER BY version', [p.id]);
const accounts: any[] = await m.query(
'SELECT ap.account, a.nickname FROM account_plugins ap LEFT JOIN accounts a ON a.account = ap.account WHERE ap.plugin_id = ? ORDER BY ap.account', [p.id]);
items.push({
id: p.id,
name: p.name,
description: p.description || '',
category: p.category || '',
icon: p.icon || '',
status: p.status,
latest_version: p.latest_version,
force_min_version: p.force_min_version,
force_deadline: p.force_deadline,
manifest,
capabilities: manifest.capabilities || [],
field_count: Object.keys((manifest.fields || {}).properties || {}).length,
versions: versions.map((v: any) => ({ version: v.version, filename: v.filename, sha256: v.sha256, uploaded_at: fmtStr(v.uploaded_at) })),
accounts: accounts.map((r: any) => ({ account: r.account, nickname: r.nickname || '' })),
});
}
return { items, total: Number(total.c || 0) };
}
/** POST /api/admin/pkg — 上传发布插件包 */
@Post('/pkg')
async pkg(
@File() file: any,
@Query('plugin_id') pluginId: string = '',
@Query('name') name: string = '',
@Query('version') version: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
pluginId = (pluginId || '').trim();
version = (version || '').trim();
name = (name || '').trim() || pluginId;
if (!pluginId || !version) throw new ApiError(400, 'plugin_id 与 version 不能为空');
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);
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 需一致)
let manifest: any = {};
try {
const zip = new AdmZip(content);
const entry = zip.getEntry('plugin.json');
if (entry) {
manifest = JSON.parse(entry.getData().toString('utf8').replace(/^\uFEFF/, ''));
const mid = String(manifest.id || '').trim();
if (mid && mid !== pluginId) {
throw new ApiError(400, `plugin.json 内 id「${mid}」与路径 plugin_id「${pluginId}」不一致`);
}
name = String(manifest.name || name).trim() || pluginId;
}
} catch (e: any) {
if (e instanceof ApiError) throw e;
throw new ApiError(400, `插件包校验失败: ${e.message || e}`);
}
const filename = `${pluginId}_v${version}.zip`;
const target = path.join(PKG_DIR, filename);
fs.mkdirSync(PKG_DIR, { recursive: true });
fs.writeFileSync(target, content);
const sha256 = crypto.createHash('sha256').update(content).digest('hex');
const manifestJson = JSON.stringify(manifest, null, 0) || '{}';
// 插件主记录 upsert
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]
);
await this.pluginVersionRepo.manager.query(
`INSERT INTO plugin_versions(plugin_id, version, filename, uploaded_at, sha256, size_bytes)
VALUES (?, ?, ?, NOW(), ?, ?)
ON DUPLICATE KEY UPDATE filename = VALUES(filename), uploaded_at = VALUES(uploaded_at), sha256 = VALUES(sha256)`,
[pluginId, version, filename, sha256, content.length]
);
// 更新 latest_version(若更高)
const cur = await this.pluginRepo.findOneBy({ id: pluginId });
if (cur && versionKey(cur.latestVersion) < versionKey(version)) {
await this.pluginRepo.update({ id: pluginId }, { latestVersion: version });
}
// 仅保留最近 3 个版本(DB + 磁盘)
const versions = await this.pluginVersionRepo
.createQueryBuilder('v')
.where('v.pluginId = :id', { id: pluginId })
.orderBy('v.id', 'DESC')
.getMany();
const stale = versions.slice(3);
for (const s of stale) {
await this.pluginVersionRepo.delete({ id: s.id });
try { fs.unlinkSync(path.join(PKG_DIR, s.filename)); } catch (e) { /* ignore */ }
}
await this.centerAuthService.audit(login, 'plugin-publish', pluginId, `version=${version}, filename=${filename}`);
return { ok: true, plugin_id: pluginId, version, filename };
}
/** POST /api/admin/plugin/delete */
@Post('/plugin/delete')
async pluginDelete(
@Body() d: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const pid = (d?.plugin_id || '').trim();
if (!pid) throw new ApiError(400, 'plugin_id 必填');
const pl = await this.pluginRepo.findOneBy({ id: pid });
if (!pl) throw new ApiError(400, `插件 ${pid} 不存在`);
const files = await this.pluginVersionRepo.findBy({ pluginId: pid });
await this.pluginVersionRepo.manager.query(
'DELETE FROM account_plugins WHERE plugin_id = ?', [pid]);
await this.pluginVersionRepo.manager.query(
'DELETE FROM plugin_versions WHERE plugin_id = ?', [pid]);
await this.pluginRepo.delete({ id: pid });
for (const f of files) {
try { fs.unlinkSync(path.join(PKG_DIR, f.filename)); } catch (e) { /* ignore */ }
}
await this.centerAuthService.audit(login, 'plugin-delete', pid, `files=${files.length}`);
return { ok: true, plugin_id: pid };
}
/** POST /api/admin/plugin/patch — 更新元信息/状态/强制更新 */
@Post('/plugin/patch')
async pluginPatch(
@Body() d: any,
@Query('plugin_id') pluginId: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(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?.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) {
set.force_min_version = String(d.force_min_version).trim();
set.force_deadline = String(d.force_deadline).trim();
} else if ((d?.force_min_version || d?.force_deadline) && !d?.clear_force) {
throw new ApiError(400, '强制更新需同时提供 force_min_version 与 force_deadline');
} else if (d?.clear_force) {
set.force_min_version = null;
set.force_deadline = null;
}
if (!Object.keys(set).length) return { ok: true };
const pl = await this.pluginRepo.findOneBy({ id: pid });
if (!pl) throw new ApiError(400, `插件 ${pid} 不存在`);
await this.pluginRepo.update({ id: pid }, set);
return { ok: true, plugin_id: pid };
}
/** GET /api/admin/grant_data */
@Get('/grant_data')
async grantData(
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(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(
'SELECT account, nickname, dept, status FROM accounts WHERE status = 1 ORDER BY account');
return { plugins, accounts };
}
/** GET /api/admin/account_grants?account= */
@Get('/account_grants')
async accountGrants(
@Query('account') account: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
account = (account || '').trim();
const grants = await this.accountPluginRepo.findBy({ account });
const platforms = await this.pluginRepo.manager.query(
'SELECT platform_id FROM account_platforms WHERE account = ? ORDER BY platform_id', [account]);
return {
plugins: grants.map(g => ({ plugin_id: g.pluginId, canRun: !!Number(g.canRun), canDownload: !!Number(g.canDownload) })),
platforms: platforms.map((r: any) => r.platform_id),
};
}
}
function fmt(d: Date | null): string {
if (!d) return '';
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())}`;
}
function fmtStr(d: any): string {
if (!d) return '';
if (d instanceof Date) return fmt(d);
return String(d).replace('T', ' ').slice(0, 19);
}
@@ -0,0 +1,568 @@
import { CoolController, BaseController } from '@cool-midway/core';
import { Body, Get, Headers, Inject, InjectClient, Post, Provide, Query } from '@midwayjs/core';
import { CachingFactory, MidwayCache } from '@midwayjs/cache-manager';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository, In } from 'typeorm';
import { CenterAuthService } from '../../service/auth';
import { BaseSysUserService } from '../../../base/service/sys/user';
import { BaseSysRoleService } from '../../../base/service/sys/role';
import { BaseSysPermsService } from '../../../base/service/sys/perms';
import { BaseSysUserEntity } from '../../../base/entity/sys/user';
import { BaseSysUserRoleEntity } from '../../../base/entity/sys/user_role';
import { BaseSysRoleEntity } from '../../../base/entity/sys/role';
import { BaseSysRoleMenuEntity } from '../../../base/entity/sys/role_menu';
import { BaseSysRoleDepartmentEntity } from '../../../base/entity/sys/role_department';
import { BaseSysMenuEntity } from '../../../base/entity/sys/menu';
import { BaseSysDepartmentEntity } from '../../../base/entity/sys/department';
/**
* 系统管理(37du 控制台侧自建 RBAC 管理)。
*
* 身份体系:控制台登录 = accounts + HMAC 管理员票据(requireAdmin),与 cool-admin 的
* base_sys_user + JWT 不同体系,故由本层统一出口管理 cool-admin 的 RBAC 表(base_sys_*)。
* 写操作全部委托 base 原生 service(md5 密码 / passwordV 失效旧 token / 授权缓存刷新
* 与原生登录链路完全一致),并对内置超管(admin 用户 / admin 角色)加保护。
*
* 只读:GET /api/admin/sys/{users,roles,menus,departments}
* 用户:POST /api/admin/sys/user/{add,edit,del} + GET /user/info
* 角色:POST /api/admin/sys/role/{add,edit,del} + GET /role/info(含 menuIdList/departmentIdList)
* 菜单:POST /api/admin/sys/menu/{add,edit,del}
* 部门:POST /api/admin/sys/dept/{add,edit,del}
*/
@Provide()
@CoolController('/api/admin/sys')
export class AdminSysController extends BaseController {
@Inject()
centerAuthService: CenterAuthService;
@Inject()
baseSysUserService: BaseSysUserService;
@Inject()
baseSysRoleService: BaseSysRoleService;
@Inject()
baseSysPermsService: BaseSysPermsService;
@InjectClient(CachingFactory, 'default')
midwayCache: MidwayCache;
@InjectEntityModel(BaseSysUserEntity)
baseSysUserRepo: Repository<BaseSysUserEntity>;
@InjectEntityModel(BaseSysUserRoleEntity)
baseSysUserRoleRepo: Repository<BaseSysUserRoleEntity>;
@InjectEntityModel(BaseSysRoleEntity)
baseSysRoleRepo: Repository<BaseSysRoleEntity>;
@InjectEntityModel(BaseSysRoleMenuEntity)
baseSysRoleMenuRepo: Repository<BaseSysRoleMenuEntity>;
@InjectEntityModel(BaseSysRoleDepartmentEntity)
baseSysRoleDeptRepo: Repository<BaseSysRoleDepartmentEntity>;
@InjectEntityModel(BaseSysMenuEntity)
baseSysMenuRepo: Repository<BaseSysMenuEntity>;
@InjectEntityModel(BaseSysDepartmentEntity)
baseSysDeptRepo: Repository<BaseSysDepartmentEntity>;
private async admin(xAdminToken: string, xApiToken: string): Promise<string> {
return this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
}
/**
* cool BaseService 的实体由原生 CRUD 控制器经 setEntity(repo) 注入;
* 本控制器直接委托 base service,需先注入对应 Repository(否则报"未设置操作实体")。
*/
private prepareDelegation(): void {
this.baseSysUserService.setEntity(this.baseSysUserRepo);
this.baseSysRoleService.setEntity(this.baseSysRoleRepo);
}
private async audit(account: string, action: string, target: string, detail: any) {
let json = '';
try {
json = detail === undefined ? '' : JSON.stringify(detail);
} catch (e) {
json = '';
}
await this.centerAuthService.audit(account, action, target, json);
}
// ==================== 只读列表 ====================
/** GET /api/admin/sys/users — 控制台用户(含部门名/角色,不含密码) */
@Get('/users')
async users(
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.admin(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
FROM base_sys_user a LEFT JOIN base_sys_department b ON a.departmentId = b.id
ORDER BY a.id`
);
const userRoles: any[] = await this.baseSysUserRepo.manager.query(
`SELECT a.userId, a.roleId, r.name AS roleName FROM base_sys_user_role a
LEFT JOIN base_sys_role r ON r.id = a.roleId`
);
const items = rows.map(r => {
const roles = userRoles.filter(u => Number(u.userId) === Number(r.id));
return {
...r,
roleIds: roles.map(u => Number(u.roleId)),
roleName: roles.map(u => u.roleName || '').filter(Boolean).join(','),
usernameProtected: r.username === 'admin',
};
});
return { items };
}
/** GET /api/admin/sys/roles — 角色 */
@Get('/roles')
async roles(
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.admin(xAdminToken, xApiToken);
const rows: any[] = await this.baseSysUserRepo.manager.query(
`SELECT id, name, label, remark, relevance FROM base_sys_role ORDER BY id`
);
return {
items: rows.map(r => ({ ...r, relevance: !!Number(r.relevance), protected: Number(r.id) === 1 })),
};
}
/** GET /api/admin/sys/menus — 菜单(树) */
@Get('/menus')
async menus(
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.admin(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`
);
return { items: buildTree(rows) };
}
/** GET /api/admin/sys/departments — 部门(树) */
@Get('/departments')
async departments(
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.admin(xAdminToken, xApiToken);
const rows: any[] = await this.baseSysUserRepo.manager.query(
`SELECT id, parentId, name, orderNum, createTime FROM base_sys_department ORDER BY orderNum, id`
);
return { items: buildTree(rows) };
}
// ==================== 用户管理 ====================
/** GET /api/admin/sys/user/info?id= — 用户详情(含 roleIdList,不含密码) */
@Get('/user/info')
async userInfo(
@Query('id') id: number,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.admin(xAdminToken, xApiToken);
if (!id) throw err(400, 'id 不能为空');
this.prepareDelegation();
return this.baseSysUserService.info(id);
}
/** POST /api/admin/sys/user/add — 新增用户(md5 密码 + 角色分配 + 缓存刷新) */
@Post('/user/add')
async userAdd(
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(xAdminToken, xApiToken);
const username = String(b?.username || '').trim();
if (!username) throw err(400, 'username 不能为空');
if (!b?.password) throw err(400, 'password 不能为空');
if (String(b.username).toLowerCase() === 'admin') throw err(400, '不能创建内置用户名 admin');
this.prepareDelegation();
const param = {
...b,
username,
roleIdList: Array.isArray(b?.roleIdList) ? b.roleIdList.map(Number) : [],
};
const raw = await this.baseSysUserService.add(param as any);
const id = Number((raw as any)?.id ?? raw ?? 0);
await this.audit(login, 'sys-user-add', username, { id });
return { ok: true, id };
}
/** POST /api/admin/sys/user/edit — 编辑用户(改密自动 passwordV+1 使旧 token 失效;不支持改 username) */
@Post('/user/edit')
async userEdit(
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(xAdminToken, xApiToken);
if (!b?.id) throw err(400, 'id 不能为空');
const row = await this.baseSysUserRepo.findOneBy({ id: Number(b.id) });
if (!row) throw err(404, '用户不存在');
if (row.username === 'admin') throw err(403, '内置管理员不允许编辑');
this.prepareDelegation();
const param: any = { ...b, id: Number(b.id) };
delete param.username; // 用户名不可改
if (Array.isArray(b?.roleIdList)) param.roleIdList = b.roleIdList.map(Number);
else delete param.roleIdList;
await this.baseSysUserService.update(param);
await this.audit(login, 'sys-user-edit', row.username, { id: param.id });
return { ok: true };
}
/** POST /api/admin/sys/user/del — 删除用户(内置 admin 保护) */
@Post('/user/del')
async userDel(
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(xAdminToken, xApiToken);
if (!b?.id) throw err(400, 'id 不能为空');
const row = await this.baseSysUserRepo.findOneBy({ id: Number(b.id) });
if (!row) throw err(404, '用户不存在');
if (row.username === 'admin' || Number(b.id) === 1) throw err(403, '内置管理员不允许删除');
await this.baseSysUserRoleRepo.delete({ userId: Number(b.id) });
await this.baseSysUserRepo.delete({ id: Number(b.id) });
await this.midwayCache.del(`admin:token:${b.id}`);
await this.midwayCache.del(`admin:perms:${b.id}`);
await this.midwayCache.del(`admin:department:${b.id}`);
await this.midwayCache.del(`admin:passwordVersion:${b.id}`);
await this.audit(login, 'sys-user-del', row.username, { id: Number(b.id) });
return { ok: true };
}
// ==================== 角色管理 ====================
/** GET /api/admin/sys/role/info?id= — 角色详情(含 menuIdList/departmentIdList) */
@Get('/role/info')
async roleInfo(
@Query('id') id: number,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
await this.admin(xAdminToken, xApiToken);
if (!id) throw err(400, 'id 不能为空');
this.prepareDelegation();
return this.baseSysRoleService.info(id);
}
/** POST /api/admin/sys/role/add — 新增角色(可带 menuIdList/departmentIdList,原生链路刷新授权) */
@Post('/role/add')
async roleAdd(
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(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 为内置超管标识,不可使用');
this.prepareDelegation();
const menuIdList = Array.isArray(b?.menuIdList) ? b.menuIdList.map(Number) : [];
const departmentIdList = Array.isArray(b?.departmentIdList) ? b.departmentIdList.map(Number) : [];
const res = await this.baseSysRoleRepo.insert({
userId: String(b?.userId ?? 0),
name,
label: String(b?.label || '').trim(),
remark: String(b?.remark || ''),
// base_sys_role.userId 为非空"创建者ID"列(原生流程由 JWT 上下文注入);
// 控制台身份是 accounts 体系,无法映射 base_sys_user 时记 0(控制台创建)
relevance: !!b?.relevance,
// JSON 冗余列与关系表同源写入(原生 info/授权读取走关系表)
menuIdList,
departmentIdList,
} as any);
const id = Number((res as any).identifiers?.[0]?.id || 0);
// 显式 await 授权关系写入(不依赖原生 modifyAfter 的 fire-and-forget,避免竞态/重复行)
await this.baseSysRoleService.updatePerms(id, menuIdList, departmentIdList);
await this.audit(login, 'sys-role-add', name, { id });
return { ok: true, id };
}
/** POST /api/admin/sys/role/edit — 编辑角色(含授权,自动刷新相关用户权限缓存) */
@Post('/role/edit')
async roleEdit(
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(xAdminToken, xApiToken);
if (!b?.id) throw err(400, 'id 不能为空');
const row = await this.baseSysRoleRepo.findOneBy({ id: Number(b.id) });
if (!row) throw err(404, '角色不存在');
if (Number(b.id) === 1 || row.label === 'admin') throw err(403, '内置超管角色不允许编辑');
if (b?.label && String(b.label).trim().toLowerCase() === 'admin') throw err(400, 'label admin 为内置超管标识,不可使用');
const patch: any = {};
if (b?.name !== undefined) patch.name = String(b.name).trim();
if (b?.label !== undefined) patch.label = String(b.label).trim();
if (b?.remark !== undefined) patch.remark = String(b.remark);
if (b?.relevance !== undefined) patch.relevance = !!b.relevance;
let menuIdList: number[] | null = null;
let departmentIdList: number[] | null = null;
if (Array.isArray(b?.menuIdList)) {
menuIdList = b.menuIdList.map(Number);
patch.menuIdList = menuIdList;
}
if (Array.isArray(b?.departmentIdList)) {
departmentIdList = b.departmentIdList.map(Number);
patch.departmentIdList = departmentIdList;
}
if (Object.keys(patch).length) {
await this.baseSysRoleRepo.update({ id: Number(b.id) }, patch);
}
// 授权关系显式一次写入(不依赖原生 modifyAfter 的 fire-and-forget,避免竞态/重复行)
if (menuIdList !== null || departmentIdList !== null) {
await this.baseSysRoleService.updatePerms(
Number(b.id),
menuIdList ?? [],
departmentIdList ?? []
);
}
await this.audit(login, 'sys-role-edit', row.name, { id: Number(b.id) });
return { ok: true };
}
/** POST /api/admin/sys/role/del — 删除角色(内置超管保护,级联清理授权关系) */
@Post('/role/del')
async roleDel(
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(xAdminToken, xApiToken);
if (!b?.id) throw err(400, 'id 不能为空');
const row = await this.baseSysRoleRepo.findOneBy({ id: Number(b.id) });
if (!row) throw err(404, '角色不存在');
if (Number(b.id) === 1 || row.label === 'admin') throw err(403, '内置超管角色不允许删除');
const userRoles = await this.baseSysUserRoleRepo.findBy({ roleId: Number(b.id) });
await this.baseSysUserRoleRepo.delete({ roleId: Number(b.id) });
await this.baseSysRoleMenuRepo.delete({ roleId: Number(b.id) });
await this.baseSysRoleDeptRepo.delete({ roleId: Number(b.id) });
await this.baseSysRoleRepo.delete({ id: Number(b.id) });
for (const ur of userRoles) {
await this.baseSysPermsService.refreshPerms(ur.userId);
}
await this.audit(login, 'sys-role-del', row.name, { id: Number(b.id) });
return { ok: true };
}
// ==================== 菜单管理 ====================
/** POST /api/admin/sys/menu/add — 新增菜单(type: 0目录 1菜单 2按钮) */
@Post('/menu/add')
async menuAdd(
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(xAdminToken, xApiToken);
const name = String(b?.name || '').trim();
if (!name) throw err(400, 'name 不能为空');
const type = Number(b?.type ?? 0);
if (![0, 1, 2].includes(type)) throw err(400, 'type 仅允许 0/1/2');
if (type !== 2 && !String(b?.router || '').trim()) throw err(400, '该类型必须填写路由地址');
if (b?.parentId) {
const parent = await this.baseSysMenuRepo.findOneBy({ id: Number(b.parentId) });
if (!parent) throw err(404, '上级菜单不存在');
if (Number(parent.type) === 2) throw err(400, '按钮下不能再挂子级');
}
const res = await this.baseSysMenuRepo.insert({
parentId: b?.parentId ? Number(b.parentId) : null,
name,
router: String(b?.router || '').trim(),
perms: String(b?.perms || '').trim(),
icon: String(b?.icon || '').trim(),
type,
orderNum: Number(b?.orderNum || 0) || 0,
} as any);
const id = Number((res as any).identifiers?.[0]?.id || 0);
await this.audit(login, 'sys-menu-add', name, { id });
return { ok: true, id };
}
/** POST /api/admin/sys/menu/edit — 编辑菜单 */
@Post('/menu/edit')
async menuEdit(
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(xAdminToken, xApiToken);
if (!b?.id) throw err(400, 'id 不能为空');
const row = await this.baseSysMenuRepo.findOneBy({ id: Number(b.id) });
if (!row) throw err(404, '菜单不存在');
if (Number(b.id) === Number(b?.parentId)) throw err(400, '上级菜单不能是自己');
if (b?.parentId) {
// 防环:parentId 不能落在本菜单子树内
const all = await this.baseSysMenuRepo.find();
if (isDescendant(all, Number(b.id), Number(b.parentId))) throw err(400, '上级菜单不能是自己的子级');
}
const patch: any = {};
if (b?.parentId !== undefined) patch.parentId = b.parentId ? Number(b.parentId) : null;
if (b?.name !== undefined) patch.name = String(b.name).trim();
if (b?.router !== undefined) patch.router = String(b.router).trim();
if (b?.perms !== undefined) patch.perms = String(b.perms).trim();
if (b?.icon !== undefined) patch.icon = String(b.icon).trim();
if (b?.type !== undefined) {
const type = Number(b.type);
if (![0, 1, 2].includes(type)) throw err(400, 'type 仅允许 0/1/2');
patch.type = type;
}
if (b?.orderNum !== undefined) patch.orderNum = Number(b.orderNum) || 0;
if (Object.keys(patch).length) {
await this.baseSysMenuRepo.update({ id: Number(b.id) }, patch);
}
await this.audit(login, 'sys-menu-edit', row.name, { id: Number(b.id) });
return { ok: true };
}
/** POST /api/admin/sys/menu/del — 删除菜单(有子级时拒绝;级联清理角色授权) */
@Post('/menu/del')
async menuDel(
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(xAdminToken, xApiToken);
if (!b?.id) throw err(400, 'id 不能为空');
const id = Number(b.id);
const row = await this.baseSysMenuRepo.findOneBy({ id });
if (!row) throw err(404, '菜单不存在');
const children = await this.baseSysMenuRepo.count({ where: { parentId: id } as any });
if (children > 0) throw err(400, '存在子级菜单,请先删除子级');
await this.baseSysRoleMenuRepo.delete({ menuId: id });
await this.baseSysMenuRepo.delete({ id });
await this.audit(login, 'sys-menu-del', row.name, { id });
return { ok: true };
}
// ==================== 部门管理 ====================
/** POST /api/admin/sys/dept/add — 新增部门 */
@Post('/dept/add')
async deptAdd(
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(xAdminToken, xApiToken);
const name = String(b?.name || '').trim();
if (!name) throw err(400, 'name 不能为空');
if (b?.parentId) {
const parent = await this.baseSysDeptRepo.findOneBy({ id: Number(b.parentId) });
if (!parent) throw err(404, '上级部门不存在');
}
const res = await this.baseSysDeptRepo.insert({
parentId: b?.parentId ? Number(b.parentId) : null,
name,
orderNum: Number(b?.orderNum || 0) || 0,
} as any);
const id = Number((res as any).identifiers?.[0]?.id || 0);
await this.audit(login, 'sys-dept-add', name, { id });
return { ok: true, id };
}
/** POST /api/admin/sys/dept/edit — 编辑部门 */
@Post('/dept/edit')
async deptEdit(
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(xAdminToken, xApiToken);
if (!b?.id) throw err(400, 'id 不能为空');
const row = await this.baseSysDeptRepo.findOneBy({ id: Number(b.id) });
if (!row) throw err(404, '部门不存在');
if (Number(b.id) === Number(b?.parentId)) throw err(400, '上级部门不能是自己');
if (b?.parentId) {
const all = await this.baseSysDeptRepo.find();
if (isDescendant(all, Number(b.id), Number(b.parentId))) throw err(400, '上级部门不能是自己的子级');
}
const patch: any = {};
if (b?.parentId !== undefined) patch.parentId = b.parentId ? Number(b.parentId) : null;
if (b?.name !== undefined) patch.name = String(b.name).trim();
if (b?.orderNum !== undefined) patch.orderNum = Number(b.orderNum) || 0;
if (Object.keys(patch).length) {
await this.baseSysDeptRepo.update({ id: Number(b.id) }, patch);
}
await this.audit(login, 'sys-dept-edit', row.name, { id: Number(b.id) });
return { ok: true };
}
/** POST /api/admin/sys/dept/del — 删除部门(有子级或在用用户时拒绝) */
@Post('/dept/del')
async deptDel(
@Body() b: any,
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
const login = await this.admin(xAdminToken, xApiToken);
if (!b?.id) throw err(400, 'id 不能为空');
const id = Number(b.id);
const row = await this.baseSysDeptRepo.findOneBy({ id });
if (!row) throw err(404, '部门不存在');
const children = await this.baseSysDeptRepo.count({ where: { parentId: id } as any });
if (children > 0) throw err(400, '存在子部门,请先删除子部门');
const userCount = await this.baseSysUserRepo.count({ where: { departmentId: id } as any });
if (userCount > 0) throw err(400, `该部门仍有 ${userCount} 个用户,请先转移用户`);
await this.baseSysRoleDeptRepo.delete({ departmentId: id });
await this.baseSysDeptRepo.delete({ id });
await this.audit(login, 'sys-dept-del', row.name, { id });
return { ok: true };
}
}
/** 业务错误(ApiError 语义:携带 HTTP 状态码) */
function err(status: number, message: string): Error & { status: number } {
const e: any = new Error(message);
e.status = status;
return e;
}
/** 以 parentId 构建树(通用) */
function buildTree(rows: any[]): any[] {
const map = new Map<number, any>();
rows.forEach((r) => map.set(Number(r.id), { ...r, children: [] }));
const roots: any[] = [];
map.forEach((node) => {
const pid = node.parentId ? Number(node.parentId) : 0;
if (map.has(pid)) map.get(pid).children.push(node);
else roots.push(node);
});
return roots;
}
/** 判断 targetId 是否在 rootId 的子树内(防环) */
function isDescendant(all: any[], rootId: number, targetId: number): boolean {
const childrenMap = new Map<number, number[]>();
for (const r of all) {
const pid = r.parentId ? Number(r.parentId) : 0;
if (!childrenMap.has(pid)) childrenMap.set(pid, []);
childrenMap.get(pid)!.push(Number(r.id));
}
const queue = [...(childrenMap.get(rootId) || [])];
const seen = new Set<number>();
while (queue.length) {
const id = queue.shift()!;
if (id === targetId) return true;
if (seen.has(id)) continue;
seen.add(id);
queue.push(...(childrenMap.get(id) || []));
}
return false;
}
@@ -0,0 +1,100 @@
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 { ClientCredEntity } from '../../entity/account';
import { AccountEntity } from '../../entity/account';
import { CenterAuthService, ApiError } from '../../service/auth';
import { rsaEncrypt } from '../../service/crypto';
/**
* 执行机敏感凭证(对齐旧 FastAPI apis/config_push.py):
* - POST /api/admin/creds/register:登记/更新 RSA 公钥(管理员任意账号 / 云令牌本人)
* - GET /api/admin/creds:仅管理员可拉,服务端用账号公钥 OAEP 加密每个明文值下发
*/
@Provide()
@CoolController('/api/admin')
export class ApiCredsController extends BaseController {
@Inject()
centerAuthService: CenterAuthService;
@InjectEntityModel(ClientCredEntity)
clientCredRepo: Repository<ClientCredEntity>;
@InjectEntityModel(AccountEntity)
accountRepo: Repository<AccountEntity>;
/** POST /api/admin/creds/register */
@Post('/creds/register')
async credsRegister(
@Body() b: any,
@Headers('Authorization') authorization: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
// 鉴权双轨:管理员可为任意账号登记;云令牌账号只能登记本人
let adminOk = false;
try {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
adminOk = true;
} catch (e) {
adminOk = false;
}
if (!adminOk) {
const self = await this.centerAuthService.cloudAccount(authorization);
if (!self || self !== (b?.account || '').trim()) {
throw new ApiError(401, '登录态无效或已过期,请重新登录');
}
}
const account = (b?.account || '').trim();
const pem = (b?.pubkey_pem || '').trim();
if (!account || !pem) throw new ApiError(400, 'account 与 pubkey_pem 不能为空');
const existing = await this.clientCredRepo.findOneBy({ account });
const creds = existing?.creds || '{}';
await this.clientCredRepo.manager.query(
`INSERT INTO client_creds(account, pubkey_pem, creds, updated_at) VALUES (?, ?, ?, NOW())
ON DUPLICATE KEY UPDATE pubkey_pem = VALUES(pubkey_pem), creds = VALUES(creds), updated_at = VALUES(updated_at)`,
[account, pem, creds]
);
return { ok: true, account };
}
/** GET /api/admin/creds — 下发敏感凭证(仅管理员) */
@Get('/creds')
async credsFetch(
@Headers('Authorization') authorization: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = '',
@Headers('X-Admin-User') xAdminUser: string = ''
) {
let account = '';
try {
account = await this.centerAuthService.identity(authorization, xAdminToken, xApiToken, xAdminUser);
} catch (e) {
account = '';
}
if (!account) throw new ApiError(401, '登录态无效或已过期,请重新登录');
const admin = await this.accountRepo
.createQueryBuilder('a')
.select('a.isAdmin', 'isAdmin')
.where('a.account = :account', { account })
.getRawOne();
if (!admin || !Number(admin.isAdmin)) throw new ApiError(403, '仅管理员可拉取敏感凭证');
const row = await this.clientCredRepo.findOneBy({ account });
if (!row || !row.pubkeyPem) return { account, creds: {} };
let encrypted: Record<string, string> = {};
try {
const source = JSON.parse(row.creds || '{}');
for (const [k, v] of Object.entries(source)) {
if (v !== null && v !== undefined) encrypted[k] = rsaEncrypt(row.pubkeyPem, String(v));
}
} catch (e: any) {
throw new ApiError(500, `凭证加密失败: ${e.message || e}`);
}
await this.clientCredRepo.manager.query(
'UPDATE client_creds SET updated_at = NOW() WHERE account = ?',
[account]
);
return { account, creds: encrypted };
}
}
@@ -0,0 +1,69 @@
import { CoolController, BaseController } from '@cool-midway/core';
import { Body, Headers, Inject, Post, Provide } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { RuntimeReportEntity, DeviceEntity } from '../../entity/runtime';
import { CenterAuthService, ApiError } from '../../service/auth';
/**
* 运行上报 + 设备上报(对齐旧 FastAPI apis/plugins.py /api/runtime/report、/api/device/report)
* 注意:现网 devices 表无 client_version 列(以现网 schema 为准),上报仅 upsert 现有列
*/
@Provide()
@CoolController('/api')
export class ApiDeviceController extends BaseController {
@Inject()
centerAuthService: CenterAuthService;
@InjectEntityModel(RuntimeReportEntity)
runtimeRepo: Repository<RuntimeReportEntity>;
@InjectEntityModel(DeviceEntity)
deviceRepo: Repository<DeviceEntity>;
/** POST /api/runtime/report */
@Post('/runtime/report')
async runtimeReport(@Body() b: any, @Headers('X-API-Token') xApiToken: string = '') {
this.centerAuthService.checkApiToken(xApiToken);
await this.runtimeRepo.insert({
account: b?.account || '',
deviceId: b?.device_id || '',
pluginId: b?.plugin_id || '',
version: b?.version || '',
status: b?.status || '',
msg: b?.msg || '',
durationSec: Number(b?.duration_sec || 0),
at: new Date(),
});
return { ok: true };
}
/** POST /api/device/report — 执行机心跳/环境上报(按 device_id 幂等 upsert) */
@Post('/device/report')
async deviceReport(@Body() b: any, @Headers('X-API-Token') xApiToken: string = '') {
this.centerAuthService.checkApiToken(xApiToken);
const deviceId = (b?.device_id || '').trim();
if (!deviceId) throw new ApiError(400, 'device_id 不能为空');
await this.deviceRepo.manager.query(
`INSERT INTO devices(device_id, account, hostname, os, ip, chrome_installed, chrome_version, chrome_ok, last_seen, status)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?)
ON DUPLICATE KEY UPDATE
account = VALUES(account), hostname = VALUES(hostname), os = VALUES(os),
ip = VALUES(ip), chrome_installed = VALUES(chrome_installed),
chrome_version = VALUES(chrome_version), chrome_ok = VALUES(chrome_ok),
last_seen = VALUES(last_seen), status = VALUES(status)`,
[
deviceId,
(b?.account || '').trim(),
(b?.hostname || '').trim(),
(b?.os || '').trim(),
(b?.ip || '').trim(),
Number(!!b?.chrome_installed),
(b?.chrome_version || '').trim(),
Number(!!b?.chrome_ok),
Number(!!b?.status),
]
);
return { ok: true, device_id: deviceId };
}
}
@@ -0,0 +1,95 @@
import { CoolController, BaseController } from '@cool-midway/core';
import { Body, Inject, Post, 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 { hashPassword } from '../../service/crypto';
import { dingtalkUserinfo } from '../../service/dingtalk';
import { CenterNotifyService } from '../../service/notify';
import { dingtalkDefaultPassword } from '../../comm/conf';
// 壳子直连入口:错误渲染走 api-error 中间件({"detail"} 契约)
/**
* 员工端扫码登录 /auth/exchange(对齐旧 FastAPI apis/auth.py v3 最简方案,壳本机直连 code):
* 壳把浏览器带回的钉钉 code POST 到此,用 AppSecret 换身份 → 找建账号
* (不存在则自动建号:空壳+默认密码+强制改密,并推送钉钉通知)→ 签发云端会话 token
* (供壳调 /api/plugins 鉴权)。注意:路径不在 /api/ 下,属壳子直连的公开入口。
*/
@Provide()
@CoolController('/auth')
export class AuthExchangeController extends BaseController {
@Inject()
centerAuthService: CenterAuthService;
@Inject()
centerNotifyService: CenterNotifyService;
@InjectEntityModel(AccountEntity)
accountRepo: Repository<AccountEntity>;
/** POST /auth/exchange — 壳 → 云端:钉钉授权码换员工工号 + 云端会话 token(找建账号) */
@Post('/exchange')
async exchange(@Body() d: any) {
const code = String(d?.code || '').trim();
if (!code) throw new ApiError(400, '缺少 code');
const appKey = (process.env.DINGTALK_APP_KEY || '').trim();
const appSecret = (process.env.DINGTALK_APP_SECRET || '').trim();
if (!appKey || !appSecret) {
throw new ApiError(503, '未配置钉钉开放平台应用(DINGTALK_APP_KEY / DINGTALK_APP_SECRET)');
}
let info: { account: string; nickname: string; unionid: string };
try {
info = await dingtalkUserinfo(code);
} catch (e: any) {
// 已带状态码的(401/503)原样透出;网络类错误包装为 502
if (e?.status) throw new ApiError(e.status, e.message || '钉钉接口访问失败');
throw new ApiError(502, e?.message || '钉钉接口访问失败');
}
const account = (info.account || '').trim();
if (!account) throw new ApiError(401, '扫码未解析到有效账号,请重新扫码');
const nickname = (info.nickname || '').trim();
const unionid = (info.unionid || '').trim();
// 找建账号(与 /api/admin/dingtalk/auth 同语义):已存在则同步昵称;不存在则自动建号并通知
let created = false;
let mustChange = false;
let isAdmin = false;
const existing = await this.accountRepo.findOneBy({ account });
if (existing) {
if (!Number(existing.status)) throw new ApiError(403, '账号已停用,请联系管理员');
if (nickname && nickname !== (existing.nickname || '')) {
await this.accountRepo.update({ account }, { nickname });
}
mustChange = !!Number(existing.mustChangePwd);
isAdmin = !!Number(existing.isAdmin);
} else {
// 自动建号(空壳):初始密码取默认值,强制首次改密
const pwd = dingtalkDefaultPassword();
const { hash, salt } = hashPassword(pwd);
await this.accountRepo.insert({
account,
passwordHash: hash,
salt,
isAdmin: 0,
dept: '',
nickname,
dingtalkUid: unionid,
mustChangePwd: 1,
} as any);
created = true;
mustChange = true;
isAdmin = false;
this.centerNotifyService.notifyAccountCreated(account, nickname, pwd, unionid, '钉钉扫码');
}
const token = await this.centerAuthService.issueCloudToken(account, nickname);
return {
token,
account,
nickname,
exists: !created,
created,
must_change_pwd: mustChange,
is_admin: isAdmin,
};
}
}
@@ -0,0 +1,80 @@
import { CoolController, BaseController } from '@cool-midway/core';
import { Body, Headers, Inject, Post, Provide } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { FileserverStatusEntity } from '../../entity/resource';
import { CenterAuthService, ApiError } from '../../service/auth';
import { fmtNow } from '../../comm/conf';
// 心跳 upsert 语义:恢复上线翻转 status=1 并清除 offline_notified(对齐 fileserver_status.py)
/**
* 内网文件服务器状态 API(对齐旧 FastAPI apis/fileserver_status.py):
* - POST /api/fileserver/heartbeat:文件服务器(8802)周期心跳上报,upsert 状态快照;
* 离线中收到心跳则恢复在线并清除告警标记(恢复时不再推送)。
* 心跳上报仅需 X-API-Token(底座凭证)。
*/
@Provide()
@CoolController('/api/fileserver')
export class ApiFileserverController extends BaseController {
@Inject()
centerAuthService: CenterAuthService;
@InjectEntityModel(FileserverStatusEntity)
fileserverRepo: Repository<FileserverStatusEntity>;
/** POST /api/fileserver/heartbeat — 接收文件服务器心跳 */
@Post('/heartbeat')
async heartbeat(
@Body() b: any,
@Headers('X-API-Token') xApiToken: string = ''
) {
this.centerAuthService.checkApiToken(xApiToken);
const host = String(b?.host || '').trim();
if (!host) throw new ApiError(400, 'host 不能为空');
const now = new Date();
const nowStr = fmtNow(now);
const payload = {
baseUrl: String(b?.base_url || '').trim(),
hostname: String(b?.hostname || '').trim(),
ip: String(b?.ip || '').trim(),
port: Number(b?.port || 0) || 0,
fileCount: Number(b?.file_count || 0) || 0,
totalSize: Number(b?.total_size || 0) || 0,
version: String(b?.version || '').trim(),
uptimeSec: Number(b?.uptime_sec || 0) || 0,
};
const m = this.fileserverRepo.manager;
const row: any = (
await m.query('SELECT status, offline_notified FROM fileserver_status WHERE host = ?', [host])
)[0];
if (row) {
// 离线期间恢复上线:标记在线、清除离线告警标记(恢复时不再推送)
const wasOffline = !Number(row.status) || !!Number(row.offline_notified);
if (wasOffline) {
await m.query(
'UPDATE fileserver_status SET base_url=?, hostname=?, ip=?, port=?, file_count=?, ' +
'total_size=?, version=?, uptime_sec=?, last_seen=?, status=1, offline_notified=0, ' +
'last_status_change=? WHERE host=?',
[payload.baseUrl, payload.hostname, payload.ip, payload.port, payload.fileCount,
payload.totalSize, payload.version, payload.uptimeSec, nowStr, nowStr, host]
);
} else {
await m.query(
'UPDATE fileserver_status SET base_url=?, hostname=?, ip=?, port=?, file_count=?, ' +
'total_size=?, version=?, uptime_sec=?, last_seen=?, status=1, offline_notified=0 WHERE host=?',
[payload.baseUrl, payload.hostname, payload.ip, payload.port, payload.fileCount,
payload.totalSize, payload.version, payload.uptimeSec, nowStr, host]
);
}
} else {
await m.query(
'INSERT INTO fileserver_status(host, base_url, hostname, ip, port, file_count, ' +
'total_size, version, uptime_sec, last_seen, status, offline_notified, created_at, last_status_change) ' +
'VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 0, ?, ?)',
[host, payload.baseUrl, payload.hostname, payload.ip, payload.port, payload.fileCount,
payload.totalSize, payload.version, payload.uptimeSec, nowStr, nowStr, nowStr]
);
}
return { ok: true, host, last_seen: nowStr };
}
}
@@ -0,0 +1,107 @@
import { CoolController, BaseController } from '@cool-midway/core';
import { Get, Headers, Inject, Provide, Query } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { PluginEntity, AccountPluginEntity } from '../../entity/plugin';
import { CenterAuthService, ApiError } from '../../service/auth';
import { pubkeyPem, signBlob } from '../../service/crypto';
import { LICENSE_TTL_DAYS, fmtNow } from '../../comm/conf';
/**
* 客户端票据接口(对齐旧 FastAPI apis/plugins.py /api/me/*)
* - /api/me/pubkey:下发中心机公钥(Ed25519 PEM)
* - /api/me/license:签发离线授权票据(插件授权快照,Ed25519 签名)
* - /api/me/control-list:签发管控清单(revoked/disabled/forcedUpdates,Ed25519 签名)
*/
@Provide()
@CoolController('/api')
export class ApiMeController extends BaseController {
@Inject()
centerAuthService: CenterAuthService;
@InjectEntityModel(PluginEntity)
pluginRepo: Repository<PluginEntity>;
@InjectEntityModel(AccountPluginEntity)
accountPluginRepo: Repository<AccountPluginEntity>;
private expiresAtEpoch(): number {
return Math.floor(Date.now() / 1000) + LICENSE_TTL_DAYS * 24 * 3600;
}
/** GET /api/me/pubkey */
@Get('/me/pubkey')
async pubkey() {
return { pub: pubkeyPem(), algo: 'ed25519' };
}
/** GET /api/me/license?account=&device= */
@Get('/me/license')
async license(
@Query('account') account: string = '',
@Query('device') device: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
this.centerAuthService.checkApiToken(xApiToken);
if (!(account || '').trim()) throw new ApiError(400, 'account 不能为空');
if (await this.centerAuthService.accountDisabled(account.trim())) {
throw new ApiError(403, '账号已停用,无法获取授权');
}
const rows = await this.accountPluginRepo
.createQueryBuilder('g')
.innerJoin(PluginEntity, 'p', 'p.id = g.pluginId')
.select([
'g.pluginId AS pluginId',
'g.canDownload AS canDownload',
'g.canRun AS canRun',
'p.name AS name',
'p.status AS status',
'p.latestVersion AS latestVersion',
])
.where('g.account = :account', { account: account.trim() })
.getRawMany();
const plugins = rows.map(r => ({
pluginId: r.pluginId,
name: r.name,
canDownload: !!Number(r.canDownload),
canRun: !!Number(r.canRun),
status: r.status,
latestVersion: r.latestVersion,
}));
const issuedAt = fmtNow();
const expiresAt = this.expiresAtEpoch();
const blob = signBlob({
userId: account.trim(),
deviceId: device || '',
issuedAt,
expiresAt,
plugins,
});
return { ticket: blob, plugins, issuedAt, expiresAt };
}
/** GET /api/me/control-list */
@Get('/me/control-list')
async controlList(@Headers('X-API-Token') xApiToken: string = '') {
this.centerAuthService.checkApiToken(xApiToken);
const revoked: string[] = [];
const disabled: string[] = [];
const forced: any[] = [];
const rows = await this.pluginRepo.find();
for (const r of rows) {
if (r.status === 'revoked') revoked.push(r.id);
else if (r.status === 'disabled') disabled.push(r.id);
if (r.forceMinVersion && r.forceDeadline) {
forced.push({ pluginId: r.id, minVersion: r.forceMinVersion, deadline: r.forceDeadline });
}
}
const payload = {
revokedPlugins: revoked,
disabledPlugins: disabled,
forcedUpdates: forced,
updatedAt: fmtNow(),
expiresAt: this.expiresAtEpoch(),
};
return { ticket: signBlob(payload), control: payload };
}
}
@@ -0,0 +1,231 @@
import { CoolController, BaseController } from '@cool-midway/core';
import { Body, Get, Headers, Inject, Param, Post, Provide, Query } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import * as fs from 'fs';
import * as path from 'path';
import { FileSourceEntity } from '../../entity/resource';
import { NotificationEntity } from '../../entity/runtime';
import { ScheduleBackupEntity } from '../../entity/resource';
import { CenterAuthService, ApiError } from '../../service/auth';
import { AVATAR_DIR } from '../../comm/conf';
/**
* 客户端杂项接口(对齐旧 FastAPI):
* - GET /api/file-sources/{category}:内网大文件源最新启用直链
* - GET /api/notifications:通知拉取(HTTP 兜底)
* - GET/POST /api/schedules/backup:壳子定时任务配置备份(自助,身份=账号)
* - GET /api/dingtalk/login-url:钉钉扫码授权 URL(执行机代理调用)
*/
@Provide()
@CoolController('/api')
export class ApiMiscController extends BaseController {
@Inject()
centerAuthService: CenterAuthService;
@Inject()
ctx: any;
@InjectEntityModel(FileSourceEntity)
fileSourceRepo: Repository<FileSourceEntity>;
@InjectEntityModel(NotificationEntity)
notificationRepo: Repository<NotificationEntity>;
@InjectEntityModel(ScheduleBackupEntity)
scheduleBackupRepo: Repository<ScheduleBackupEntity>;
/** GET /api/file-sources/{category} — 客户端取某分类最新启用的一条 */
@Get('/file-sources/:category')
async fileSourceLatest(
@Param('category') category: string,
@Headers('X-API-Token') xApiToken: string = ''
) {
this.centerAuthService.checkApiToken(xApiToken);
const rows = await this.fileSourceRepo
.createQueryBuilder('f')
.select(['f.id', 'f.category', 'f.version', 'f.filename', 'f.url', 'f.sha256', 'f.notes'])
.where('f.category = :c', { c: (category || '').trim() })
.andWhere('f.enabled = 1')
.getMany();
if (!rows.length) return { available: false, category: (category || '').trim() };
// 版本号按数值语义取最新("1.10" > "1.9")
const r = rows.reduce((a, b) => (versionKey(b.version) > versionKey(a.version) ? b : a));
return {
available: true,
category: r.category,
version: r.version,
filename: r.filename,
url: r.url,
sha256: r.sha256,
notes: r.notes || '',
};
}
/** GET /api/notifications — 客户端拉取通知(云令牌优先,兜底 account+X-API-Token) */
@Get('/notifications')
async notifications(
@Query('account') account: string = '',
@Headers('X-API-Token') xApiToken: string = '',
@Headers('Authorization') authorization: string = ''
) {
let acct = await this.centerAuthService.cloudAccount(authorization);
if (!acct) {
this.centerAuthService.checkApiToken(xApiToken);
acct = (account || '').trim();
}
if (!acct) throw new ApiError(400, '缺少有效会话或 account');
const rows = await this.notificationRepo
.createQueryBuilder('n')
.select(['n.id', 'n.title', 'n.content', 'n.level', 'n.target', 'n.account', 'n.createdAt', 'n.expiresAt'])
.where('n.active = 1')
.andWhere('(n.target = :all OR (n.target = :acct AND n.account = :acct))', { all: 'all', acct })
.andWhere('(n.expiresAt IS NULL OR n.expiresAt > NOW())')
.orderBy('n.createdAt', 'DESC')
.limit(50)
.getMany();
return {
notifications: rows.map(r => ({
id: r.id,
title: r.title,
content: r.content,
level: r.level,
target: r.target,
account: r.account,
created_at: fmtDt(r.createdAt),
expires_at: r.expiresAt ? fmtDt(r.expiresAt) : null,
})),
};
}
/** POST /api/schedules/backup — 覆盖保存某账号定时任务配置 */
@Post('/schedules/backup')
async schedBackupSave(
@Body() b: any,
@Headers('Authorization') authorization: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = '',
@Headers('X-Admin-User') xAdminUser: string = ''
) {
const account = await this.requireIdentity(authorization, xAdminToken, xApiToken, xAdminUser);
const payload = b?.data && typeof b.data === 'object' ? b.data : {};
if (!Array.isArray(payload.schedules)) throw new ApiError(400, 'data.schedules 必须为数组');
await this.scheduleBackupRepo.manager.query(
`INSERT INTO schedule_backups(account, data, updated_at) VALUES (?, ?, NOW())
ON DUPLICATE KEY UPDATE data = VALUES(data), updated_at = VALUES(updated_at)`,
[account, JSON.stringify(payload)]
);
return { ok: true, account };
}
/** GET /api/schedules/backup — 读取某账号定时任务备份 */
@Get('/schedules/backup')
async schedBackupLoad(
@Headers('Authorization') authorization: string = '',
@Headers('X-Admin-Token') xAdminToken: string = '',
@Headers('X-API-Token') xApiToken: string = '',
@Headers('X-Admin-User') xAdminUser: string = ''
) {
const account = await this.requireIdentity(authorization, xAdminToken, xApiToken, xAdminUser);
const row = await this.scheduleBackupRepo.findOneBy({ account });
if (!row) return { data: { schedules: [] } };
try {
const data = JSON.parse(row.data);
if (data && typeof data === 'object' && Array.isArray(data.schedules)) return { data };
} catch (e) {
/* fallthrough */
}
return { data: { schedules: [] } };
}
/** GET /api/avatar/{account} — 读取账号头像(前端 img 直接引用) */
@Get('/avatar/:account')
async avatar(@Param('account') account: string) {
const row: any = await this.fileSourceRepo.manager.query(
'SELECT avatar FROM accounts WHERE account = ?', [account]);
if (!row.length || !row[0].avatar) throw new ApiError(404, '未设置头像');
const f = path.join(AVATAR_DIR, row[0].avatar);
if (!fs.existsSync(f)) throw new ApiError(404, '头像文件缺失');
this.ctx.type = path.extname(f);
this.ctx.body = fs.createReadStream(f);
}
/** GET /api/dingtalk/login-url — 构造钉钉扫码授权 URL */
@Get('/dingtalk/login-url')
async dingtalkLoginUrl(
@Query('back') back: string,
@Query('state') state: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
this.centerAuthService.checkApiToken(xApiToken);
const appKey = process.env.DINGTALK_APP_KEY || '';
const appSecret = process.env.DINGTALK_APP_SECRET || '';
if (!appKey || !appSecret) {
throw new ApiError(503, '控制面未配置钉钉开放平台应用(DINGTALK_APP_KEY / DINGTALK_APP_SECRET)');
}
if (!safeBackUrl(back)) throw new ApiError(400, '回跳地址非法(仅允许回环/内网/控制面域名)');
const qs = new URLSearchParams({
redirect_uri: back,
response_type: 'code',
client_id: appKey,
scope: 'openid',
prompt: 'consent',
state: state || back,
});
return { url: `https://login.dingtalk.com/oauth2/challenge.htm?${qs.toString()}` };
}
/** 统一身份解析(core.auth._identity 语义),无效抛 401 */
private async requireIdentity(
authorization: string,
xAdminToken: string,
xApiToken: string,
xAdminUser: string
): Promise<string> {
try {
return await this.centerAuthService.identity(authorization, xAdminToken, xApiToken, xAdminUser);
} catch (e) {
throw new ApiError(401, '登录态无效或已过期,请重新登录');
}
}
}
/** 版本号数值语义比较(对齐 pkgutil._version_key:"1.10" > "1.9") */
function versionKey(v: string): number[] {
return String(v || '')
.split('.')
.map(s => parseInt(s, 10) || 0);
}
/** 时间格式化为 'YYYY-MM-DD HH:mm:ss'(null 返回 null) */
function fmtDt(d: Date | null): string | null {
if (!d) return null;
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())}`;
}
/** 回跳地址白名单(对齐 dingtalk.py _safe_back_url):http(s) + 回环/内网私有段/控制面域名 */
function safeBackUrl(url: string): boolean {
if (!url || !(url.startsWith('http://') || url.startsWith('https://'))) return false;
try {
const host = new URL(url).hostname.toLowerCase();
if (host === 'localhost' || host === '127.0.0.1' || host === '::1') return true;
const cb = (process.env.DINGTALK_CALLBACK || '');
if (cb) {
const cbHost = new URL(cb).hostname.toLowerCase();
if (host === cbHost) return true;
}
// IPv4 私有网段
const m = host.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
if (m) {
const a = Number(m[1]), b = Number(m[2]);
if (a === 10) return true;
if (a === 127) return true;
if (a === 172 && b >= 16 && b <= 31) return true;
if (a === 192 && b === 168) return true;
}
return false;
} catch (e) {
return false;
}
}
@@ -0,0 +1,29 @@
import { CoolController, BaseController } from '@cool-midway/core';
import { Get, Inject, Provide } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { CenterAuthService, ApiError } from '../../service/auth';
/**
* 契约冒烟测试控制器(验证 /api/* 自定义路由 + ApiErrorMiddleware 的 {detail} 渲染)
*/
@Provide()
@CoolController('/api')
export class ApiPingController extends BaseController {
@Inject()
ctx: Context;
@Inject()
centerAuthService: CenterAuthService;
/** GET /api/ping */
@Get('/ping')
async ping() {
return { ok: true, time: Date.now() };
}
/** GET /api/ping/error → 验证错误渲染为 {"detail": "..."} + 状态码 */
@Get('/ping/error')
async error() {
throw new ApiError(401, '测试错误:登录态无效');
}
}
@@ -0,0 +1,85 @@
import { CoolController, BaseController } from '@cool-midway/core';
import { Get, Headers, Inject, Provide, Query } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { PluginEntity, AccountPluginEntity, AccountPlatformEntity } from '../../entity/plugin';
import { CenterAuthService, ApiError } from '../../service/auth';
/**
* 客户端插件清单接口(对齐旧 FastAPI apis/plugins.py /api/plugins、/api/platforms/allowed)
* 身份:优先 Authorization: Bearer <cloud_token>,兜底 account + X-API-Token
*/
@Provide()
@CoolController('/api')
export class ApiPluginsController extends BaseController {
@Inject()
centerAuthService: CenterAuthService;
@InjectEntityModel(PluginEntity)
pluginRepo: Repository<PluginEntity>;
@InjectEntityModel(AccountPluginEntity)
accountPluginRepo: Repository<AccountPluginEntity>;
@InjectEntityModel(AccountPlatformEntity)
accountPlatformRepo: Repository<AccountPlatformEntity>;
/** 解析账号身份;无有效身份抛 400 */
private async resolveAcct(
account: string,
xApiToken: string,
authorization: string
): Promise<string> {
let acct = await this.centerAuthService.cloudAccount(authorization);
if (!acct) {
this.centerAuthService.checkApiToken(xApiToken);
acct = (account || '').trim();
}
if (!acct) throw new ApiError(400, '缺少有效会话或 account');
return acct;
}
/** GET /api/plugins — 按账号返回可用插件清单(权限隔离) */
@Get('/plugins')
async plugins(
@Query('account') account: string = '',
@Headers('X-API-Token') xApiToken: string = '',
@Headers('Authorization') authorization: string = ''
) {
const acct = await this.resolveAcct(account, xApiToken, authorization);
if (await this.centerAuthService.accountDisabled(acct)) {
return { account: acct, plugins: [] };
}
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'])
.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 })),
};
}
/** GET /api/platforms/allowed — 按账号返回可登录平台白名单 */
@Get('/platforms/allowed')
async platformsAllowed(
@Query('account') account: string = '',
@Headers('X-API-Token') xApiToken: string = '',
@Headers('Authorization') authorization: string = ''
) {
const acct = await this.resolveAcct(account, xApiToken, authorization);
if (await this.centerAuthService.accountDisabled(acct)) {
return { account: acct, allowed: [] };
}
const rows = await this.accountPlatformRepo
.createQueryBuilder('ap')
.select('ap.platformId', 'platformId')
.where('ap.account = :account', { account: acct })
.orderBy('ap.platformId', 'ASC')
.getRawMany();
return { account: acct, allowed: rows.map(r => r.platformId) };
}
}
@@ -0,0 +1,104 @@
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 * as fs from 'fs';
import * as path from 'path';
import { FileSourceEntity } from '../../entity/resource';
import { CenterAuthService, ApiError } from '../../service/auth';
import { SHELL_DIR } from '../../comm/conf';
/**
* 壳子自动更新(对齐旧 FastAPI apis/plugins.py /api/shell/version、/api/shell/pkg)
* version.json 约定:{"version","filename","sha256","notes"}
*/
@Provide()
@CoolController('/api')
export class ApiShellController extends BaseController {
@Inject()
ctx: any;
@Inject()
centerAuthService: CenterAuthService;
@InjectEntityModel(FileSourceEntity)
fileSourceRepo: Repository<FileSourceEntity>;
/** 读 shell/version.json(utf-8-sig 兼容 BOM),缺失/非法返回 {} */
private shellMeta(): any {
const vf = path.join(SHELL_DIR, 'version.json');
if (!fs.existsSync(vf)) return {};
try {
const d = JSON.parse(fs.readFileSync(vf, 'utf-8').replace(/^\uFEFF/, ''));
return d && typeof d === 'object' ? d : {};
} catch (e) {
return {};
}
}
/** 优先取 file_sources category='shell' 的最新启用记录;无返回 {} */
private async shellSourceUrl(): Promise<any> {
try {
const rows = await this.fileSourceRepo
.createQueryBuilder('f')
.select(['f.version', 'f.filename', 'f.url', 'f.sha256', 'f.notes'])
.where('f.category = :c', { c: 'shell' })
.andWhere('f.enabled = 1')
.orderBy('f.id', 'DESC')
.getMany();
const row = rows[0];
if (!row || !row.url) return {};
return {
version: row.version || '',
filename: row.filename || '',
url: row.url,
sha256: row.sha256 || '',
notes: row.notes || '',
};
} catch (e) {
return {};
}
}
/** GET /api/shell/version */
@Get('/shell/version')
async shellVersion(@Headers('X-API-Token') xApiToken: string = '') {
this.centerAuthService.checkApiToken(xApiToken);
const source = await this.shellSourceUrl();
const meta = this.shellMeta();
if (source.url) {
return {
available: true,
version: source.version || meta.version || '',
filename: source.filename || meta.filename || '',
url: source.url,
sha256: source.sha256 || meta.sha256 || '',
notes: source.notes || meta.notes || '',
};
}
if (!meta.version) return { available: false, version: '' };
return {
available: true,
version: String(meta.version),
filename: meta.filename || '',
sha256: meta.sha256 || '',
notes: meta.notes || '',
url: '',
};
}
/** GET /api/shell/pkg — 下载壳子安装包(setup.exe) */
@Get('/shell/pkg')
async shellPkg(@Headers('X-API-Token') xApiToken: string = '') {
this.centerAuthService.checkApiToken(xApiToken);
const meta = this.shellMeta();
const fn = meta.filename || '';
const pkgPath = fn ? path.join(SHELL_DIR, fn) : '';
if (!pkgPath || !fs.existsSync(pkgPath)) {
throw new ApiError(404, '壳子安装包缺失,请联系管理员');
}
this.ctx.attachment(path.basename(pkgPath));
this.ctx.set('Content-Type', 'application/octet-stream');
this.ctx.body = fs.createReadStream(pkgPath);
}
}
@@ -0,0 +1,106 @@
import { CoolController, BaseController } from '@cool-midway/core';
import { Get, Headers, Inject, Param, Provide, Query } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import * as fs from 'fs';
import * as path from 'path';
import { randomBytes } from 'node:crypto';
import { AccountPluginEntity } from '../../entity/plugin';
import { PluginVersionEntity } from '../../entity/plugin';
import { DownloadTicketEntity } from '../../entity/account';
import { AuditLogEntity } from '../../entity/runtime';
import { CenterAuthService, ApiError } from '../../service/auth';
import { PKG_DIR, fmtNow } from '../../comm/conf';
/**
* 一次性下载票据(对齐旧 FastAPI apis/plugins.py):
* - GET /api/plugins/{plugin_id}/versions/{version}/download-ticket:鉴权(can_download)后签发
* - GET /api/download/{ticket}:兑换即作废 + 写审计 + 流式返回包文件
*/
@Provide()
@CoolController('/api')
export class ApiTicketController extends BaseController {
@Inject()
ctx: any;
@Inject()
centerAuthService: CenterAuthService;
@InjectEntityModel(AccountPluginEntity)
accountPluginRepo: Repository<AccountPluginEntity>;
@InjectEntityModel(PluginVersionEntity)
pluginVersionRepo: Repository<PluginVersionEntity>;
@InjectEntityModel(DownloadTicketEntity)
downloadTicketRepo: Repository<DownloadTicketEntity>;
@InjectEntityModel(AuditLogEntity)
auditRepo: Repository<AuditLogEntity>;
/** GET /api/plugins/{plugin_id}/versions/{version}/download-ticket */
@Get('/plugins/:pluginId/versions/:version/download-ticket')
async downloadTicket(
@Param('pluginId') pluginId: string,
@Param('version') version: string,
@Query('account') account: string = '',
@Headers('X-API-Token') xApiToken: string = ''
) {
this.centerAuthService.checkApiToken(xApiToken);
if (!(account || '').trim()) throw new ApiError(400, 'account 不能为空');
const grant = await this.accountPluginRepo.findOneBy({
account: account.trim(),
pluginId,
});
const ver = await this.pluginVersionRepo.findOneBy({ pluginId, version });
if (!ver) throw new ApiError(404, `未找到插件包 ${pluginId}@${version}`);
if (!grant || !Number(grant.canDownload)) throw new ApiError(403, '无该插件的下载授权');
const pkgPath = path.join(PKG_DIR, ver.filename);
if (!fs.existsSync(pkgPath)) throw new ApiError(404, `包文件缺失:${ver.filename}`);
// 票据落库共享(多实例通用);顺手清理过期票据
const nonce = randomBytes(16).toString('hex');
await this.downloadTicketRepo.manager.query(
'DELETE FROM download_tickets WHERE created_at < DATE_SUB(NOW(), INTERVAL 3600 SECOND)'
);
await this.downloadTicketRepo.insert({
nonce,
filename: ver.filename,
sha256: ver.sha256 || '',
used: 0,
});
return {
ticket: nonce,
url: `/api/download/${nonce}`,
filename: ver.filename,
sha256: ver.sha256 || '',
expiresAt: fmtNow(),
};
}
/** GET /api/download/{ticket} — 兑换下载(一次性) */
@Get('/download/:ticket')
async download(@Param('ticket') ticket: string, @Headers('X-API-Token') xApiToken: string = '') {
this.centerAuthService.checkApiToken(xApiToken);
// 原子占位:仅 used=0 能改成 1,命中行数=0 说明不存在或已用
const res = await this.downloadTicketRepo.manager.query(
'UPDATE download_tickets SET used = 1 WHERE nonce = ? AND used = 0',
[ticket]
);
const affected = Array.isArray(res) ? Number(res[0]?.affectedRows || 0) : Number(res?.affectedRows || 0);
const row = await this.downloadTicketRepo.findOneBy({ nonce: ticket });
if (!affected || !row) throw new ApiError(404, '下载票据无效或已使用');
const pkgPath = path.join(PKG_DIR, row.filename);
if (!fs.existsSync(pkgPath)) throw new ApiError(404, `包文件缺失:${row.filename}`);
// 审计
await this.auditRepo.insert({
account: '',
action: 'download-ticket',
target: row.filename,
detail: '',
at: new Date(),
});
this.ctx.attachment(row.filename);
this.ctx.set('Content-Type', 'application/octet-stream');
this.ctx.body = fs.createReadStream(pkgPath);
}
}
@@ -0,0 +1,128 @@
import { Column, Entity, Index, PrimaryColumn, PrimaryGeneratedColumn } from 'typeorm';
/**
* 统一账号(现网 accounts 表)
*/
@Entity('accounts')
export class AccountEntity {
@PrimaryGeneratedColumn({ name: 'id', type: 'int', unsigned: true, comment: '账号自增ID' })
id: number;
@Index({ unique: true })
@Column({ name: 'account', type: 'varchar', length: 64, comment: '登录账号(工号,唯一)' })
account: string;
@Column({ name: 'password_hash', type: 'varchar', length: 128, comment: '密码哈希(加盐)' })
passwordHash: string;
@Column({ name: 'salt', type: 'varchar', length: 64, comment: '密码盐值' })
salt: string;
@Column({ name: 'is_admin', type: 'tinyint', width: 1, default: 0, comment: '是否管理员' })
isAdmin: number;
@Index()
@Column({ name: 'dept', type: 'varchar', length: 64, default: '', comment: '所属部门' })
dept: string;
@Column({ name: 'nickname', type: 'varchar', length: 64, default: '', comment: '昵称/姓名' })
nickname: string;
@Column({ name: 'dingtalk_uid', type: 'varchar', length: 64, default: '', comment: '钉钉用户ID' })
dingtalkUid: string;
@Column({ name: 'must_change_pwd', type: 'tinyint', width: 1, default: 0, comment: '是否必须改密' })
mustChangePwd: number;
@Column({ name: 'avatar', type: 'varchar', length: 255, default: '', comment: '头像文件名' })
avatar: string;
@Column({ name: 'status', type: 'tinyint', width: 1, default: 1, comment: '1=启用 0=停用' })
status: number;
@Column({ name: 'created_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', comment: '创建时间' })
createdAt: Date;
@Column({ name: 'updated_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP', comment: '更新时间' })
updatedAt: Date;
}
/**
* 云端会话令牌(现网 cloud_tokens 表,主键 token)
*/
@Entity('cloud_tokens')
export class CloudTokenEntity {
@PrimaryColumn({ name: 'token', type: 'varchar', length: 64, comment: '云端会话令牌' })
token: string;
@Column({ name: 'account', type: 'varchar', length: 64, comment: '所属账号(工号)' })
account: string;
@Column({ name: 'nickname', type: 'varchar', length: 64, default: '', comment: '昵称快照' })
nickname: string;
@Index()
@Column({ name: 'expires_at', type: 'datetime', comment: '过期时间' })
expiresAt: Date;
@Column({ name: 'created_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', comment: '签发时间' })
createdAt: Date;
}
/**
* 执行机敏感凭证(现网 client_creds 表,主键 account)
*/
@Entity('client_creds')
export class ClientCredEntity {
@PrimaryColumn({ name: 'account', type: 'varchar', length: 64, comment: '执行机账号(工号)' })
account: string;
@Column({ name: 'pubkey_pem', type: 'text', comment: 'RSA 公钥 PEM' })
pubkeyPem: string;
@Column({ name: 'creds', type: 'mediumtext', comment: '敏感凭证密文 JSON' })
creds: string;
@Column({ name: 'updated_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP', comment: '更新时间' })
updatedAt: Date;
}
/**
* 一次性下载票据(现网 download_tickets 表,主键 nonce)
*/
@Entity('download_tickets')
export class DownloadTicketEntity {
@PrimaryColumn({ name: 'nonce', type: 'varchar', length: 32, comment: '一次性下载票据' })
nonce: string;
@Column({ name: 'filename', type: 'varchar', length: 255, comment: '插件包文件名' })
filename: string;
@Column({ name: 'sha256', type: 'char', length: 64, default: '', comment: 'sha256 校验值' })
sha256: string;
@Column({ name: 'used', type: 'tinyint', width: 1, default: 0, comment: '是否已兑换' })
used: number;
@Index()
@Column({ name: 'created_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', comment: '签发时间' })
createdAt: Date;
}
/**
* 登录防爆破计数(现网 auth_fail_counts 表,主键 account)
*/
@Entity('auth_fail_counts')
export class AuthFailCountEntity {
@PrimaryColumn({ name: 'account', type: 'varchar', length: 64, comment: '登录账号(工号)' })
account: string;
@Column({ name: 'fails', type: 'int', unsigned: true, default: 0, comment: '连续失败次数' })
fails: number;
@Column({ name: 'locked_until', type: 'datetime', nullable: true, comment: '锁定截止时间' })
lockedUntil: Date;
@Column({ name: 'updated_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP', comment: '更新时间' })
updatedAt: Date;
}
@@ -0,0 +1,110 @@
import { Column, Entity, Index, PrimaryColumn, PrimaryGeneratedColumn } from 'typeorm';
/**
* 插件元数据(现网 plugins 表)
*/
@Entity('plugins')
export class PluginEntity {
@PrimaryColumn({ name: 'id', type: 'varchar', length: 64, comment: '插件ID(唯一,如 seal_check)' })
id: string;
@Column({ name: 'name', type: 'varchar', length: 128, comment: '插件名称' })
name: string;
@Column({ name: 'latest_version', type: 'varchar', length: 32, comment: '最新版本号' })
latestVersion: string;
@Column({ name: 'description', type: 'varchar', length: 512, default: '', comment: '插件描述' })
description: string;
@Column({ name: 'category', type: 'varchar', length: 64, default: '', comment: '分类' })
category: string;
@Column({ name: 'icon', type: 'varchar', length: 255, default: '', comment: '图标标识' })
icon: string;
@Column({ name: 'status', type: 'varchar', length: 16, default: 'published', comment: 'published/disabled/revoked' })
status: string;
@Column({ name: 'force_min_version', type: 'varchar', length: 32, nullable: true, comment: '强制更新最低版本' })
forceMinVersion: string;
@Column({ name: 'force_deadline', type: 'varchar', length: 32, nullable: true, comment: '强制更新截止时间(ISO)' })
forceDeadline: string;
@Column({ name: 'manifest', type: 'text', nullable: true, comment: 'plugin.json 原文' })
manifest: string;
@Column({ name: 'created_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', comment: '创建时间' })
createdAt: Date;
@Column({ name: 'updated_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP', comment: '更新时间' })
updatedAt: Date;
}
/**
* 插件版本(现网 plugin_versions 表)
*/
@Entity('plugin_versions')
export class PluginVersionEntity {
@PrimaryGeneratedColumn({ name: 'id', type: 'bigint', unsigned: true, comment: '版本记录自增ID' })
id: number;
@Index()
@Column({ name: 'plugin_id', type: 'varchar', length: 64, comment: '所属插件ID' })
pluginId: string;
@Column({ name: 'version', type: 'varchar', length: 32, comment: '版本号' })
version: string;
@Column({ name: 'filename', type: 'varchar', length: 255, comment: '包文件名' })
filename: string;
@Column({ name: 'sha256', type: 'char', length: 64, default: '', comment: 'sha256 校验值' })
sha256: string;
@Column({ name: 'size_bytes', type: 'bigint', unsigned: true, default: 0, comment: '包体积(字节)' })
sizeBytes: number;
@Column({ name: 'uploaded_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', comment: '上传时间' })
uploadedAt: Date;
}
/**
* 账号-插件授权(现网 account_plugins 表,复合主键)
*/
@Entity('account_plugins')
export class AccountPluginEntity {
@PrimaryColumn({ name: 'account', type: 'varchar', length: 64, comment: '账号(工号)' })
account: string;
@PrimaryColumn({ name: 'plugin_id', type: 'varchar', length: 64, comment: '插件ID' })
pluginId: string;
@Column({ name: 'can_download', type: 'tinyint', width: 1, default: 1, comment: '是否允许下载' })
canDownload: number;
@Column({ name: 'can_run', type: 'tinyint', width: 1, default: 1, comment: '是否允许运行' })
canRun: number;
@Column({ name: 'granted_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', comment: '授权时间' })
grantedAt: Date;
@Column({ name: 'updated_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP', comment: '更新时间' })
updatedAt: Date;
}
/**
* 账号-平台白名单(现网 account_platforms 表,复合主键)
*/
@Entity('account_platforms')
export class AccountPlatformEntity {
@PrimaryColumn({ name: 'account', type: 'varchar', length: 64, comment: '账号(工号)' })
account: string;
@PrimaryColumn({ name: 'platform_id', type: 'varchar', length: 64, comment: '平台ID(hr/oa 等)' })
platformId: string;
@Column({ name: 'granted_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', comment: '授权时间' })
grantedAt: Date;
}
@@ -0,0 +1,152 @@
import { Column, Entity, Index, PrimaryColumn, PrimaryGeneratedColumn } from 'typeorm';
/**
* 大文件源(现网 file_sources 表)
*/
@Entity('file_sources')
export class FileSourceEntity {
@PrimaryGeneratedColumn({ name: 'id', type: 'int', unsigned: true, comment: '自增ID' })
id: number;
@Index()
@Column({ name: 'category', type: 'varchar', length: 32, default: '', comment: 'shell/chrome/browser 等' })
category: string;
@Column({ name: 'version', type: 'varchar', length: 32, default: '', comment: '版本号' })
version: string;
@Column({ name: 'filename', type: 'varchar', length: 255, default: '', comment: '原文件名' })
filename: string;
@Column({ name: 'url', type: 'text', comment: '内网文件服务器直链' })
url: string;
@Column({ name: 'sha256', type: 'char', length: 64, default: '', comment: 'sha256 校验值' })
sha256: string;
@Column({ name: 'notes', type: 'varchar', length: 512, default: '', comment: '说明' })
notes: string;
@Column({ name: 'enabled', type: 'tinyint', width: 1, default: 1, comment: '1=启用 0=停用' })
enabled: number;
@Column({ name: 'updated_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP', comment: '更新时间' })
updatedAt: Date;
}
/**
* Chrome 安装包下载源(现网 chrome_releases 表)
*/
@Entity('chrome_releases')
export class ChromeReleaseEntity {
@PrimaryGeneratedColumn({ name: 'id', type: 'int', unsigned: true, comment: '配置自增ID' })
id: number;
@Column({ name: 'version', type: 'varchar', length: 32, default: '', comment: 'Chrome 版本号' })
version: string;
@Column({ name: 'url', type: 'text', comment: '安装包外链下载地址' })
url: string;
@Column({ name: 'filename', type: 'varchar', length: 255, default: '', comment: '落盘文件名' })
filename: string;
@Column({ name: 'sha256', type: 'char', length: 64, default: '', comment: 'sha256 校验值' })
sha256: string;
@Column({ name: 'notes', type: 'varchar', length: 512, default: '', comment: '说明' })
notes: string;
@Column({ name: 'enabled', type: 'tinyint', width: 1, default: 1, comment: '1=启用 0=停用' })
enabled: number;
@Column({ name: 'updated_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP', comment: '更新时间' })
updatedAt: Date;
}
/**
* 壳子定时任务备份(现网 schedule_backups 表,主键 account)
*/
@Entity('schedule_backups')
export class ScheduleBackupEntity {
@PrimaryColumn({ name: 'account', type: 'varchar', length: 64, comment: '执行机账号(工号)' })
account: string;
@Column({ name: 'data', type: 'mediumtext', comment: '定时任务全量配置 JSON' })
data: string;
@Column({ name: 'updated_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP', comment: '更新时间' })
updatedAt: Date;
}
/**
* 内网文件服务器状态(现网 fileserver_status 表)
*/
@Entity('fileserver_status')
export class FileserverStatusEntity {
@PrimaryGeneratedColumn({ name: 'id', type: 'int', unsigned: true, comment: '自增ID' })
id: number;
@Index({ unique: true })
@Column({ name: 'host', type: 'varchar', length: 255, comment: '文件服务器标识(唯一)' })
host: string;
@Column({ name: 'base_url', type: 'varchar', length: 255, default: '', comment: '对外下载根' })
baseUrl: string;
@Column({ name: 'hostname', type: 'varchar', length: 128, default: '', comment: '主机名' })
hostname: string;
@Column({ name: 'ip', type: 'varchar', length: 64, default: '', comment: 'IP 地址' })
ip: string;
@Column({ name: 'port', type: 'int', unsigned: true, default: 0, comment: '服务端口' })
port: number;
@Column({ name: 'file_count', type: 'int', unsigned: true, default: 0, comment: '文件数量' })
fileCount: number;
@Column({ name: 'total_size', type: 'bigint', unsigned: true, default: 0, comment: '文件总字节' })
totalSize: number;
@Column({ name: 'version', type: 'varchar', length: 64, default: '', comment: '服务版本' })
version: string;
@Column({ name: 'uptime_sec', type: 'int', unsigned: true, default: 0, comment: '进程运行秒数' })
uptimeSec: number;
@Index()
@Column({ name: 'last_seen', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', comment: '最后心跳时间' })
lastSeen: Date;
@Index()
@Column({ name: 'status', type: 'tinyint', width: 1, default: 1, comment: '1=在线 0=离线' })
status: number;
@Column({ name: 'last_status_change', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', comment: '最近在线/离线切换时间' })
lastStatusChange: Date;
@Column({ name: 'offline_notified', type: 'tinyint', width: 1, default: 0, comment: '离线已告警' })
offlineNotified: number;
@Column({ name: 'created_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', comment: '首次上报时间' })
createdAt: Date;
@Column({ name: 'updated_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP', comment: '更新时间' })
updatedAt: Date;
}
/**
* 系统级键值配置(现网 system_settings 表,主键 key)
*/
@Entity('system_settings')
export class SystemSettingEntity {
@PrimaryColumn({ name: 'key', type: 'varchar', length: 64, comment: '配置键' })
key: string;
@Column({ name: 'value', type: 'text', comment: '配置值(JSON 文本)' })
value: string;
@Column({ name: 'updated_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP', comment: '更新时间' })
updatedAt: Date;
}
@@ -0,0 +1,142 @@
import { Column, Entity, Index, PrimaryColumn, PrimaryGeneratedColumn } from 'typeorm';
/**
* 运行上报(现网 runtime_reports 表)
*/
@Entity('runtime_reports')
export class RuntimeReportEntity {
@PrimaryGeneratedColumn({ name: 'id', type: 'bigint', unsigned: true, comment: '记录自增ID' })
id: number;
@Index()
@Column({ name: 'account', type: 'varchar', length: 64, default: '', comment: '运行账号(工号)' })
account: string;
@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: 'version', type: 'varchar', length: 32, default: '', comment: '插件版本号' })
version: string;
@Index()
@Column({ name: 'status', type: 'varchar', length: 32, default: '', comment: 'start/done/success/error/failed' })
status: string;
@Column({ name: 'msg', type: 'text', comment: '结果/错误信息' })
msg: string;
@Column({ name: 'duration_sec', type: 'int', unsigned: true, default: 0, comment: '运行时长(秒)' })
durationSec: number;
@Index()
@Column({ name: 'at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', comment: '上报时间' })
at: Date;
}
/**
* 执行机设备(现网 devices 表,主键 device_id)
*/
@Entity('devices')
export class DeviceEntity {
@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: 'os', type: 'varchar', length: 64, default: '', comment: '操作系统' })
os: string;
@Column({ name: 'ip', type: 'varchar', length: 64, default: '', comment: 'IP 地址' })
ip: string;
@Column({ name: 'chrome_installed', type: 'tinyint', width: 1, default: 0, comment: '是否已安装 Chrome' })
chromeInstalled: number;
@Column({ name: 'chrome_version', type: 'varchar', length: 32, default: '', comment: 'Chrome 版本号' })
chromeVersion: string;
@Column({ name: 'chrome_ok', type: 'tinyint', width: 1, default: 0, comment: 'Chrome 是否就绪' })
chromeOk: number;
@Index()
@Column({ name: 'last_seen', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', comment: '最后在线时间' })
lastSeen: Date;
@Column({ name: 'status', type: 'tinyint', width: 1, default: 1, comment: '1=在线 0=离线' })
status: number;
@Column({ name: 'created_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', comment: '首次上报时间' })
createdAt: Date;
@Column({ name: 'updated_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP', comment: '更新时间' })
updatedAt: Date;
}
/**
* 审计日志(现网 audit_logs 表)
*/
@Entity('audit_logs')
export class AuditLogEntity {
@PrimaryGeneratedColumn({ name: 'id', type: 'bigint', unsigned: true, comment: '日志自增ID' })
id: number;
@Index()
@Column({ name: 'account', type: 'varchar', length: 64, default: '', comment: '操作账号' })
account: string;
@Index()
@Column({ name: 'action', type: 'varchar', length: 64, comment: '动作' })
action: string;
@Column({ name: 'target', type: 'varchar', length: 128, default: '', comment: '操作对象' })
target: string;
@Column({ name: 'detail', type: 'text', comment: '操作详情(JSON)' })
detail: string;
@Index()
@Column({ name: 'at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', comment: '操作时间' })
at: Date;
}
/**
* 通知(现网 notifications 表)
*/
@Entity('notifications')
export class NotificationEntity {
@PrimaryGeneratedColumn({ name: 'id', type: 'int', unsigned: true, comment: '通知ID' })
id: number;
@Column({ name: 'title', type: 'varchar', length: 200, comment: '标题' })
title: string;
@Column({ name: 'content', type: 'text', comment: '内容' })
content: string;
@Column({ name: 'level', type: 'varchar', length: 16, default: 'info', comment: 'info/warning/important' })
level: string;
@Column({ name: 'target', type: 'varchar', length: 16, default: 'all', comment: 'all/account' })
target: string;
@Column({ name: 'account', type: 'varchar', length: 64, default: '', comment: 'target=account 时的目标账号' })
account: string;
@Column({ name: 'created_at', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', comment: '创建时间' })
createdAt: Date;
@Column({ name: 'expires_at', type: 'datetime', nullable: true, comment: '过期时间' })
expiresAt: Date;
@Column({ name: 'active', type: 'tinyint', width: 1, default: 1, comment: '1=启用 0=停用' })
active: number;
}
@@ -0,0 +1,39 @@
import { Middleware } from '@midwayjs/core';
import { Context, NextFunction } from '@midwayjs/koa';
import { IMiddleware } from '@midwayjs/core';
/**
* 全局错误兜底中间件(37du 定制):
* - /api/* 与 /auth/exchange:渲染 FastAPI 兼容的 `{"detail": "<消息>"}`(壳子/插件/agent_cli 依赖)
* - 其余路径(/admin/* 等):渲染 cool-admin 信封 `{"code": <状态码>, "message": "..."}`
*
* 关键职责:兜住一切未捕获异常(含框架对未匹配路由抛出的 404 NotFoundError),
* 不允许任何错误击穿中间件链导致进程崩溃(Node 24 下 unhandled rejection 会直接退出)。
*/
@Middleware()
export class ApiErrorMiddleware implements IMiddleware<Context, NextFunction> {
resolve() {
return async (ctx: Context, next: NextFunction) => {
try {
await next();
} catch (err: any) {
const url = (ctx.url || '').split('?')[0];
let status = Number(err?.status || err?.statusCode || 0);
// 框架 404 NotFoundError:err.code === '404'
if (!status && String(err?.code) === '404') status = 404;
const code = status >= 400 && status <= 599 ? status : 500;
const message = String(err?.message || err?.detail || '服务器内部错误');
const isDetailContract =
url.startsWith('/api/') || url === '/auth/exchange';
ctx.status = code;
if (isDetailContract) {
ctx.body = { detail: message };
} else {
ctx.body = { code: status || code, message };
}
ctx.set('Content-Type', 'application/json');
}
};
}
}
@@ -0,0 +1,199 @@
import { Inject, Provide } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { randomBytes } from 'node:crypto';
import { AccountEntity, CloudTokenEntity, AuthFailCountEntity } from '../entity/account';
import { AuditLogEntity } from '../entity/runtime';
import { verifyAdminToken } from './crypto';
/**
* 业务鉴权(对齐旧 FastAPI core/auth.py):
* - X-API-Token:执行机底座→中心机的内部调用凭证
* - X-Admin-Token:管理员签名票据(HMAC,12h),管理操作唯一可信身份
* - Authorization: Bearer <cloud_token>:员工端扫码登录的云端会话(落库 7 天)
*/
/** 业务错误:携带 HTTP 状态码,由 api-error 中间件渲染为 {detail} */
export class ApiError extends Error {
status: number;
constructor(status: number, message: string) {
super(message);
this.status = status;
}
}
@Provide()
export class CenterAuthService {
@InjectEntityModel(AccountEntity)
accountRepo: Repository<AccountEntity>;
@InjectEntityModel(CloudTokenEntity)
cloudTokenRepo: Repository<CloudTokenEntity>;
@InjectEntityModel(AuthFailCountEntity)
authFailRepo: Repository<AuthFailCountEntity>;
// ==================== 内部凭证 ====================
checkApiToken(xApiToken: string = '') {
const token = process.env.CONTROLPLANE_TOKEN || '';
if (token && xApiToken !== token) {
throw new ApiError(401, '鉴权失败:无效或缺失 X-API-Token');
}
}
/** 账号是否已停用(停用后机器侧一律不给插件/授权) */
async accountDisabled(acct: string): Promise<boolean> {
const row = await this.accountRepo.findOneBy({ account: acct });
return !!row && !Number(row.status);
}
// ==================== 管理员票据 ====================
async requireAdmin(xAdminToken: string = '', xApiToken: string = ''): Promise<string> {
let account = '';
try {
account = verifyAdminToken(xAdminToken);
} catch (e) {
throw new ApiError(401, '登录态无效或已过期,请重新登录');
}
if (!account) throw new ApiError(401, '缺少有效登录态');
return this._adminGate(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, '请先修改初始密码后再执行管理操作');
return account;
}
// ==================== 云端会话 token ====================
async cloudAccount(bearer: string): Promise<string> {
let token = (bearer || '').trim();
if (token.toLowerCase().startsWith('bearer ')) token = token.slice(7).trim();
if (!token) return '';
try {
const row = await this.cloudTokenRepo
.createQueryBuilder('t')
.innerJoin(AccountEntity, 'a', 'a.account = t.account')
.select('t.account', 'account')
.where('t.token = :token', { token })
.andWhere('t.expiresAt > NOW()')
.andWhere('a.status = 1')
.getRawOne();
return row ? String(row.account) : '';
} catch (e) {
return '';
}
}
async issueCloudToken(account: string, nickname: string): Promise<string> {
const token = randomBytes(32).toString('base64url');
await this.cloudTokenRepo
.createQueryBuilder()
.delete()
.where('expiresAt < NOW()')
.execute();
await this.cloudTokenRepo.save(
this.cloudTokenRepo.create({
token,
account,
nickname: nickname || '',
expiresAt: new Date(Date.now() + 7 * 24 * 3600 * 1000),
})
);
return token;
}
async revokeAccountTokens(account: string) {
try {
await this.cloudTokenRepo.delete({ account });
} catch (e) {
/* 吊销失败不阻断 */
}
}
// ==================== 统一身份解析 ====================
async identity(
authorization: string = '',
xAdminToken: string = '',
xApiToken: string = '',
xAdminUser: string = ''
): Promise<string> {
const acct = await this.cloudAccount(authorization);
if (acct) return acct;
return this.resolveLogin(xAdminToken, xApiToken, xAdminUser);
}
resolveLogin(xAdminToken: string, xApiToken: string, xAdminUser: string): string {
try {
const account = verifyAdminToken(xAdminToken);
if (account) return account;
} catch (e) {
/* fallthrough */
}
if (
(xAdminUser || '').trim() &&
process.env.CONTROLPLANE_TOKEN &&
xApiToken === process.env.CONTROLPLANE_TOKEN
) {
return xAdminUser.trim();
}
throw new Error('no identity');
}
// ==================== 登录防爆破(auth_fail_counts) ====================
async authGate(account: string) {
try {
const row = await this.authFailRepo
.createQueryBuilder('f')
.select('1')
.where('f.account = :account', { account })
.andWhere('f.lockedUntil > NOW()')
.getRawOne();
if (row) throw new ApiError(429, '失败次数过多,账号已临时锁定,请 5 分钟后再试');
} catch (e) {
if (e instanceof ApiError) throw e;
/* 计数失败不阻断 */
}
}
async authFail(account: string) {
const LIMIT = 5;
try {
const conn = this.authFailRepo.manager;
await conn.query(
`INSERT INTO auth_fail_counts(account, fails, locked_until) VALUES (?, 1, NULL)
ON DUPLICATE KEY UPDATE
fails = IF(locked_until IS NOT NULL AND locked_until <= NOW(), 1, fails + 1),
locked_until = IF(fails + 1 >= ${LIMIT}, DATE_ADD(NOW(), INTERVAL 300 SECOND), NULL)`,
[account]
);
} catch (e) {
/* 计数失败不阻断 */
}
}
async authReset(account: string) {
try {
await this.authFailRepo.delete({ account });
} catch (e) {
/* 忽略 */
}
}
/** 写审计日志(audit_logs),失败不阻断 */
async audit(account: string, action: string, target: string = '', detail: string = '') {
try {
await this.authFailRepo.manager.insert(AuditLogEntity, {
account: account || '',
action,
target: target || '',
detail: detail || '',
at: new Date(),
});
} catch (e) {
/* 审计失败不阻断 */
}
}
}
@@ -0,0 +1,139 @@
import * as crypto from 'crypto';
import * as fs from 'fs';
import * as path from 'path';
import { CENTER_DATA_DIR } from '../comm/conf';
/**
* 中心机密码学(与旧 FastAPI core/crypto.py 逐字对齐):
* - 口令哈希:pbkdf2_hmac(sha256, 120000 轮),盐随机 + 常数时间比较
* - Ed25519 签名:{base64url(json_canon)}.{base64url(sig64)},私钥持久化可导入现网密钥
* - RSA-OAEP(SHA256) 加密:执行机敏感凭证下发
*/
const PBKDF2_ITER = 120000;
const KEY_DIR = path.join(CENTER_DATA_DIR, 'keys');
/** 规范化 JSON(递归按 key 排序、紧凑分隔符),对齐 Python json.dumps(sort_keys=True, separators=(',',':')) */
export function canonicalJson(obj: any): string {
if (obj === null || typeof obj !== 'object') return JSON.stringify(obj);
if (Array.isArray(obj)) return '[' + obj.map(canonicalJson).join(',') + ']';
const keys = Object.keys(obj).sort();
return '{' + keys.map(k => JSON.stringify(k) + ':' + canonicalJson(obj[k])).join(',') + '}';
}
// ==================== 口令哈希 ====================
export function hashPassword(pwd: string, salt: string = ''): { hash: string; salt: string } {
const s = salt || crypto.randomBytes(8).toString('hex');
const dk = crypto.pbkdf2Sync(pwd, s, PBKDF2_ITER, 32, 'sha256');
return { hash: dk.toString('hex'), salt: s };
}
export function verifyPassword(pwd: string, salt: string, hexdigest: string): boolean {
const dk = crypto.pbkdf2Sync(pwd, salt, PBKDF2_ITER, 32, 'sha256');
const a = Buffer.from(dk.toString('hex'), 'utf8');
const b = Buffer.from(hexdigest || '', 'utf8');
return a.length === b.length && crypto.timingSafeEqual(a, b);
}
// ==================== Ed25519 密钥 + 签名票据 ====================
let _keys: { priv: crypto.KeyObject; pub: crypto.KeyObject } | null = null;
function loadOrCreateKeypair() {
if (_keys) return _keys;
fs.mkdirSync(KEY_DIR, { recursive: true });
const privPath = path.join(KEY_DIR, 'center_key.priv');
const pubPath = path.join(KEY_DIR, 'center_key.pub');
if (fs.existsSync(privPath) && fs.existsSync(pubPath)) {
_keys = {
priv: crypto.createPrivateKey(fs.readFileSync(privPath)),
pub: crypto.createPublicKey(fs.readFileSync(pubPath)),
};
} else {
const { publicKey, privateKey } = crypto.generateKeyPairSync('ed25519');
fs.writeFileSync(privPath, privateKey.export({ type: 'pkcs8', format: 'pem' }));
fs.writeFileSync(pubPath, publicKey.export({ type: 'spki', format: 'pem' }));
_keys = { priv: privateKey, pub: publicKey };
}
return _keys;
}
/** 中心机公钥 PEM(/api/me/pubkey 下发,执行机缓存离线验签) */
export function pubkeyPem(): string {
return loadOrCreateKeypair().pub.export({ type: 'spki', format: 'pem' }).toString();
}
/** 签名打包:{base64url(json)}.{base64url(ed25519sig)} */
export function signBlob(payload: object): string {
const canon = Buffer.from(canonicalJson(payload), 'utf8');
const sig = crypto.sign(null, canon, loadOrCreateKeypair().priv);
return `${canon.toString('base64url')}.${sig.toString('base64url')}`;
}
/** 验签并返回 payload;签名非法抛 Error */
export function verifyBlob(blob: string, pub: crypto.KeyObject): any {
const idx = blob.lastIndexOf('.');
if (idx < 0) throw new Error('bad blob');
const canon = Buffer.from(blob.slice(0, idx), 'base64url');
const sig = Buffer.from(blob.slice(idx + 1), 'base64url');
if (sig.length !== 64) throw new Error('bad signature len');
const ok = crypto.verify(null, canon, pub, sig);
if (!ok) throw new Error('bad signature');
return JSON.parse(canon.toString('utf8'));
}
// ==================== RSA-OAEP 加密(凭证下发) ====================
export function rsaEncrypt(pubkeyPem: string, plaintext: string): string {
const pub = crypto.createPublicKey(pubkeyPem);
const ct = crypto.publicEncrypt(
{
key: pub,
padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
oaepHash: 'sha256',
},
Buffer.from(plaintext, 'utf8')
);
return ct.toString('base64');
}
// ==================== 管理员票据 HMAC 签名(对齐 core/auth.py) ====================
const ADMIN_TOKEN_TTL = 12 * 3600; // 12h
function loadAdminSecret(): string {
const env = (process.env.CONTROLPLANE_ADMIN_SECRET || '').trim();
if (env) return env;
const dir = CENTER_DATA_DIR;
fs.mkdirSync(dir, { recursive: true });
const f = path.join(dir, '.admin_secret');
if (fs.existsSync(f)) return fs.readFileSync(f, 'utf8').trim();
const secret = crypto.randomBytes(32).toString('hex');
fs.writeFileSync(f, secret, 'utf8');
return secret;
}
let _adminSecret: string | null = null;
export function adminSecret(): string {
if (!_adminSecret) _adminSecret = loadAdminSecret();
return _adminSecret;
}
export function signAdminToken(account: string): string {
const payload = Buffer.from(
JSON.stringify({ a: account, e: Math.floor(Date.now() / 1000) + ADMIN_TOKEN_TTL })
).toString('base64url');
const sig = crypto.createHmac('sha256', adminSecret()).update(payload).digest('hex');
return `${payload}.${sig}`;
}
export function verifyAdminToken(tok: string): string {
const idx = tok.lastIndexOf('.');
if (idx < 0) throw new Error('invalid token');
const payload = tok.slice(0, idx);
const sig = tok.slice(idx + 1);
const expect = crypto.createHmac('sha256', adminSecret()).update(payload).digest('hex');
const a = Buffer.from(expect, 'utf8');
const b = Buffer.from(sig, 'utf8');
if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) throw new Error('bad signature');
const data = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
if (Number(data.e || 0) < Date.now() / 1000) throw new Error('expired');
return String(data.a || '');
}
@@ -0,0 +1,75 @@
import { Provide } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { BaseSysDepartmentEntity } from '../../base/entity/sys/department';
/**
* 部门数据范围("本部门及以下")补齐工具。
*
* cool-admin 原生:部门树(parentId) + 角色-部门授权(base_sys_role_department),
* 但 `role.relevance`(关联上下级)字段未被消费,"本部门及以下"的自动展开缺失。
* 本工具:
* 1. 解析操作者角色的授权部门集合(超管=全部)
* 2. 按 parentId 树递归向下展开后代部门("本部门及以下")
* 3. 业务列表查询据此拼 dept_id IN (...) 过滤
*/
@Provide()
export class CenterDeptScopeService {
@InjectEntityModel(BaseSysDepartmentEntity)
deptRepo: Repository<BaseSysDepartmentEntity>;
/**
* 某用户的部门数据范围
* @returns { admin: boolean, deptIds: number[] } — admin=true 表示全量;deptIds 为"本部门及以下"展开后的集合
*/
async userScope(userId: number, username: string): Promise<{ admin: boolean; deptIds: number[] }> {
if (username === 'admin') return { admin: true, deptIds: [] };
const m = this.deptRepo.manager;
// 用户 → 角色 → 授权部门
const rows: any[] = await m.query(
`SELECT DISTINCT rd.department_id AS departmentId
FROM base_sys_user_role ur
JOIN base_sys_role_department rd ON rd.role_id = ur.role_id
WHERE ur.user_id = ?`,
[userId]
);
const rootIds = rows.map((r: any) => Number(r.departmentId)).filter((n: number) => !isNaN(n) && n > 0);
if (!rootIds.length) return { admin: false, deptIds: [] };
return { admin: false, deptIds: await this.expandDescendants(rootIds) };
}
/**
* 按 parentId 树向下展开:返回 rootIds 及其所有后代部门 ID
*/
async expandDescendants(rootIds: number[]): Promise<number[]> {
const all = await this.deptRepo.find();
const children: Record<number, number[]> = {};
for (const d of all) {
const pid = d.parentId ? Number(d.parentId) : 0;
if (!children[pid]) children[pid] = [];
children[pid].push(Number(d.id));
}
const result = new Set<number>();
const queue = [...rootIds];
while (queue.length) {
const id = queue.shift()!;
if (result.has(id)) continue;
result.add(id);
for (const c of children[id] || []) queue.push(c);
}
return [...result];
}
/**
* 生成业务查询的 dept 过滤条件片段(含参数)。
* 返回 { sql: string, args: number[] };scope.admin=true 时返回 { sql: '', args: [] }(全量)。
*/
async deptFilter(userId: number, username: string, deptColumn = 'dept_id') {
const scope = await this.userScope(userId, username);
if (scope.admin || !scope.deptIds.length) return { sql: '', args: [] as number[] };
return {
sql: `${deptColumn} IN (${scope.deptIds.map(() => '?').join(',')})`,
args: scope.deptIds,
};
}
}
@@ -0,0 +1,115 @@
import axios from 'axios';
/**
* 中心机钉钉官方接口封装(对齐旧 FastAPI core/dingtalk.py):
* - dingtalkUserinfo(authCode):OAuth 扫码 authCode → unionid/昵称 →(可选)企业内部 token
* → getbyunionid 取 userid → v2/user/get 取工号;
* - 与执行机/老后端共用一套凭证语义:DINGTALK_APP_KEY/SECRET 即可完成全链路。
*/
const HTTP_TIMEOUT = 10000;
async function getJson(url: string, headers: Record<string, string> = {}): Promise<any> {
try {
const r = await axios.get(url, { timeout: HTTP_TIMEOUT, headers });
return r.data;
} catch (e: any) {
throw new Error(`钉钉接口访问失败:${e?.message || e}`);
}
}
async function postJson(url: string, payload: object, headers: Record<string, string> = {}): Promise<any> {
try {
const r = await axios.post(url, payload, {
timeout: HTTP_TIMEOUT,
headers: { 'Content-Type': 'application/json', ...headers },
});
return r.data;
} catch (e: any) {
throw new Error(`钉钉接口访问失败:${e?.message || e}`);
}
}
// 企业内部 token 缓存(gettoken 的 access_token 有 TTL,缓存到临近过期)
const topapiCache: { at: string; exp: number } = { at: '', exp: 0 };
/** 获取企业内部应用 access_token(取工号/发工作通知链路用)。失败返回空串不阻断。 */
export async function topapiToken(): Promise<string> {
const appKey = (process.env.DINGTALK_APP_KEY || '').trim();
const appSecret = (process.env.DINGTALK_APP_SECRET || '').trim();
if (!appKey || !appSecret) return '';
const now = Date.now() / 1000;
if (topapiCache.at && topapiCache.exp > now + 60) return topapiCache.at;
try {
const info = await getJson(
`https://oapi.dingtalk.com/gettoken?appkey=${encodeURIComponent(appKey)}&appsecret=${encodeURIComponent(appSecret)}`
);
const at = String(info?.access_token || '');
if (!at) return '';
topapiCache.at = at;
topapiCache.exp = now + Number(info?.expires_in || 7200);
return at;
} catch (e) {
return ''; // 取企业内部 token 失败不阻断扫码登录
}
}
/** 用钉钉扫码回调的 authCode 换取当前钉钉用户工号/姓名/unionid(对齐 _dingtalk_userinfo)。 */
export async function dingtalkUserinfo(authCode: string): Promise<{ account: string; nickname: string; unionid: string }> {
const appKey = (process.env.DINGTALK_APP_KEY || '').trim();
const appSecret = (process.env.DINGTALK_APP_SECRET || '').trim();
if (!appKey || !appSecret) {
const err: any = new Error('未配置钉钉开放平台应用(DINGTALK_APP_KEY / DINGTALK_APP_SECRET)');
err.status = 503;
throw err;
}
// Step1: authCode -> accessToken -> unionid + nick
let tok: any;
try {
tok = await postJson('https://api.dingtalk.com/v1.0/oauth2/userAccessToken', {
clientId: appKey,
clientSecret: appSecret,
code: authCode,
grantType: 'authorization_code',
});
} catch (e) {
throw e; // 网络/接口错误原样上抛(502 语义由调用方包装)
}
const at = String(tok?.accessToken || '');
if (!at) {
const err: any = new Error('钉钉授权码无效或已过期,请重新扫码');
err.status = 401;
throw err;
}
const me = await getJson('https://api.dingtalk.com/v1.0/contact/users/me', {
'x-acs-dingtalk-access-token': at,
});
const unionid = String(me?.unionId || me?.unionid || '');
let nickname = String(me?.nick || '');
let account = String(me?.jobNumber || me?.userId || unionid);
// Step2/3: (可选)企业内部 token -> getbyunionid(userid) -> v2/user/get(job_number)
const topAt = await topapiToken();
if (topAt && unionid) {
try {
const byunion = await postJson(
`https://oapi.dingtalk.com/topapi/user/getbyunionid?access_token=${topAt}`,
{ unionid }
);
const ures = byunion?.result || {};
const userid = String(ures?.userid || ures?.userId || '');
if (userid) {
const ud = await postJson(
`https://oapi.dingtalk.com/topapi/v2/user/get?access_token=${topAt}`,
{ userid }
);
const res = ud?.result || {};
const job = String(res?.job_number || res?.jobNumber || '');
nickname = nickname || String(res?.name || '');
account = job || userid || account;
}
} catch (e) {
/* 取工号失败不阻断登录,回退已得字段 */
}
}
return { account, nickname, unionid };
}
@@ -0,0 +1,81 @@
import { Inject, Provide } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { FileserverStatusEntity } from '../entity/resource';
import { CenterNotifyService } from './notify';
import { FILESERVER_HEARTBEAT_TIMEOUT, FILESERVER_MONITOR_INTERVAL } from '../comm/conf';
/**
* 内网文件服务器离线监控(对齐旧 FastAPI core/monitor.py):
* - 文件服务器周期主动上报心跳(/api/fileserver/heartbeat,默认 60s 一次,落库 last_seen);
* - 本服务按 FILESERVER_MONITOR_INTERVAL(默认 30s)扫描「在线且未告警」的记录,
* 对 last_seen 超过 FILESERVER_HEARTBEAT_TIMEOUT(默认 180s)的判定离线并推送钉钉;
* - 离线转换用「带条件的原子 UPDATE」认领(status=1 且 offline_notified=0 且 last_seen 超时),
* 多实例并发下仅一个实例认领成功,避免重复告警;
* - 恢复上线由心跳接口处理:收到心跳即翻转在线并清除告警标记。
*/
@Provide()
export class FileserverMonitorService {
@InjectEntityModel(FileserverStatusEntity)
fileserverRepo: Repository<FileserverStatusEntity>;
@Inject()
centerNotifyService: CenterNotifyService;
private timer: NodeJS.Timeout | null = null;
start(): void {
if (this.timer) return;
const interval = Math.max(5, FILESERVER_MONITOR_INTERVAL) * 1000;
this.timer = setInterval(() => {
this.scanOnce().catch(() => {
/* 监控异常不退出,下轮重试 */
});
}, interval);
// 不阻止进程退出
this.timer.unref?.();
}
stop(): void {
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
}
/** 扫描一次:将心跳超时的在线文件服务器翻转为离线并告警(幂等 / 并发安全)。 */
async scanOnce(): Promise<void> {
const cutoff = new Date(Date.now() - FILESERVER_HEARTBEAT_TIMEOUT * 1000);
const rows = await this.fileserverRepo
.createQueryBuilder('f')
.select(['f.host', 'f.hostname', 'f.ip', 'f.lastSeen'])
.where('f.status = 1')
.andWhere('f.offlineNotified = 0')
.getMany();
for (const r of rows) {
let claimed = false;
try {
const res = await this.fileserverRepo
.createQueryBuilder()
.update(FileserverStatusEntity)
.set({ status: 0, offlineNotified: 1, lastStatusChange: new Date() })
.where('host = :host', { host: r.host })
.andWhere('status = 1')
.andWhere('offlineNotified = 0')
.andWhere('lastSeen < :cutoff', { cutoff })
.execute();
claimed = Number(res?.affected || 0) > 0;
} catch (e) {
continue; // 单条认领失败不影响其余扫描
}
if (!claimed) continue; // 已被其它实例认领,或刚恢复心跳
console.warn(`检测到文件服务器离线:${r.host}(最后心跳 ${r.lastSeen})`);
this.centerNotifyService.notifyFileserverDown(
r.host,
r.hostname || '',
r.ip || '',
String(r.lastSeen || '')
);
}
}
}
@@ -0,0 +1,204 @@
import axios from 'axios';
import * as crypto from 'crypto';
import { Inject, Provide } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { AccountEntity } from '../entity/account';
import { topapiToken } from './dingtalk';
/**
* 钉钉通知(对齐旧 FastAPI core/notify.py):自建应用工作通知(个人推送)
* + 群机器人 webhook(备用渠道)。全部后台异步发送,失败仅记日志不阻断业务。
*
* 配置项(server/.env):
* - DINGTALK_AGENT_ID 自建应用 AgentId;留空则不发工作通知(KEY/SECRET 复用扫码那套)
* - DINGTALK_ADMIN_NAME 权限开通提醒管理员姓名(默认 夏一平)
* - DINGTALK_WEBHOOK_URL 群机器人 webhook(备用渠道)
* - DINGTALK_WEBHOOK_SECRET 群机器人加签密钥(可选)
*/
const HTTP_TIMEOUT = 10000;
const SIGN_NAME = '37du 自动化平台';
const STATUS_COLORS: Record<string, string> = {
info: '#0077ff',
success: '#00b300',
warning: '#ff9900',
error: '#ff0000',
};
function footer(): string {
const d = new Date();
const p = (n: number) => String(n).padStart(2, '0');
return `###### ${SIGN_NAME} | ${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
}
async function postJson(url: string, payload: object, headers: Record<string, string> = {}): Promise<any> {
const r = await axios.post(url, payload, {
timeout: HTTP_TIMEOUT,
headers: { 'Content-Type': 'application/json', ...headers },
});
return r.data;
}
@Provide()
export class CenterNotifyService {
@InjectEntityModel(AccountEntity)
accountRepo: Repository<AccountEntity>;
// ==================== userid 解析(单次直查,不做通讯录遍历/缓存) ====================
private async useridByUnionid(at: string, unionid: string): Promise<string> {
try {
const body = await postJson(
`https://oapi.dingtalk.com/topapi/user/getbyunionid?access_token=${at}`,
{ unionid }
);
return String(body?.result?.userid || '');
} catch (e) {
return '';
}
}
private async useridByName(at: string, name: string): Promise<string> {
try {
const body = await postJson(
'https://api.dingtalk.com/v1.0/contact/users/search',
{ queryWord: name.trim(), offset: 0, size: 5, maxResults: 5 },
{ 'x-acs-dingtalk-access-token': at }
);
const list: any[] = body?.list || [];
return list.length ? String(list[0]) : '';
} catch (e) {
return '';
}
}
// ==================== 渠道一:自建应用工作通知 ====================
private async sendWorkTo(
at: string, agentId: string, userid: string, title: string, content: string,
status: string = 'info'
): Promise<boolean> {
const color = STATUS_COLORS[status] || STATUS_COLORS.info;
let text = `**<font color='${color}'>${title}</font>**\n\n`;
text += content.trim() + '\n';
text += `\n\n---\n\n${footer()}`;
try {
const body = await postJson(
`https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token=${at}`,
{
agent_id: agentId,
userid_list: userid,
msg: { msgtype: 'markdown', markdown: { title, text } },
}
);
if (Number(body?.errcode) !== 0) return false;
return true;
} catch (e) {
return false; // 通知失败不阻断业务
}
}
// ==================== 渠道二:群机器人 webhook(+ 加签) ====================
private signedWebhookUrl(): string {
const url = (process.env.DINGTALK_WEBHOOK_URL || '').trim();
if (!url) return '';
const secret = (process.env.DINGTALK_WEBHOOK_SECRET || '').trim();
if (secret) {
const ts = String(Date.now());
const sign = crypto
.createHmac('sha256', secret)
.update(`${ts}\n${secret}`, 'utf8')
.digest('base64');
return `${url}${url.includes('?') ? '&' : '?'}timestamp=${ts}&sign=${encodeURIComponent(sign)}`;
}
return url;
}
private async sendRobot(title: string, text: string): Promise<void> {
const url = this.signedWebhookUrl();
if (!url) return;
try {
const body = await postJson(url, { msgtype: 'markdown', markdown: { title, text } });
if (Number(body?.errcode) !== 0) console.warn('钉钉群通知被拒:', JSON.stringify(body));
} catch (e: any) {
console.warn('钉钉群通知异常:', e?.message || e);
}
}
// ==================== 新账号创建通知(管理台/钉钉扫码共用) ====================
/** 新账号创建通知(新用户收账号+初始密码,管理员收权限开通提醒),异步发送。 */
notifyAccountCreated(account: string, nickname = '', password = '', unionid = '', source = '管理台'): void {
// 异步 fire-and-forget,不阻断业务主流程
this.workAccountCreated(account, nickname, password, unionid, source).catch(() => {});
}
private async workAccountCreated(
account: string, nickname: string, password: string, unionid: string, source: string
): Promise<void> {
const agentId = (process.env.DINGTALK_AGENT_ID || process.env.CREDS_DINGTALK_AGENT_ID || '').trim();
if (!agentId) return;
try {
const at = await topapiToken();
if (!at) return;
// 1) 新用户本人:unionid 精确解析 userid,兜底按昵称搜索直查
let uid = unionid ? await this.useridByUnionid(at, unionid) : '';
if (!uid && nickname) uid = await this.useridByName(at, nickname);
if (uid) {
await this.sendWorkTo(
at, agentId, uid, '账号开通通知',
`**🔹 ${nickname || account}‑账号开通**\n\n> 账号:${account}\n\n> 初始密码:${password}\n\n> 备注:首次登录须修改密码,请及时登录并妥善保管`,
'success'
);
}
// 2) 管理员:权限开通提醒(按姓名搜索直查)
const adminName = (process.env.DINGTALK_ADMIN_NAME || '夏一平').trim();
const adminUid = await this.useridByName(at, adminName);
if (adminUid) {
await this.sendWorkTo(
at, agentId, adminUid, '新账号待开通权限',
`> 账号:${account}\n\n> 姓名:${nickname || '—'}\n\n> 来源:${source}\n\n> 备注:请到管理台为该账号开通插件权限`,
'warning'
);
}
} catch (e) {
/* 通知失败不阻断业务 */
}
}
// ==================== 内网文件服务器离线告警 ====================
/** 管理员名单(nickname 优先,其次 account),用于离线告警收件人。 */
private async adminNames(): Promise<string[]> {
try {
const rows: any[] = await this.accountRepo.find({ where: { isAdmin: 1 } as any });
return rows
.sort((a, b) => a.id - b.id)
.map(r => (r.nickname || r.account || '').trim())
.filter(Boolean);
} catch (e) {
return [];
}
}
/** 文件服务器离线告警:优先工作通知推给全部管理员,无人送达回退群机器人 webhook。 */
notifyFileserverDown(host: string, hostname = '', ip = '', lastSeen = ''): void {
this.workFileserverDown(host, hostname, ip, lastSeen).catch(() => {});
}
private async workFileserverDown(host: string, hostname: string, ip: string, lastSeen: string): Promise<void> {
const title = '内网文件服务器下线告警';
const content =
`> 服务:${hostname || '—'}\n\n> 地址:${host}\n\n> IP:${ip || '—'}\n\n` +
`> 最后心跳:${lastSeen || '—'}\n\n` +
'> 提示:执行机将无法下载大文件(壳子/Chrome 安装包),请尽快排查进程或网络;服务恢复后将自动解除告警';
const agentId = (process.env.DINGTALK_AGENT_ID || process.env.CREDS_DINGTALK_AGENT_ID || '').trim();
const at = agentId ? await topapiToken() : '';
let sentAny = false;
if (at) {
for (const name of await this.adminNames()) {
if (!name) continue;
const uid = await this.useridByName(at, name);
if (uid && (await this.sendWorkTo(at, agentId, uid, title, content, 'error'))) sentAny = true;
}
}
if (!sentAny) await this.sendRobot(title, content);
}
}
@@ -0,0 +1,19 @@
import { ModuleConfig } from '@cool-midway/core';
/**
* 模块配置
*/
export default () => {
return {
// 模块名称
name: 'demo模块',
// 模块描述
description: '演示用',
// 中间件,只对本模块有效
middlewares: [],
// 中间件,全局有效
globalMiddlewares: [],
// 模块加载顺序,默认为0,值越大越优先加载
order: 0,
} as ModuleConfig;
};
@@ -0,0 +1,27 @@
import { CoolController, BaseController } from '@cool-midway/core';
import { DemoGoodsEntity } from '../../entity/goods';
import { UserInfoEntity } from '../../../user/entity/info';
import { DemoGoodsService } from '../../service/goods';
/**
* 商品模块-商品信息
*/
@CoolController({
api: ['add', 'delete', 'update', 'info', 'list', 'page'],
entity: DemoGoodsEntity,
service: DemoGoodsService,
pageQueryOp: {
keyWordLikeFields: ['a.description'],
fieldEq: ['a.status'],
fieldLike: ['a.title'],
select: ['a.*', 'b.nickName as userName'],
join: [
{
entity: UserInfoEntity,
alias: 'b',
condition: 'a.id = b.id',
},
],
},
})
export class AdminDemoGoodsController extends BaseController {}
@@ -0,0 +1,23 @@
import { CoolController, BaseController } from '@cool-midway/core';
import { DemoGoodsEntity } from '../../entity/goods';
import { DemoTenantService } from '../../service/tenant';
/**
* 多租户
*/
@CoolController({
serviceApis: [
'use',
{
method: 'noUse',
summary: '不使用多租户',
},
{
method: 'noTenant',
summary: '局部不使用多租户',
},
],
entity: DemoGoodsEntity,
service: DemoTenantService,
})
export class AdminDemoTenantController extends BaseController {}
@@ -0,0 +1,37 @@
import { DemoCacheService } from '../../service/cache';
import { Inject, Post, Provide, Get, InjectClient } from '@midwayjs/core';
import { CoolController, BaseController } from '@cool-midway/core';
import { CachingFactory, MidwayCache } from '@midwayjs/cache-manager';
/**
* 缓存
*/
@CoolController()
export class OpenDemoCacheController extends BaseController {
@InjectClient(CachingFactory, 'default')
midwayCache: MidwayCache;
@Inject()
demoCacheService: DemoCacheService;
/**
* 设置缓存
* @returns
*/
@Post('/set', { summary: '设置缓存' })
async set() {
await this.midwayCache.set('a', 1);
// 缓存10秒
await this.midwayCache.set('a', 1, 10 * 1000);
return this.ok(await this.midwayCache.get('a'));
}
/**
* 获得缓存
* @returns
*/
@Get('/get', { summary: '获得缓存' })
async get() {
return this.ok(await this.demoCacheService.get());
}
}
@@ -0,0 +1,27 @@
import { Inject, Post } from '@midwayjs/core';
import {
CoolController,
BaseController,
CoolEventManager,
} from '@cool-midway/core';
/**
* 事件
*/
@CoolController()
export class OpenDemoEventController extends BaseController {
@Inject()
coolEventManager: CoolEventManager;
@Post('/comm', { summary: '普通事件,本进程生效' })
async comm() {
await this.coolEventManager.emit('demo', { a: 2 }, 1);
return this.ok();
}
@Post('/global', { summary: '全局事件,多进程都有效' })
async global() {
await this.coolEventManager.globalEmit('demo', false, { a: 2 }, 1);
return this.ok();
}
}
@@ -0,0 +1,35 @@
import { DemoGoodsService } from '../../service/goods';
import { DemoGoodsEntity } from '../../entity/goods';
import { Body, Inject, Post } from '@midwayjs/core';
import { CoolController, BaseController } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
/**
* 测试
*/
@CoolController({
api: ['add', 'delete', 'update', 'info', 'list', 'page'],
entity: DemoGoodsEntity,
service: DemoGoodsService,
pageQueryOp: {
fieldLike: ['title'],
},
})
export class OpenDemoGoodsController extends BaseController {
@InjectEntityModel(DemoGoodsEntity)
demoGoodsEntity: Repository<DemoGoodsEntity>;
@Inject()
demoGoodsService: DemoGoodsService;
@Post('/sqlPage', { summary: 'sql分页查询' })
async sqlPage(@Body() query) {
return this.ok(await this.demoGoodsService.sqlPage(query));
}
@Post('/entityPage', { summary: 'entity分页查询' })
async entityPage(@Body() query) {
return this.ok(await this.demoGoodsService.entityPage(query));
}
}
@@ -0,0 +1,20 @@
import { CoolController, BaseController } from '@cool-midway/core';
import { DemoI18nService } from '../../service/i18n';
/**
* 国际化
*/
@CoolController({
serviceApis: [
{
method: 'en',
summary: '翻译成英文',
},
{
method: 'tw',
summary: '翻译成繁体',
},
],
service: DemoI18nService,
})
export class DemoI18nController extends BaseController {}
@@ -0,0 +1,29 @@
import { CoolController, BaseController } from '@cool-midway/core';
import { PluginService } from '../../../plugin/service/info';
import { Get, Inject } from '@midwayjs/core';
/**
* 插件
*/
@CoolController()
export class OpenDemoPluginController extends BaseController {
@Inject()
pluginService: PluginService;
@Get('/invoke', { summary: '调用插件' })
async invoke() {
// 获取插件实例
const instance: any = await this.pluginService.getInstance('ollama');
// 调用chat
const messages = [
{ role: 'system', content: '你叫小酷,是一个智能助理' },
{ role: 'user', content: '写一个1000字的关于春天的文章' },
];
for (let i = 0; i < 3; i++) {
instance.chat(messages, { stream: true }, res => {
console.log(i, res.content);
});
}
return this.ok();
}
}
@@ -0,0 +1,49 @@
import { Get, Inject, Post, Provide } from '@midwayjs/core';
import { CoolController, BaseController } from '@cool-midway/core';
import { DemoCommQueue } from '../../queue/comm';
import { DemoGetterQueue } from '../../queue/getter';
/**
* 队列
*/
@CoolController()
export class OpenDemoQueueController extends BaseController {
// 普通队列
@Inject()
demoCommQueue: DemoCommQueue;
// 主动消费队列
@Inject()
demoGetterQueue: DemoGetterQueue;
/**
* 发送数据到队列
*/
@Post('/add', { summary: '发送队列数据' })
async queue() {
this.demoCommQueue.add({ a: 2 });
return this.ok();
}
@Post('/addGetter')
async addGetter() {
await this.demoGetterQueue.add({ a: new Date() });
return this.ok();
}
/**
* 获得队列中的数据,只有当队列类型为getter时有效
*/
@Get('/getter')
async getter() {
const job = await this.demoGetterQueue.getters.getJobs(
['wait'],
0,
0,
true
);
// 获得完将数据从队列移除
await job[0]?.remove();
return this.ok(job[0]?.data);
}
}
@@ -0,0 +1,29 @@
import { Inject, Provide, Get } from '@midwayjs/core';
import { CoolController, BaseController } from '@cool-midway/core';
import { DemoRpcService } from '../../service/rpc';
/**
* 远程RPC调用
*/
@CoolController()
export class OpenDemoRpcController extends BaseController {
@Inject()
demoRpcService: DemoRpcService;
@Get('/call', { summary: '远程调用' })
async call() {
return this.ok(await this.demoRpcService.call());
}
@Get('/event', { summary: '集群事件' })
async event() {
await this.demoRpcService.event();
return this.ok();
}
@Get('/transaction', { summary: '分布式事务' })
async transaction() {
await this.demoRpcService.transaction({ a: 1 });
return this.ok();
}
}
@@ -0,0 +1,49 @@
import { CoolController, BaseController } from '@cool-midway/core';
import { Get, Inject } from '@midwayjs/core';
import { PluginService } from '../../../plugin/service/info';
import { PassThrough } from 'stream';
import { IMidwayKoaContext } from '@midwayjs/koa';
/**
* 事件流 服务端主动推送
*/
@CoolController()
export class OpenDemoSSEController extends BaseController {
@Inject()
ctx: IMidwayKoaContext;
@Inject()
pluginService: PluginService;
@Get('/call', { summary: '事件流 服务端主动推送' })
async call() {
// 设置响应头
this.ctx.set('Content-Type', 'text/event-stream');
this.ctx.set('Cache-Control', 'no-cache');
this.ctx.set('Connection', 'keep-alive');
const stream = new PassThrough();
// 发送数据
const send = (data: any) => {
stream.write(`data: ${JSON.stringify(data)}\n\n`);
};
// 获取插件实例
const instance: any = await this.pluginService.getInstance('ollama');
// 调用chat
const messages = [
{ role: 'system', content: '你叫小酷,是个编程助手' },
{ role: 'user', content: '用js写个Hello World' },
];
instance.chat(messages, { stream: true }, res => {
send(res);
if (res.isEnd) {
this.ctx.res.end();
}
});
this.ctx.status = 200;
this.ctx.body = stream;
}
}
@@ -0,0 +1,13 @@
import { CoolController, BaseController } from '@cool-midway/core';
import { DemoGoodsEntity } from '../../entity/goods';
import { DemoTenantService } from '../../service/tenant';
/**
* 多租户
*/
@CoolController({
api: [],
entity: DemoGoodsEntity,
service: DemoTenantService,
})
export class OpenDemoTenantController extends BaseController {}
@@ -0,0 +1,14 @@
import { DemoGoodsEntity } from '../../entity/goods';
import { Provide } from '@midwayjs/core';
import { CoolController, BaseController } from '@cool-midway/core';
import { DemoTransactionService } from '../../service/transaction';
/**
* 事务
*/
@CoolController({
api: ['add', 'delete', 'update', 'info', 'list', 'page'],
entity: DemoGoodsEntity,
service: DemoTransactionService,
})
export class OpenDemoTransactionController extends BaseController {}
@@ -0,0 +1,43 @@
import { BaseEntity, transformerJson } from '../../base/entity/base';
import { Column, Entity, Index } from 'typeorm';
/**
* 商品模块-商品信息
*/
@Entity('demo_goods')
export class DemoGoodsEntity extends BaseEntity {
@Index()
@Column({ comment: '标题', length: 50 })
title: string;
@Column({
comment: '价格',
type: 'decimal',
precision: 5,
scale: 2,
})
price: number;
@Column({ comment: '描述', nullable: true })
description: string;
@Column({ comment: '主图', nullable: true })
mainImage: string;
@Column({ comment: '分类', dict: 'goodsType' })
type: number;
@Column({ comment: '状态', dict: ['禁用', '启用'], default: 1 })
status: number;
@Column({
comment: '示例图',
nullable: true,
type: 'json',
transformer: transformerJson,
})
exampleImages: string[];
@Column({ comment: '库存', default: 0 })
stock: number;
}
@@ -0,0 +1,27 @@
import { CoolEvent, Event } from '@cool-midway/core';
import { EVENT_PLUGIN_READY } from '../../plugin/service/center';
/**
* 普通事件
*/
@CoolEvent()
export class DemoCommEvent {
/**
* 根据事件名接收事件
* @param msg
* @param a
*/
@Event('demo')
async demo(msg, a) {
console.log(`comm当前进程的ID是: ${process.pid}`);
console.log('comm收到消息', msg, a);
}
/**
* 插件已就绪
*/
@Event(EVENT_PLUGIN_READY)
async pluginReady() {
// TODO 插件已就绪
}
}
@@ -0,0 +1,20 @@
import { BaseCoolQueue, CoolQueue } from '@cool-midway/task';
import { IMidwayApplication } from '@midwayjs/core';
import { App } from '@midwayjs/core';
/**
* 普通队列
*/
@CoolQueue()
export class DemoCommQueue extends BaseCoolQueue {
@App()
app: IMidwayApplication;
async data(job: any, done: any): Promise<void> {
// 这边可以执行定时任务具体的业务或队列的业务
console.log('数据', job.data);
// 抛出错误 可以让队列重试,默认重试5次
//throw new Error('错误');
done();
}
}
@@ -0,0 +1,7 @@
import { BaseCoolQueue, CoolQueue } from '@cool-midway/task';
/**
* 主动消费队列
*/
@CoolQueue({ type: 'getter' })
export class DemoGetterQueue extends BaseCoolQueue {}
@@ -0,0 +1,20 @@
import { BaseCoolQueue, CoolQueue } from '@cool-midway/task';
import { IMidwayApplication } from '@midwayjs/core';
import { App } from '@midwayjs/core';
/**
* 单例队列,cluster 或 集群模式下 只会有一个实例消费数据
*/
@CoolQueue({ type: 'single' })
export class DemoSingleQueue extends BaseCoolQueue {
@App()
app: IMidwayApplication;
async data(job: any, done: any): Promise<void> {
// 这边可以执行定时任务具体的业务或队列的业务
console.log('数据', job.data);
// 抛出错误 可以让队列重试,默认重试5次
//throw new Error('错误');
done();
}
}
@@ -0,0 +1,18 @@
import { Provide } from '@midwayjs/core';
import { CoolCache } from '@cool-midway/core';
/**
* 缓存
*/
@Provide()
export class DemoCacheService {
// 数据缓存5秒
@CoolCache(5000)
async get() {
console.log('执行方法');
return {
a: 1,
b: 2,
};
}
}
@@ -0,0 +1,43 @@
import { DemoGoodsEntity } from './../entity/goods';
import { Inject, Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
/**
* 商品示例
*/
@Provide()
export class DemoGoodsService extends BaseService {
@InjectEntityModel(DemoGoodsEntity)
demoGoodsEntity: Repository<DemoGoodsEntity>;
@Inject()
ctx;
/**
* 执行sql分页
*/
async sqlPage(query) {
await this.demoGoodsEntity.save({
id: 1,
title: '标题',
price: 99.0,
description: '商品描述',
mainImage: 'https://cool-js.com/logo.png',
});
return this.sqlRenderPage(
'select * from demo_goods ORDER BY id ASC',
query,
false
);
}
/**
* 执行entity分页
*/
async entityPage(query) {
const find = this.demoGoodsEntity.createQueryBuilder();
return this.entityRenderPage(find, query);
}
}
@@ -0,0 +1,29 @@
import { Inject, Provide } from '@midwayjs/core';
import { BaseTranslateService } from '../../base/service/translate';
/**
* 国际化服务
*/
@Provide()
export class DemoI18nService {
@Inject()
translate: BaseTranslateService;
/**
* 翻译成英文
*/
async en() {
const value = this.translate.comm('一个很Cool的框架')['en'];
console.log(value);
return value;
}
/**
* 翻译成繁体
*/
async tw() {
const value = this.translate.comm('一个很Cool的框架')['zh-tw'];
console.log(value);
return value;
}
}
@@ -0,0 +1,70 @@
import { App, Provide } from '@midwayjs/core';
import { DemoGoodsEntity } from '../entity/goods';
import { IMidwayApplication, Inject } from '@midwayjs/core';
import {
BaseRpcService,
CoolRpc,
CoolRpcService,
CoolRpcTransaction,
} from '@cool-midway/rpc';
import { QueryRunner } from 'typeorm';
@Provide()
@CoolRpcService({
entity: DemoGoodsEntity,
method: ['info', 'add', 'page'],
})
export class DemoRpcService extends BaseRpcService {
@App()
app: IMidwayApplication;
@Inject()
rpc: CoolRpc;
/**
* 远程调用
* @returns
*/
async call() {
return await this.rpc.call('goods', 'demoGoodsService', 'test', {
a: 1,
});
}
/**
* 集群事件
*/
async event() {
this.rpc.event('test', { a: 1 });
}
async info(params) {
return params;
}
async getUser() {
return {
uid: '123',
username: 'mockedName',
phone: '12345678901',
email: 'xxx.xxx@xxx.com',
};
}
@CoolRpcTransaction()
async transaction(params, rpcTransactionId?, queryRunner?: QueryRunner) {
console.log('获得的参数', params);
const data = {
title: '商品标题',
pic: 'https://xxx',
price: 99.0,
type: 1,
};
await queryRunner.manager.save(DemoGoodsEntity, data);
// 将事务id传给调用的远程服务方法
await this.rpc.call('goods', 'demoGoodsService', 'transaction', {
rpcTransactionId,
...params,
});
}
}
@@ -0,0 +1,50 @@
import { Inject, Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { DemoGoodsEntity } from '../entity/goods';
import { noTenant } from '../../base/db/tenant';
/**
* 商品服务
*/
@Provide()
export class DemoTenantService extends BaseService {
@InjectEntityModel(DemoGoodsEntity)
demoGoodsEntity: Repository<DemoGoodsEntity>;
@Inject()
ctx;
/**
* 使用多租户
*/
async use() {
await this.demoGoodsEntity.createQueryBuilder().getMany();
await this.demoGoodsEntity.find();
}
/**
* 不使用多租户(局部不使用)
*/
async noUse() {
// 过滤多租户
await this.demoGoodsEntity.createQueryBuilder().getMany();
// 被noTenant包裹,不会过滤多租户
await noTenant(this.ctx, async () => {
return await this.demoGoodsEntity.createQueryBuilder().getMany();
});
// 过滤多租户
await this.demoGoodsEntity.find();
}
/**
* 无效多租户
*/
async invalid() {
// 自定义sql,不进行多租户过滤
await this.nativeQuery('select * from demo_goods');
// 自定义分页sql,不进行多租户过滤
await this.sqlRenderPage('select * from demo_goods');
}
}
@@ -0,0 +1,23 @@
import { DemoGoodsEntity } from './../entity/goods';
import { Provide } from '@midwayjs/core';
import { BaseService, CoolTransaction } from '@cool-midway/core';
import { QueryRunner } from 'typeorm';
/**
* 操作事务
*/
@Provide()
export class DemoTransactionService extends BaseService {
/**
* 事务操作
*/
@CoolTransaction({
connectionName: 'default',
})
async add(param, queryRunner?: QueryRunner) {
await queryRunner.manager.insert<DemoGoodsEntity>(DemoGoodsEntity, param);
return {
id: param.id,
};
}
}

Some files were not shown because too many files have changed in this diff Show More