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`);
}
}