diff --git a/.eslintrc.json b/.eslintrc.json index 8d20e22..a5bb461 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -1,7 +1,22 @@ { "extends": "./node_modules/mwts/", - "ignorePatterns": ["node_modules", "dist", "test", "jest.config.js", "typings"], + "ignorePatterns": [ + "node_modules", + "dist", + "test", + "jest.config.js", + "typings", + "src/app/public/**/**", + "src/app/view/**/**" + ], "env": { "jest": true + }, + "rules": { + "@typescript-eslint/explicit-module-boundary-types": "off", + "@typescript-eslint/no-unused-vars": "off", + "node/no-extraneous-import": "off", + "no-empty": "off", + "node/no-extraneous-require": "off" } } diff --git a/bootstrap.js b/bootstrap.js index b38098c..abb687a 100644 --- a/bootstrap.js +++ b/bootstrap.js @@ -1,7 +1,7 @@ const WebFramework = require('@midwayjs/web').Framework; const web = new WebFramework().configure({ - port: 8001, + port: 8001, }); const { Bootstrap } = require('@midwayjs/bootstrap'); -Bootstrap.load(web).run(); \ No newline at end of file +Bootstrap.load(web).run(); diff --git a/package.json b/package.json index 1444b5e..da4fb52 100755 --- a/package.json +++ b/package.json @@ -14,6 +14,8 @@ "jsonwebtoken": "^8.5.1", "md5": "^2.3.0", "midwayjs-cool-core": "/Users/ap/Documents/srcs/cool-admin/midway-core/core/dist", + "midwayjs-cool-oss": "^1.0.0", + "midwayjs-cool-redis": "/Users/ap/Documents/srcs/cool-admin/midway-core/redis/dist", "mysql2": "^2.2.5", "svg-captcha": "^1.4.0", "svg-to-dataurl": "^1.0.0" diff --git a/src/app/comm/utils.ts b/src/app/comm/utils.ts index d5d0a4b..3b06452 100644 --- a/src/app/comm/utils.ts +++ b/src/app/comm/utils.ts @@ -8,60 +8,62 @@ import { Context } from 'egg'; */ @Provide() export class Utils { + @Inject() + baseDir; - @Inject() - baseDir; + /** + * 获得请求IP + */ + async getReqIP(ctx: Context) { + const req = ctx.req; + return ( + req.headers['x-forwarded-for'] || + req.socket.remoteAddress.replace('::ffff:', '') + ); + } - /** - * 获得请求IP - */ - async getReqIP(ctx: Context) { - const req = ctx.req; - return req.headers['x-forwarded-for'] || req.socket.remoteAddress.replace('::ffff:', ''); + /** + * 根据IP获得请求地址 + * @param ip 为空时则为当前请求的IP地址 + */ + async getIpAddr(ctx: Context, ip?: string | string[]) { + try { + if (!ip) { + ip = await this.getReqIP(ctx); + } + const bst = new ipdb.BaseStation( + `${this.baseDir}/app/comm/ipipfree.ipdb` + ); + const result = bst.findInfo(ip, 'CN'); + const addArr: any = []; + if (result) { + addArr.push(result.countryName); + addArr.push(result.regionName); + addArr.push(result.cityName); + return _.uniq(addArr).join(''); + } + } catch (err) { + return '无法获取地址信息'; } + } - /** - * 根据IP获得请求地址 - * @param ip 为空时则为当前请求的IP地址 - */ - async getIpAddr(ctx: Context, ip?: string | string[]) { - try { - if (!ip) { - ip = await this.getReqIP(ctx); - } - const bst = new ipdb.BaseStation(`${this.baseDir}/app/comm/ipipfree.ipdb`); - const result = bst.findInfo(ip, 'CN'); - const addArr: any = []; - if (result) { - addArr.push(result.countryName); - addArr.push(result.regionName); - addArr.push(result.cityName); - return _.uniq(addArr).join(''); - } - // @ts-ignore - } catch (err) { - console.log(err) - return '无法获取地址信息'; - } - } + /** + * 去除对象的空值属性 + * @param obj + */ + async removeEmptyP(obj) { + Object.keys(obj).forEach(key => { + if (obj[key] === null || obj[key] === '' || obj[key] === 'undefined') { + delete obj[key]; + } + }); + } - /** - * 去除对象的空值属性 - * @param obj - */ - async removeEmptyP(obj) { - Object.keys(obj).forEach(key => { - if (obj[key] === null || obj[key] === '' || obj[key] === 'undefined') { - delete obj[key]; - } - }); - } - - /** - * 线程阻塞毫秒数 - * @param ms - */ - sleep(ms) { - return new Promise(resolve => setTimeout(resolve, ms)); - } + /** + * 线程阻塞毫秒数 + * @param ms + */ + sleep(ms) { + return new Promise(resolve => setTimeout(resolve, ms)); + } } diff --git a/src/app/modules/base/config.ts b/src/app/modules/base/config.ts index 5b1fca0..db02092 100644 --- a/src/app/modules/base/config.ts +++ b/src/app/modules/base/config.ts @@ -1,16 +1,16 @@ -import { Application } from "egg"; +import { Application } from 'egg'; import { ModuleConfig } from 'midwayjs-cool-core'; /** * 模块的配置 */ export default (app: Application) => { - return { - // 模块名称 - name: '权限管理', - // 模块描述 - description: '基础的权限管理功能,包括登录,权限校验', - // 中间件 - middlewares: ['baseAuthorityMiddleware', 'baseLogMiddleware'], - } as ModuleConfig; + return { + // 模块名称 + name: '权限管理', + // 模块描述 + description: '基础的权限管理功能,包括登录,权限校验', + // 中间件 + middlewares: ['baseAuthorityMiddleware', 'baseLogMiddleware'], + } as ModuleConfig; }; diff --git a/src/app/modules/base/controller/admin/comm.ts b/src/app/modules/base/controller/admin/comm.ts index 10ac8d3..c97cc14 100644 --- a/src/app/modules/base/controller/admin/comm.ts +++ b/src/app/modules/base/controller/admin/comm.ts @@ -12,70 +12,70 @@ import { BaseSysUserService } from '../../service/sys/user'; @Provide() @CoolController() export class BaseCommController extends BaseController { + @Inject() + baseSysUserService: BaseSysUserService; - @Inject() - baseSysUserService: BaseSysUserService; + @Inject() + baseSysPermsService: BaseSysPermsService; - @Inject() - baseSysPermsService: BaseSysPermsService; + @Inject() + baseSysLoginService: BaseSysLoginService; - @Inject() - baseSysLoginService: BaseSysLoginService; + @Inject() + ctx: Context; - @Inject() - ctx: Context; + @Inject('cool:file') + coolFile: CoolFile; - @Inject('cool:file') - coolFile: CoolFile; + /** + * 获得个人信息 + */ + @Get('/person') + async person() { + return this.ok(await this.baseSysUserService.person()); + } - /** - * 获得个人信息 - */ - @Get('/person') - async person() { - return this.ok(await this.baseSysUserService.person()); - } + /** + * 修改个人信息 + */ + @Post('/personUpdate') + async personUpdate(@Body(ALL) user: BaseSysUserEntity) { + await this.baseSysUserService.personUpdate(user); + return this.ok(); + } - /** - * 修改个人信息 - */ - @Post('/personUpdate') - async personUpdate(@Body(ALL) user: BaseSysUserEntity) { - await this.baseSysUserService.personUpdate(user); - return this.ok(); - } + /** + * 权限菜单 + */ + @Get('/permmenu') + async permmenu() { + return this.ok( + await this.baseSysPermsService.permmenu(this.ctx.admin.roleIds) + ); + } - /** - * 权限菜单 - */ - @Get('/permmenu') - async permmenu() { - return this.ok(await this.baseSysPermsService.permmenu(this.ctx.admin.roleIds)); - } + /** + * 文件上传 + */ + @Post('/upload') + async upload() { + return this.ok(await this.coolFile.upload(this.ctx)); + } - /** - * 文件上传 - */ - @Post('/upload') - async upload() { - return this.ok(await this.coolFile.upload(this.ctx)); - } + /** + * 文件上传模式,本地或者云存储 + */ + @Get('/uploadMode') + async uploadMode() { + return this.ok(this.coolFile.getMode()); + } - /** - * 文件上传模式,本地或者云存储 - */ - @Get('/uploadMode') - async uploadMode() { - return this.ok(this.coolFile.getMode()); - } - - /** - * 退出 - */ - @Post('/logout') - async logout() { - await this.baseSysLoginService.logout(); - return this.ok(); - } - -} \ No newline at end of file + /** + * 退出 + */ + @Post('/logout') + async logout() { + await this.baseSysLoginService.logout(); + return this.ok(); + } +} diff --git a/src/app/modules/base/controller/admin/open.ts b/src/app/modules/base/controller/admin/open.ts index 7222688..0455596 100644 --- a/src/app/modules/base/controller/admin/open.ts +++ b/src/app/modules/base/controller/admin/open.ts @@ -1,4 +1,12 @@ -import { Provide, Body, ALL, Inject, Post, Get, Query } from '@midwayjs/decorator'; +import { + Provide, + Body, + ALL, + Inject, + Post, + Get, + Query, +} from '@midwayjs/decorator'; import { Context } from 'egg'; import { CoolController, BaseController } from 'midwayjs-cool-core'; import { LoginDTO } from '../../dto/login'; @@ -11,46 +19,49 @@ import { BaseSysParamService } from '../../service/sys/param'; @Provide() @CoolController() export class BaseSysOpenController extends BaseController { + @Inject() + baseSysLoginService: BaseSysLoginService; - @Inject() - baseSysLoginService: BaseSysLoginService; + @Inject() + baseSysParamService: BaseSysParamService; - @Inject() - baseSysParamService: BaseSysParamService; + @Inject() + ctx: Context; - @Inject() - ctx: Context; + /** + * 根据配置参数key获得网页内容(富文本) + */ + @Get('/html') + async htmlByKey(@Query() key: string) { + this.ctx.body = await this.baseSysParamService.htmlByKey(key); + } - /** - * 根据配置参数key获得网页内容(富文本) - */ - @Get('/html') - async htmlByKey(@Query() key: string) { - this.ctx.body = await this.baseSysParamService.htmlByKey(key); - } + /** + * 登录 + * @param login + */ + @Post('/login') + async login(@Body(ALL) login: LoginDTO) { + return this.ok(await this.baseSysLoginService.login(login)); + } - /** - * 登录 - * @param login - */ - @Post('/login') - async login(@Body(ALL) login: LoginDTO) { - return this.ok(await this.baseSysLoginService.login(login)) - } + /** + * 获得验证码 + */ + @Get('/captcha') + async captcha( + @Query() type: string, + @Query() width: number, + @Query() height: number + ) { + return this.ok(await this.baseSysLoginService.captcha(type, width, height)); + } - /** - * 获得验证码 - */ - @Get('/captcha') - async captcha(@Query() type: string, @Query() width: number, @Query() height: number) { - return this.ok(await this.baseSysLoginService.captcha(type, width, height)); - } - - /** - * 刷新token - */ - @Get('/refreshToken') - async refreshToken(@Query() refreshToken: string) { - return this.ok(await this.baseSysLoginService.refreshToken(refreshToken)) - } -} \ No newline at end of file + /** + * 刷新token + */ + @Get('/refreshToken') + async refreshToken(@Query() refreshToken: string) { + return this.ok(await this.baseSysLoginService.refreshToken(refreshToken)); + } +} diff --git a/src/app/modules/base/controller/admin/plugin/info.ts b/src/app/modules/base/controller/admin/plugin/info.ts index 0448d4e..305f374 100644 --- a/src/app/modules/base/controller/admin/plugin/info.ts +++ b/src/app/modules/base/controller/admin/plugin/info.ts @@ -8,45 +8,44 @@ import { BasePluginInfoService } from '../../../service/plugin/info'; @Provide() @CoolController() export class BasePluginInfoController extends BaseController { + @Inject() + basePluginInfoService: BasePluginInfoService; + /** + * 插件列表 + */ + @Post('/list') + async list(@Body() keyWord: string) { + return this.ok(await this.basePluginInfoService.list(keyWord)); + } - @Inject() - basePluginInfoService: BasePluginInfoService; - /** - * 插件列表 - */ - @Post('/list') - async list(@Body() keyWord: string) { - return this.ok(await this.basePluginInfoService.list(keyWord)) - } + /** + * 配置 + * @param namespace + * @param config + */ + @Post('/config') + async config(@Body() namespace: string, @Body() config: any) { + await this.basePluginInfoService.config(namespace, config); + return this.ok(); + } - /** - * 配置 - * @param namespace - * @param config - */ - @Post('/config') - async config(@Body() namespace: string, @Body() config: any) { - await this.basePluginInfoService.config(namespace, config); - return this.ok(); - } + /** + * 配置 + * @param namespace + * @param config + */ + @Get('/getConfig') + async getConfig(@Query() namespace: string) { + return this.ok(await this.basePluginInfoService.getConfig(namespace)); + } - /** - * 配置 - * @param namespace - * @param config - */ - @Get('/getConfig') - async getConfig(@Query() namespace: string) { - return this.ok(await this.basePluginInfoService.getConfig(namespace)); - } - - /** - * 启用插件 - * @param enable - */ - @Post('/enable') - async enable(@Body() namespace: string, @Body() enable: number) { - await this.basePluginInfoService.enable(namespace, enable); - return this.ok(); - } -} \ No newline at end of file + /** + * 启用插件 + * @param enable + */ + @Post('/enable') + async enable(@Body() namespace: string, @Body() enable: number) { + await this.basePluginInfoService.enable(namespace, enable); + return this.ok(); + } +} diff --git a/src/app/modules/base/controller/admin/sys/department.ts b/src/app/modules/base/controller/admin/sys/department.ts index bf3d776..488437e 100644 --- a/src/app/modules/base/controller/admin/sys/department.ts +++ b/src/app/modules/base/controller/admin/sys/department.ts @@ -8,22 +8,20 @@ import { BaseSysDepartmentService } from '../../../service/sys/department'; */ @Provide() @CoolController({ - api: ['add', 'delete', 'update', 'list'], - entity: BaseSysDepartmentEntity, - service: BaseSysDepartmentService + api: ['add', 'delete', 'update', 'list'], + entity: BaseSysDepartmentEntity, + service: BaseSysDepartmentService, }) export class BaseDepartmentController extends BaseController { + @Inject() + baseDepartmentService: BaseSysDepartmentService; - @Inject() - baseDepartmentService: BaseSysDepartmentService; - - /** - * 部门排序 - */ - @Post('/order') - async order(@Body(ALL) params: Object) { - await this.baseDepartmentService.order(params); - return this.ok(); - } - -} \ No newline at end of file + /** + * 部门排序 + */ + @Post('/order') + async order(@Body(ALL) params: any) { + await this.baseDepartmentService.order(params); + return this.ok(); + } +} diff --git a/src/app/modules/base/controller/admin/sys/log.ts b/src/app/modules/base/controller/admin/sys/log.ts index 023bafa..aff40a3 100644 --- a/src/app/modules/base/controller/admin/sys/log.ts +++ b/src/app/modules/base/controller/admin/sys/log.ts @@ -10,51 +10,50 @@ import { BaseSysLogService } from '../../../service/sys/log'; */ @Provide() @CoolController({ - api: ['page'], - entity: BaseSysLogEntity, - pageQueryOp: { - keyWordLikeFields: ['b.name', 'a.params', 'a.ipAddr'], - select: ['a.*, b.name'], - leftJoin: [{ - entity: BaseSysUserEntity, - alias: 'b', - condition: 'a.userId = b.id' - }] - } + api: ['page'], + entity: BaseSysLogEntity, + pageQueryOp: { + keyWordLikeFields: ['b.name', 'a.params', 'a.ipAddr'], + select: ['a.*, b.name'], + leftJoin: [ + { + entity: BaseSysUserEntity, + alias: 'b', + condition: 'a.userId = b.id', + }, + ], + }, }) export class BaseSysLogController extends BaseController { + @Inject() + baseSysLogService: BaseSysLogService; - @Inject() - baseSysLogService: BaseSysLogService; + @Inject() + baseSysConfService: BaseSysConfService; - @Inject() - baseSysConfService: BaseSysConfService; + /** + * 清空日志 + */ + @Post('/clear') + public async clear() { + await this.baseSysLogService.clear(true); + return this.ok(); + } - /** - * 清空日志 - */ - @Post('/clear') - public async clear() { - await this.baseSysLogService.clear(true); - return this.ok(); - } + /** + * 设置日志保存时间 + */ + @Post('/setKeep') + public async setKeep(@Body() value: number) { + await this.baseSysConfService.updateVaule('logKeep', value); + return this.ok(); + } - - /** - * 设置日志保存时间 - */ - @Post('/setKeep') - public async setKeep(@Body() value: number) { - await this.baseSysConfService.updateVaule('logKeep', value); - return this.ok(); - } - - /** - * 获得日志保存时间 - */ - @Get('/getKeep') - public async getKeep() { - return this.ok(await this.baseSysConfService.getValue('logKeep')); - } - -} \ No newline at end of file + /** + * 获得日志保存时间 + */ + @Get('/getKeep') + public async getKeep() { + return this.ok(await this.baseSysConfService.getValue('logKeep')); + } +} diff --git a/src/app/modules/base/controller/admin/sys/menu.ts b/src/app/modules/base/controller/admin/sys/menu.ts index 9f26945..193226b 100644 --- a/src/app/modules/base/controller/admin/sys/menu.ts +++ b/src/app/modules/base/controller/admin/sys/menu.ts @@ -8,13 +8,11 @@ import { BaseSysMenuService } from '../../../service/sys/menu'; */ @Provide() @CoolController({ - api: ['add', 'delete', 'update', 'info', 'list', 'page'], - entity: BaseSysMenuEntity, - service: BaseSysMenuService + api: ['add', 'delete', 'update', 'info', 'list', 'page'], + entity: BaseSysMenuEntity, + service: BaseSysMenuService, }) export class BaseSysMenuController extends BaseController { - - @Inject() - baseSysMenuService: BaseSysMenuService; - -} \ No newline at end of file + @Inject() + baseSysMenuService: BaseSysMenuService; +} diff --git a/src/app/modules/base/controller/admin/sys/param.ts b/src/app/modules/base/controller/admin/sys/param.ts index 56d7649..07ba439 100644 --- a/src/app/modules/base/controller/admin/sys/param.ts +++ b/src/app/modules/base/controller/admin/sys/param.ts @@ -9,26 +9,24 @@ import { BaseSysParamService } from '../../../service/sys/param'; */ @Provide() @CoolController({ - api: ['add', 'delete', 'update', 'info', 'page'], - entity: BaseSysParamEntity, - pageQueryOp: { - keyWordLikeFields: ['name', 'keyName'] - } + api: ['add', 'delete', 'update', 'info', 'page'], + entity: BaseSysParamEntity, + pageQueryOp: { + keyWordLikeFields: ['name', 'keyName'], + }, }) export class BaseSysParamController extends BaseController { + @Inject() + baseSysParamService: BaseSysParamService; - @Inject() - baseSysParamService: BaseSysParamService; + @Inject() + ctx: Context; - @Inject() - ctx: Context; - - /** - * 根据配置参数key获得网页内容(富文本) - */ - @Get('/html') - async htmlByKey(@Query() key: string) { - this.ctx.body = await this.baseSysParamService.htmlByKey(key); - } - -} \ No newline at end of file + /** + * 根据配置参数key获得网页内容(富文本) + */ + @Get('/html') + async htmlByKey(@Query() key: string) { + this.ctx.body = await this.baseSysParamService.htmlByKey(key); + } +} diff --git a/src/app/modules/base/controller/admin/sys/role.ts b/src/app/modules/base/controller/admin/sys/role.ts index 837595e..00dbe4f 100644 --- a/src/app/modules/base/controller/admin/sys/role.ts +++ b/src/app/modules/base/controller/admin/sys/role.ts @@ -13,24 +13,26 @@ import { BaseSysRoleService } from '../../../service/sys/role'; entity: BaseSysRoleEntity, service: BaseSysRoleService, // 新增的时候插入当前用户ID - insertParam: (async (ctx: Context) => { + insertParam: async (ctx: Context) => { return { - userId: ctx.admin.userId - } - }), + userId: ctx.admin.userId, + }; + }, pageQueryOp: { keyWordLikeFields: ['name', 'label'], - where: (async (ctx: Context) => { + where: async (ctx: Context) => { const { userId, roleIds, role } = ctx.admin; return [ // 超级管理员的角色不展示 ['label != :label', { label: 'admin' }], // 如果不是超管,只能看到自己新建的或者自己有的角色 - ['(userId=:userId or id in (:roleIds))', { userId, roleIds }, role != 'admin'] - ] - }) - } + [ + '(userId=:userId or id in (:roleIds))', + { userId, roleIds }, + role !== 'admin', + ], + ]; + }, + }, }) -export class BaseSysRoleController extends BaseController { - -} \ No newline at end of file +export class BaseSysRoleController extends BaseController {} diff --git a/src/app/modules/base/controller/admin/sys/user.ts b/src/app/modules/base/controller/admin/sys/user.ts index 105bcc9..4e3c8b5 100644 --- a/src/app/modules/base/controller/admin/sys/user.ts +++ b/src/app/modules/base/controller/admin/sys/user.ts @@ -8,22 +8,20 @@ import { BaseSysUserService } from '../../../service/sys/user'; */ @Provide() @CoolController({ - api: ['add', 'delete', 'update', 'info', 'list', 'page'], - entity: BaseSysUserEntity, - service: BaseSysUserService + api: ['add', 'delete', 'update', 'info', 'list', 'page'], + entity: BaseSysUserEntity, + service: BaseSysUserService, }) export class BaseSysUserController extends BaseController { + @Inject() + baseSysUserService: BaseSysUserService; - @Inject() - baseSysUserService: BaseSysUserService; - - /** - * 移动部门 - */ - @Post('/move') - async move(@Body() departmentId: number, @Body() userIds: []) { - await this.baseSysUserService.move(departmentId, userIds); - return this.ok(); - } - -} \ No newline at end of file + /** + * 移动部门 + */ + @Post('/move') + async move(@Body() departmentId: number, @Body() userIds: []) { + await this.baseSysUserService.move(departmentId, userIds); + return this.ok(); + } +} diff --git a/src/app/modules/base/dto/login.ts b/src/app/modules/base/dto/login.ts index ce18b85..860c94b 100644 --- a/src/app/modules/base/dto/login.ts +++ b/src/app/modules/base/dto/login.ts @@ -3,20 +3,19 @@ import { Rule, RuleType } from '@midwayjs/decorator'; * 登录参数校验 */ export class LoginDTO { - // 用户名 - @Rule(RuleType.string().required()) - username: string; + // 用户名 + @Rule(RuleType.string().required()) + username: string; - // 密码 - @Rule(RuleType.string().required()) - password: number; + // 密码 + @Rule(RuleType.string().required()) + password: number; - // 验证码ID - @Rule(RuleType.string().required()) - captchaId: string; + // 验证码ID + @Rule(RuleType.string().required()) + captchaId: string; - // 验证码 - @Rule(RuleType.string().required()) - verifyCode: number; - -} \ No newline at end of file + // 验证码 + @Rule(RuleType.string().required()) + verifyCode: number; +} diff --git a/src/app/modules/base/entity/app/space/info.ts b/src/app/modules/base/entity/app/space/info.ts index 3273617..4852358 100644 --- a/src/app/modules/base/entity/app/space/info.ts +++ b/src/app/modules/base/entity/app/space/info.ts @@ -7,14 +7,12 @@ import { Column } from 'typeorm'; */ @EntityModel('base_app_space_info') export class BaseAppSpaceInfoEntity extends BaseEntity { + @Column({ comment: '地址' }) + url: string; - @Column({comment: '地址'}) - url: string; + @Column({ comment: '类型' }) + type: string; - @Column({comment: '类型'}) - type: string; - - @Column({comment:'分类ID', type: 'bigint', nullable: true }) - classifyId: number; - -} \ No newline at end of file + @Column({ comment: '分类ID', type: 'bigint', nullable: true }) + classifyId: number; +} diff --git a/src/app/modules/base/entity/app/space/type.ts b/src/app/modules/base/entity/app/space/type.ts index c9f6e05..6a076d6 100644 --- a/src/app/modules/base/entity/app/space/type.ts +++ b/src/app/modules/base/entity/app/space/type.ts @@ -7,11 +7,9 @@ import { Column } from 'typeorm'; */ @EntityModel('base_app_space_type') export class BaseAppSpaceTypeEntity extends BaseEntity { + @Column({ comment: '类别名称' }) + name: string; - @Column({ comment: '类别名称' }) - name: string; - - @Column({ comment: '父分类ID', type: 'tinyint', nullable: true }) - parentId: number; - -} \ No newline at end of file + @Column({ comment: '父分类ID', type: 'tinyint', nullable: true }) + parentId: number; +} diff --git a/src/app/modules/base/entity/sys/conf.ts b/src/app/modules/base/entity/sys/conf.ts index 40a93cb..145ec99 100644 --- a/src/app/modules/base/entity/sys/conf.ts +++ b/src/app/modules/base/entity/sys/conf.ts @@ -7,11 +7,10 @@ import { BaseEntity } from 'midwayjs-cool-core'; */ @EntityModel('base_sys_conf') export class BaseSysConfEntity extends BaseEntity { + @Index({ unique: true }) + @Column({ comment: '配置键' }) + cKey: string; - @Index({ unique: true }) - @Column({ comment: '配置键' }) - cKey: string; - - @Column({ comment: '配置值' }) - cValue: string; + @Column({ comment: '配置值' }) + cValue: string; } diff --git a/src/app/modules/base/entity/sys/department.ts b/src/app/modules/base/entity/sys/department.ts index b56c636..08d707d 100644 --- a/src/app/modules/base/entity/sys/department.ts +++ b/src/app/modules/base/entity/sys/department.ts @@ -7,16 +7,14 @@ import { Column } from 'typeorm'; */ @EntityModel('base_sys_department') export class BaseSysDepartmentEntity extends BaseEntity { + @Column({ comment: '部门名称' }) + name: string; - @Column({ comment: '部门名称' }) - name: string; + @Column({ comment: '上级部门ID', type: 'bigint', nullable: true }) + parentId: number; - @Column({ comment: '上级部门ID', type: 'bigint', nullable: true }) - parentId: number; - - @Column({ comment: '排序', default: 0 }) - orderNum: number; - // 父菜单名称 - parentName: string; - -} \ No newline at end of file + @Column({ comment: '排序', default: 0 }) + orderNum: number; + // 父菜单名称 + parentName: string; +} diff --git a/src/app/modules/base/entity/sys/log.ts b/src/app/modules/base/entity/sys/log.ts index f2663bf..11b435c 100644 --- a/src/app/modules/base/entity/sys/log.ts +++ b/src/app/modules/base/entity/sys/log.ts @@ -7,24 +7,22 @@ import { Column, Index } from 'typeorm'; */ @EntityModel('base_sys_log') export class BaseSysLogEntity extends BaseEntity { + @Index() + @Column({ comment: '用户ID', nullable: true, type: 'bigint' }) + userId: number; - @Index() - @Column({ comment: '用户ID', nullable: true, type: 'bigint' }) - userId: number; + @Index() + @Column({ comment: '行为', length: 100 }) + action: string; - @Index() - @Column({ comment: '行为', length: 100 }) - action: string; + @Index() + @Column({ comment: 'ip', nullable: true, length: 50 }) + ip: string; - @Index() - @Column({ comment: 'ip', nullable: true, length: 50 }) - ip: string; - - @Index() - @Column({ comment: 'ip地址', nullable: true, length: 50 }) - ipAddr: string; - - @Column({ comment: '参数', nullable: true, type: 'text' }) - params: string; + @Index() + @Column({ comment: 'ip地址', nullable: true, length: 50 }) + ipAddr: string; + @Column({ comment: '参数', nullable: true, type: 'text' }) + params: string; } diff --git a/src/app/modules/base/entity/sys/menu.ts b/src/app/modules/base/entity/sys/menu.ts index dc34eeb..8e8d20f 100644 --- a/src/app/modules/base/entity/sys/menu.ts +++ b/src/app/modules/base/entity/sys/menu.ts @@ -7,41 +7,43 @@ import { Column } from 'typeorm'; */ @EntityModel('base_sys_menu') export class BaseSysMenuEntity extends BaseEntity { + @Column({ comment: '父菜单ID', type: 'bigint', nullable: true }) + parentId: number; - @Column({ comment: '父菜单ID', type: 'bigint', nullable: true }) - parentId: number; + @Column({ comment: '菜单名称' }) + name: string; - @Column({ comment: '菜单名称' }) - name: string; + @Column({ comment: '菜单地址', nullable: true }) + router: string; - @Column({ comment: '菜单地址', nullable: true }) - router: string; + @Column({ comment: '权限标识', nullable: true }) + perms: string; - @Column({ comment: '权限标识', nullable: true }) - perms: string; + @Column({ + comment: '类型 0:目录 1:菜单 2:按钮', + default: 0, + type: 'tinyint', + }) + type: number; - @Column({ comment: '类型 0:目录 1:菜单 2:按钮', default: 0, type: 'tinyint' }) - type: number; + @Column({ comment: '图标', nullable: true }) + icon: string; - @Column({ comment: '图标', nullable: true }) - icon: string; + @Column({ comment: '排序', default: 0 }) + orderNum: number; - @Column({ comment: '排序', default: 0 }) - orderNum: number; + @Column({ comment: '视图地址', nullable: true }) + viewPath: string; - @Column({ comment: '视图地址', nullable: true }) - viewPath: string; + @Column({ comment: '路由缓存', default: true }) + keepAlive: boolean; - @Column({ comment: '路由缓存', default: true }) - keepAlive: boolean; + // 父菜单名称 + parentName: string; - // 父菜单名称 - parentName: string; + @Column({ comment: '父菜单名称', default: true }) + isShow: boolean; - @Column({ comment: '父菜单名称', default: true }) - isShow: boolean; - - @Column({ comment: '模块名', nullable: true }) - moduleName: string; - -} \ No newline at end of file + @Column({ comment: '模块名', nullable: true }) + moduleName: string; +} diff --git a/src/app/modules/base/entity/sys/param.ts b/src/app/modules/base/entity/sys/param.ts index de38552..96628b3 100644 --- a/src/app/modules/base/entity/sys/param.ts +++ b/src/app/modules/base/entity/sys/param.ts @@ -7,21 +7,23 @@ import { Column, Index } from 'typeorm'; */ @EntityModel('base_sys_param') export class BaseSysParamEntity extends BaseEntity { + @Index() + @Column({ comment: '键位' }) + keyName: string; - @Index() - @Column({ comment: '键位' }) - keyName: string; - - @Column({comment: '名称'}) - name: string; + @Column({ comment: '名称' }) + name: string; - @Column({comment: '数据', type: 'text' }) - data: string; - - @Column({comment: '数据类型 0:字符串 1:数组 2:键值对', default: 0, type: 'tinyint' }) - dataType: number; - - @Column({ comment: '备注', nullable: true }) - remark: string; + @Column({ comment: '数据', type: 'text' }) + data: string; -} \ No newline at end of file + @Column({ + comment: '数据类型 0:字符串 1:数组 2:键值对', + default: 0, + type: 'tinyint', + }) + dataType: number; + + @Column({ comment: '备注', nullable: true }) + remark: string; +} diff --git a/src/app/modules/base/entity/sys/role.ts b/src/app/modules/base/entity/sys/role.ts index 08dfa61..91bed4d 100644 --- a/src/app/modules/base/entity/sys/role.ts +++ b/src/app/modules/base/entity/sys/role.ts @@ -7,22 +7,20 @@ import { Column, Index } from 'typeorm'; */ @EntityModel('base_sys_role') export class BaseSysRoleEntity extends BaseEntity { + @Column({ comment: '用户ID' }) + userId: string; - @Column({ comment: '用户ID' }) - userId: string; + @Index({ unique: true }) + @Column({ comment: '名称' }) + name: string; - @Index({ unique: true }) - @Column({ comment: '名称' }) - name: string; + @Index({ unique: true }) + @Column({ comment: '角色标签', nullable: true, length: 50 }) + label: string; - @Index({ unique: true }) - @Column({ comment: '角色标签', nullable: true, length: 50 }) - label: string; + @Column({ comment: '备注', nullable: true }) + remark: string; - @Column({ comment: '备注', nullable: true }) - remark: string; - - @Column({ comment: '数据权限是否关联上下级', default: 1 }) - relevance: number; - -} \ No newline at end of file + @Column({ comment: '数据权限是否关联上下级', default: 1 }) + relevance: number; +} diff --git a/src/app/modules/base/entity/sys/role_department.ts b/src/app/modules/base/entity/sys/role_department.ts index b65bf73..d6cc303 100644 --- a/src/app/modules/base/entity/sys/role_department.ts +++ b/src/app/modules/base/entity/sys/role_department.ts @@ -7,11 +7,9 @@ import { Column } from 'typeorm'; */ @EntityModel('base_sys_role_department') export class BaseSysRoleDepartmentEntity extends BaseEntity { + @Column({ comment: '角色ID', type: 'bigint' }) + roleId: number; - @Column({ comment: '角色ID', type: 'bigint' }) - roleId: number; - - @Column({ comment: '部门ID', type: 'bigint' }) - departmentId: number; - -} \ No newline at end of file + @Column({ comment: '部门ID', type: 'bigint' }) + departmentId: number; +} diff --git a/src/app/modules/base/entity/sys/role_menu.ts b/src/app/modules/base/entity/sys/role_menu.ts index 12dd273..131b328 100644 --- a/src/app/modules/base/entity/sys/role_menu.ts +++ b/src/app/modules/base/entity/sys/role_menu.ts @@ -7,11 +7,9 @@ import { Column } from 'typeorm'; */ @EntityModel('base_sys_role_menu') export class BaseSysRoleMenuEntity extends BaseEntity { + @Column({ comment: '角色ID', type: 'bigint' }) + roleId: number; - @Column({ comment: '角色ID', type: 'bigint' }) - roleId: number; - - @Column({ comment: '菜单ID', type: 'bigint' }) - menuId: number; - -} \ No newline at end of file + @Column({ comment: '菜单ID', type: 'bigint' }) + menuId: number; +} diff --git a/src/app/modules/base/entity/sys/user.ts b/src/app/modules/base/entity/sys/user.ts index d9f3d49..0e41eac 100644 --- a/src/app/modules/base/entity/sys/user.ts +++ b/src/app/modules/base/entity/sys/user.ts @@ -7,44 +7,46 @@ import { Column, Index } from 'typeorm'; */ @EntityModel('base_sys_user') export class BaseSysUserEntity extends BaseEntity { + @Index() + @Column({ comment: '部门ID', type: 'bigint', nullable: true }) + departmentId: number; - @Index() - @Column({ comment: '部门ID', type: 'bigint', nullable: true }) - departmentId: number; + @Column({ comment: '姓名', nullable: true }) + name: string; - @Column({ comment: '姓名', nullable: true }) - name: string; + @Index({ unique: true }) + @Column({ comment: '用户名', length: 100 }) + username: string; - @Index({ unique: true }) - @Column({ comment: '用户名', length: 100 }) - username: string; + @Column({ comment: '密码' }) + password: string; - @Column({ comment: '密码' }) - password: string; + @Column({ + comment: '密码版本, 作用是改完密码,让原来的token失效', + default: 1, + }) + passwordV: number; - @Column({ comment: '密码版本, 作用是改完密码,让原来的token失效', default: 1 }) - passwordV: number; + @Column({ comment: '昵称', nullable: true }) + nickName: string; - @Column({ comment: '昵称', nullable: true }) - nickName: string; + @Column({ comment: '头像', nullable: true }) + headImg: string; - @Column({ comment: '头像', nullable: true }) - headImg: string; + @Index() + @Column({ comment: '手机', nullable: true, length: 20 }) + phone: string; - @Index() - @Column({ comment: '手机', nullable: true, length: 20 }) - phone: string; + @Column({ comment: '邮箱', nullable: true }) + email: string; - @Column({ comment: '邮箱', nullable: true }) - email: string; + @Column({ comment: '备注', nullable: true }) + remark: string; - @Column({ comment: '备注', nullable: true }) - remark: string; - - @Column({ comment: '状态 0:禁用 1:启用', default: 1, type: 'tinyint' }) - status: number; - // 部门名称 - departmentName: string; - // 角色ID列表 - roleIdList: number[]; + @Column({ comment: '状态 0:禁用 1:启用', default: 1, type: 'tinyint' }) + status: number; + // 部门名称 + departmentName: string; + // 角色ID列表 + roleIdList: number[]; } diff --git a/src/app/modules/base/entity/sys/user_role.ts b/src/app/modules/base/entity/sys/user_role.ts index d8e7241..865762f 100644 --- a/src/app/modules/base/entity/sys/user_role.ts +++ b/src/app/modules/base/entity/sys/user_role.ts @@ -7,11 +7,9 @@ import { Column } from 'typeorm'; */ @EntityModel('base_sys_user_role') export class BaseSysUserRoleEntity extends BaseEntity { + @Column({ comment: '用户ID', type: 'bigint' }) + userId: number; - @Column({ comment: '用户ID', type: 'bigint' }) - userId: number; - - @Column({ comment: '角色ID', type: 'bigint' }) - roleId: number; - -} \ No newline at end of file + @Column({ comment: '角色ID', type: 'bigint' }) + roleId: number; +} diff --git a/src/app/modules/base/middleware/authority.ts b/src/app/modules/base/middleware/authority.ts index dca00b5..433f22e 100644 --- a/src/app/modules/base/middleware/authority.ts +++ b/src/app/modules/base/middleware/authority.ts @@ -10,93 +10,98 @@ import { Context } from 'egg'; */ @Provide() export class BaseAuthorityMiddleware implements IWebMiddleware { + @Config('cool') + coolConfig: CoolConfig; - @Config('cool') - coolConfig: CoolConfig; + @Inject('cool:cache') + coolCache: CoolCache; - @Inject('cool:cache') - coolCache: CoolCache; - - resolve() { - return async (ctx: Context, next: IMidwayWebNext) => { - let statusCode = 200; - const { url } = ctx; - const token = ctx.get('Authorization'); - let { prefix } = this.coolConfig.router; - const adminUrl = prefix ? `${prefix}/admin/` : '/admin/'; - // 路由地址为 admin前缀的 需要权限校验 - if (_.startsWith(url, adminUrl)) { - try { - ctx.admin = jwt.verify(token, this.coolConfig.jwt.secret); - } catch (err) { } - // 不需要登录 无需权限校验 - if (new RegExp(`^${adminUrl}?.*/open/`).test(url)) { - await next(); - return; - } - if (ctx.admin) { - // 要登录每个人都有权限的接口 - if (new RegExp(`^${adminUrl}?.*/comm/`).test(url)) { - await next(); - return; - } - // 如果传的token是refreshToken则校验失败 - if (ctx.admin.isRefresh) { - ctx.status = 401; - ctx.body = { - code: RESCODE.COMMFAIL, - message: '登录失效~', - }; - return; - } - // 判断密码版本是否正确 - const passwordV = await this.coolCache.get(`admin:passwordVersion:${ctx.admin.userId}`); - if (passwordV !== ctx.admin.passwordVersion) { - ctx.status = 401; - ctx.body = { - code: RESCODE.COMMFAIL, - message: '登录失效~', - }; - return; - } - const rToken = await this.coolCache.get(`admin:token:${ctx.admin.userId}`); - if (!rToken) { - ctx.status = 401; - ctx.body = { - code: RESCODE.COMMFAIL, - message: '登录失效或无权限访问~', - }; - return; - } - if (rToken !== token && this.coolConfig.sso) { - statusCode = 401; - } else { - let perms = await this.coolCache.get(`admin:perms:${ctx.admin.userId}`); - if (!_.isEmpty(perms)) { - perms = JSON.parse(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) { - ctx.status = statusCode; - ctx.body = { - code: RESCODE.COMMFAIL, - message: '登录失效或无权限访问~', - }; - return; - } - } + resolve() { + return async (ctx: Context, next: IMidwayWebNext) => { + let statusCode = 200; + const { url } = ctx; + const token = ctx.get('Authorization'); + const { prefix } = this.coolConfig.router; + const adminUrl = prefix ? `${prefix}/admin/` : '/admin/'; + // 路由地址为 admin前缀的 需要权限校验 + if (_.startsWith(url, adminUrl)) { + try { + ctx.admin = jwt.verify(token, this.coolConfig.jwt.secret); + } catch (err) {} + // 不需要登录 无需权限校验 + if (new RegExp(`^${adminUrl}?.*/open/`).test(url)) { + await next(); + return; + } + if (ctx.admin) { + // 要登录每个人都有权限的接口 + if (new RegExp(`^${adminUrl}?.*/comm/`).test(url)) { await next(); - }; - } - -} \ No newline at end of file + return; + } + // 如果传的token是refreshToken则校验失败 + if (ctx.admin.isRefresh) { + ctx.status = 401; + ctx.body = { + code: RESCODE.COMMFAIL, + message: '登录失效~', + }; + return; + } + // 判断密码版本是否正确 + const passwordV = await this.coolCache.get( + `admin:passwordVersion:${ctx.admin.userId}` + ); + console.log(6666666666, '密码版本', passwordV); + if (passwordV !== ctx.admin.passwordVersion) { + ctx.status = 401; + ctx.body = { + code: RESCODE.COMMFAIL, + message: '登录失效~', + }; + return; + } + const rToken = await this.coolCache.get( + `admin:token:${ctx.admin.userId}` + ); + if (!rToken) { + ctx.status = 401; + ctx.body = { + code: RESCODE.COMMFAIL, + message: '登录失效或无权限访问~', + }; + return; + } + if (rToken !== token && this.coolConfig.sso) { + statusCode = 401; + } else { + let perms = await this.coolCache.get( + `admin:perms:${ctx.admin.userId}` + ); + if (!_.isEmpty(perms)) { + perms = JSON.parse(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) { + ctx.status = statusCode; + ctx.body = { + code: RESCODE.COMMFAIL, + message: '登录失效或无权限访问~', + }; + return; + } + } + await next(); + }; + } +} diff --git a/src/app/modules/base/middleware/log.ts b/src/app/modules/base/middleware/log.ts index 73b9e33..39dedeb 100644 --- a/src/app/modules/base/middleware/log.ts +++ b/src/app/modules/base/middleware/log.ts @@ -8,15 +8,18 @@ import { Context } from 'egg'; */ @Provide() export class BaseLogMiddleware implements IWebMiddleware { + @Inject() + baseSysLogService: BaseSysLogService; - @Inject() - baseSysLogService: BaseSysLogService; - - resolve() { - return async (ctx: Context, next: IMidwayWebNext) => { - this.baseSysLogService.record(ctx, ctx.url.split('?')[0], ctx.req.method === 'GET' ? ctx.request.query : ctx.request.body, ctx.admin ? ctx.admin.userId : null); - await next(); - }; - } - -} \ No newline at end of file + resolve() { + return async (ctx: Context, next: IMidwayWebNext) => { + this.baseSysLogService.record( + ctx, + ctx.url.split('?')[0], + ctx.req.method === 'GET' ? ctx.request.query : ctx.request.body, + ctx.admin ? ctx.admin.userId : null + ); + await next(); + }; + } +} diff --git a/src/app/modules/base/schedule/log.ts b/src/app/modules/base/schedule/log.ts index e255b51..666c16b 100644 --- a/src/app/modules/base/schedule/log.ts +++ b/src/app/modules/base/schedule/log.ts @@ -8,22 +8,21 @@ import { ILogger } from '@midwayjs/logger'; */ @Provide() @Schedule({ - cron: '0 0 0 * * *', // 每天0点执行 - type: 'worker' // 指定某一个 worker 执行 + cron: '0 0 0 * * *', // 每天0点执行 + type: 'worker', // 指定某一个 worker 执行 }) export class BaseLogSchedule implements CommonSchedule { + @Inject() + baseSysLogService: BaseSysLogService; - @Inject() - baseSysLogService: BaseSysLogService; + @Inject() + logger: ILogger; - @Inject() - logger: ILogger; - - // 定时执行的具体任务 - async exec() { - this.logger.info('清除日志定时任务开始执行'); - const startTime = Date.now(); - await this.baseSysLogService.clear(); - this.logger.info(`清除日志定时任务结束,耗时:${(Date.now() - startTime)}ms`); - } -} \ No newline at end of file + // 定时执行的具体任务 + async exec() { + this.logger.info('清除日志定时任务开始执行'); + const startTime = Date.now(); + await this.baseSysLogService.clear(); + this.logger.info(`清除日志定时任务结束,耗时:${Date.now() - startTime}ms`); + } +} diff --git a/src/app/modules/base/service/plugin/info.ts b/src/app/modules/base/service/plugin/info.ts index 1b15477..23aad73 100644 --- a/src/app/modules/base/service/plugin/info.ts +++ b/src/app/modules/base/service/plugin/info.ts @@ -6,38 +6,37 @@ import { BaseService, CoolPlugin } from 'midwayjs-cool-core'; */ @Provide() export class BasePluginInfoService extends BaseService { + @Inject('cool:coolPlugin') + coolPlugin: CoolPlugin; - @Inject('cool:coolPlugin') - coolPlugin: CoolPlugin; + /** + * 列表 + */ + async list(keyWord) { + return this.coolPlugin.list(keyWord); + } - /** - * 列表 - */ - async list(keyWord) { - return this.coolPlugin.list(keyWord); - } + /** + * 配置 + */ + async config(namespace: string, config) { + await this.coolPlugin.setConfig(namespace, config); + } - /** - * 配置 - */ - async config(namespace: string, config) { - await this.coolPlugin.setConfig(namespace, config); - } + /** + * 获得配置信息 + * @param namespace + */ + async getConfig(namespace: string) { + return await this.coolPlugin.getConfig(namespace); + } - /** - * 获得配置信息 - * @param namespace - */ - async getConfig(namespace: string) { - return await this.coolPlugin.getConfig(namespace); - } - - /** - * 是否启用插件 - * @param namespace - * @param enable - */ - async enable(namespace: string, enable: number){ - await this.coolPlugin.enable(namespace,enable); - } -} \ No newline at end of file + /** + * 是否启用插件 + * @param namespace + * @param enable + */ + async enable(namespace: string, enable: number) { + await this.coolPlugin.enable(namespace, enable); + } +} diff --git a/src/app/modules/base/service/sys/conf.ts b/src/app/modules/base/service/sys/conf.ts index ab06dfd..1851418 100644 --- a/src/app/modules/base/service/sys/conf.ts +++ b/src/app/modules/base/service/sys/conf.ts @@ -9,30 +9,30 @@ import { BaseSysConfEntity } from '../../entity/sys/conf'; */ @Provide() export class BaseSysConfService extends BaseService { + @InjectEntityModel(BaseSysConfEntity) + baseSysConfEntity: Repository; - @InjectEntityModel(BaseSysConfEntity) - baseSysConfEntity: Repository; - - /** - * 获得配置参数值 - * @param key - */ - async getValue(key) { - const conf = await this.baseSysConfEntity.findOne({ cKey: key }); - if (conf) { - return conf.cValue; - } + /** + * 获得配置参数值 + * @param key + */ + async getValue(key) { + const conf = await this.baseSysConfEntity.findOne({ cKey: key }); + if (conf) { + return conf.cValue; } + } - /** - * 更新配置参数 - * @param cKey - * @param cValue - */ - async updateVaule(cKey, cValue) { - await this.baseSysConfEntity.createQueryBuilder() - .update() - .set({ cKey, cValue }) - .execute(); - } -} \ No newline at end of file + /** + * 更新配置参数 + * @param cKey + * @param cValue + */ + async updateVaule(cKey, cValue) { + await this.baseSysConfEntity + .createQueryBuilder() + .update() + .set({ cKey, cValue }) + .execute(); + } +} diff --git a/src/app/modules/base/service/sys/department.ts b/src/app/modules/base/service/sys/department.ts index bcdb7e4..efb29eb 100644 --- a/src/app/modules/base/service/sys/department.ts +++ b/src/app/modules/base/service/sys/department.ts @@ -13,95 +13,112 @@ import { BaseSysPermsService } from './perms'; */ @Provide() export class BaseSysDepartmentService extends BaseService { + @InjectEntityModel(BaseSysDepartmentEntity) + baseSysDepartmentEntity: Repository; - @InjectEntityModel(BaseSysDepartmentEntity) - baseSysDepartmentEntity: Repository; + @InjectEntityModel(BaseSysRoleDepartmentEntity) + baseSysRoleDepartmentEntity: Repository; - @InjectEntityModel(BaseSysRoleDepartmentEntity) - baseSysRoleDepartmentEntity: Repository; + @Inject() + baseSysPermsService: BaseSysPermsService; - @Inject() - baseSysPermsService: BaseSysPermsService; + @Inject() + ctx: Context; - @Inject() - ctx: Context; + /** + * 获得部门菜单 + */ + async list() { + // 部门权限 + const permsDepartmentArr = await this.baseSysPermsService.departmentIds( + this.ctx.admin.userId + ); - /** - * 获得部门菜单 - */ - async list() { - // 部门权限 - const permsDepartmentArr = await this.baseSysPermsService.departmentIds(this.ctx.admin.userId); + // 过滤部门权限 + const find = this.baseSysDepartmentEntity.createQueryBuilder(); + if (this.ctx.admin.username !== 'admin') + find.andWhere('id in (:ids)', { + ids: !_.isEmpty(permsDepartmentArr) ? permsDepartmentArr : [null], + }); + find.addOrderBy('orderNum', 'ASC'); + const departments: BaseSysDepartmentEntity[] = await find.getMany(); - // 过滤部门权限 - const find = this.baseSysDepartmentEntity.createQueryBuilder(); - if (this.ctx.admin.username !== 'admin') find.andWhere('id in (:ids)', { ids: !_.isEmpty(permsDepartmentArr) ? permsDepartmentArr : [null] }); - find.addOrderBy('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; - } - }); + 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; + }); } + 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().where('roleId in (:roleIds)', { roleIds }).getMany(); - if (!_.isEmpty(result)) { - return _.uniq(result.map(e => { - return e.departmentId; - })); - } - } - return []; + /** + * 根据多个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() + .where('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); - } + /** + * 部门排序 + * @param params + */ + async order(params) { + for (const e of params) { + await this.baseSysDepartmentEntity.update(e.id, e); } + } - /** - * 删除 - */ - async delete(ids: number[]) { - let { deleteUser } = this.ctx.request.body; - await this.baseSysDepartmentEntity.delete(ids); - if (deleteUser) { - await this.nativeQuery('delete from base_sys_user where departmentId in (?)', [ids]); - } else { - const topDepartment = await this.baseSysDepartmentEntity.createQueryBuilder().where('parentId is null').getOne(); - if (topDepartment) { - await this.nativeQuery('update base_sys_user a set a.departmentId = ? where a.departmentId in (?)', [topDepartment.id, ids]); - } - } + /** + * 删除 + */ + async delete(ids: number[]) { + const { deleteUser } = this.ctx.request.body; + await this.baseSysDepartmentEntity.delete(ids); + if (deleteUser) { + await this.nativeQuery( + 'delete from base_sys_user where departmentId in (?)', + [ids] + ); + } else { + const topDepartment = await this.baseSysDepartmentEntity + .createQueryBuilder() + .where('parentId is null') + .getOne(); + if (topDepartment) { + await this.nativeQuery( + 'update base_sys_user a set a.departmentId = ? where a.departmentId in (?)', + [topDepartment.id, ids] + ); + } } - -} \ No newline at end of file + } +} diff --git a/src/app/modules/base/service/sys/log.ts b/src/app/modules/base/service/sys/log.ts index 789263f..50c127a 100644 --- a/src/app/modules/base/service/sys/log.ts +++ b/src/app/modules/base/service/sys/log.ts @@ -14,57 +14,63 @@ import { BaseSysConfService } from './conf'; */ @Provide() export class BaseSysLogService extends BaseService { + @Inject() + ctx: Context; - @Inject() - ctx: Context; + @Inject() + utils: Utils; - @Inject() - utils: Utils; + @InjectEntityModel(BaseSysLogEntity) + baseSysLogEntity: Repository; - @InjectEntityModel(BaseSysLogEntity) - baseSysLogEntity: Repository; + @Inject() + baseSysConfService: BaseSysConfService; - @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(','); - const ipAddrArr = new Array(); - for (const e of sysLog.ip.split(',')) ipAddrArr.push(await await this.utils.getIpAddr(context, e)); - sysLog.ipAddr = ipAddrArr.join(','); - sysLog.action = url; - if (!_.isEmpty(params)) { - sysLog.params = JSON.stringify(params); - } - await this.baseSysLogEntity.insert(sysLog); + /** + * 记录 + * @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(','); + const ipAddrArr = []; + for (const e of sysLog.ip.split(',')) + ipAddrArr.push(await await this.utils.getIpAddr(context, e)); + sysLog.ipAddr = ipAddrArr.join(','); + sysLog.action = url; + if (!_.isEmpty(params)) { + sysLog.params = JSON.stringify(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').format('YYYY-MM-DD')} 00:00:00`; - await this.baseSysLogEntity.createQueryBuilder() - .where('createTime < :createTime', { createTime: beforeDate }) - await this.nativeQuery(' delete from base_sys_log where createTime < ? ', [beforeDate]); - } else { - await this.baseSysLogEntity.clear(); - } + /** + * 日志 + * @param isAll 是否清除全部 + */ + async clear(isAll?) { + if (isAll) { + await this.baseSysLogEntity.clear(); + return; } -} \ No newline at end of file + const keepDay = await this.baseSysConfService.getValue('logKeep'); + if (keepDay) { + const beforeDate = `${moment() + .add(-keepDay, 'days') + .format('YYYY-MM-DD')} 00:00:00`; + await this.baseSysLogEntity + .createQueryBuilder() + .where('createTime < :createTime', { createTime: beforeDate }); + await this.nativeQuery( + ' delete from base_sys_log where createTime < ? ', + [beforeDate] + ); + } else { + await this.baseSysLogEntity.clear(); + } + } +} diff --git a/src/app/modules/base/service/sys/login.ts b/src/app/modules/base/service/sys/login.ts index 18cf066..0335e2b 100644 --- a/src/app/modules/base/service/sys/login.ts +++ b/src/app/modules/base/service/sys/login.ts @@ -1,5 +1,11 @@ import { Inject, Provide, Config } from '@midwayjs/decorator'; -import { BaseService, CoolCache, CoolCommException, CoolConfig, RESCODE } from 'midwayjs-cool-core'; +import { + BaseService, + CoolCache, + CoolCommException, + CoolConfig, + RESCODE, +} from 'midwayjs-cool-core'; import { LoginDTO } from '../../dto/login'; import * as svgCaptcha from 'svg-captcha'; import * as svgToDataURL from 'svg-to-dataurl'; @@ -20,196 +26,221 @@ import { Context } from 'egg'; */ @Provide() export class BaseSysLoginService extends BaseService { + @Inject('cool:cache') + coolCache: CoolCache; - @Inject('cool:cache') - coolCache: CoolCache; + @InjectEntityModel(BaseSysUserEntity) + baseSysUserEntity: Repository; - @InjectEntityModel(BaseSysUserEntity) - baseSysUserEntity: Repository; + @Inject() + baseSysRoleService: BaseSysRoleService; - @Inject() - baseSysRoleService: BaseSysRoleService; + @Inject() + baseSysMenuService: BaseSysMenuService; - @Inject() - baseSysMenuService: BaseSysMenuService; + @Inject() + baseSysDepartmentService: BaseSysDepartmentService; - @Inject() - baseSysDepartmentService: BaseSysDepartmentService; + @Inject() + ctx: Context; - @Inject() - ctx: Context; + @Config('cool') + coolConfig: CoolConfig; - @Config('cool') - coolConfig: 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.findOne({ 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.coolCache.set(`admin:department:${user.id}`, JSON.stringify(departments)); - await this.coolCache.set(`admin:perms:${user.id}`, JSON.stringify(perms)); - await this.coolCache.set(`admin:token:${user.id}`, result.token); - await this.coolCache.set(`admin:token:refresh:${user.id}`, result.token); - - return result; - } else { - throw new CoolCommException('验证码不正确'); + /** + * 登录 + * @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.findOne({ 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('该用户未设置任何角色,无法登录~'); + } - /** - * 验证码 - * @param type 图片验证码类型 svg - * @param width 宽 - * @param height 高 - */ - async captcha(type: string, width = 150, height = 50) { - const svg = svgCaptcha.create({ - ignoreChars: 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM', - width, - height, - }); + // 生成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.coolCache.set( + `admin:department:${user.id}`, + JSON.stringify(departments) + ); + await this.coolCache.set(`admin:perms:${user.id}`, JSON.stringify(perms)); + await this.coolCache.set(`admin:token:${user.id}`, result.token); + await this.coolCache.set(`admin:token:refresh:${user.id}`, result.token); + + return result; + } else { + throw new CoolCommException('验证码不正确'); + } + } + + /** + * 验证码 + * @param type 图片验证码类型 svg + * @param width 宽 + * @param height 高 + */ + async captcha(type: string, width = 150, height = 50) { + const svg = svgCaptcha.create({ + ignoreChars: 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM', + width, + height, + }); + 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, '#fff'); + }); + if (type === 'base64') { + result.data = svgToDataURL(result.data); + } + // 半小时过期 + await this.coolCache.set( + `verify:img:${result.captchaId}`, + svg.text.toLowerCase(), + 1800 + ); + return result; + } + + /** + * 退出登录 + */ + async logout() { + const { userId } = this.ctx.admin; + await this.coolCache.del(`admin:department:${userId}`); + await this.coolCache.del(`admin:perms:${userId}`); + await this.coolCache.del(`admin:token:${userId}`); + await this.coolCache.del(`admin:token:refresh:${userId}`); + } + + /** + * 检验图片验证码 + * @param captchaId 验证码ID + * @param value 验证码 + */ + async captchaCheck(captchaId, value) { + const rv = await this.coolCache.get(`verify:img:${captchaId}`); + if (!rv || !value || value.toLowerCase() !== rv) { + return false; + } else { + this.coolCache.del(`verify:img:${captchaId}`); + return true; + } + } + + /** + * 生成token + * @param user 用户对象 + * @param roleIds 角色集合 + * @param expire 过期 + * @param isRefresh 是否是刷新 + */ + async generateToken(user, roleIds, expire, isRefresh?) { + await this.coolCache.set( + `admin:passwordVersion:${user.id}`, + user.passwordV + ); + const tokenInfo = { + isRefresh: false, + roleIds, + username: user.username, + userId: user.id, + passwordVersion: user.passwordV, + }; + if (isRefresh) { + tokenInfo.isRefresh = true; + } + return jwt.sign(tokenInfo, this.coolConfig.jwt.secret, { + expiresIn: expire, + }); + } + + /** + * 刷新token + * @param token + */ + async refreshToken(token: string) { + try { + 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 = { - captchaId: uuid(), - data: svg.data.replace(/\"/g, "'"), - }; - // 文字变白 - const rpList = ['#111', '#222', '#333', '#444', '#555', '#666', '#777', '#888', '#999']; - rpList.forEach(rp => { - // @ts-ignore - result.data = result.data.replaceAll(rp, '#fff'); - }); - if (type === 'base64') { - result.data = svgToDataURL(result.data); - } - // 半小时过期 - await this.coolCache.set(`verify:img:${result.captchaId}`, svg.text.toLowerCase(), 1800); - return result; - } - - /** - * 退出登录 - */ - async logout() { - const { userId } = this.ctx.admin; - await this.coolCache.del(`admin:department:${userId}`); - await this.coolCache.del(`admin:perms:${userId}`); - await this.coolCache.del(`admin:token:${userId}`); - await this.coolCache.del(`admin:token:refresh:${userId}`); - } - - /** - * 检验图片验证码 - * @param captchaId 验证码ID - * @param value 验证码 - */ - async captchaCheck(captchaId, value) { - const rv = await this.coolCache.get(`verify:img:${captchaId}`); - if (!rv || !value || value.toLowerCase() !== rv) { - return false; - } else { - this.coolCache.del(`verify:img:${captchaId}`); - return true; - } - } - - /** - * 生成token - * @param user 用户对象 - * @param roleIds 角色集合 - * @param expire 过期 - * @param isRefresh 是否是刷新 - */ - async generateToken(user, roleIds, expire, isRefresh?) { - await this.coolCache.set(`admin:passwordVersion:${user.id}`, user.passwordV); - const tokenInfo = { - isRefresh: false, - roleIds, - username: user.username, - userId: user.id, - passwordVersion: user.passwordV, - }; - if (isRefresh) { - tokenInfo.isRefresh = true; - } - return jwt.sign(tokenInfo, - this.coolConfig.jwt.secret, { + 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.coolCache.set( + `admin:passwordVersion:${decoded['userId']}`, + decoded['passwordVersion'] + ); + return result; + } + } catch (err) { + console.log(err); + this.ctx.status = 401; + this.ctx.body = { + code: RESCODE.COMMFAIL, + message: '登录失效~', + }; + return; } - - /** - * 刷新token - * @param token - */ - async refreshToken(token: string) { - try { - 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.coolCache.set(`admin:passwordVersion:${decoded['userId']}`, decoded['passwordVersion']); - return result; - } - } catch (err) { - console.log(err); - this.ctx.status = 401; - this.ctx.body = { - code: RESCODE.COMMFAIL, - message: '登录失效~', - }; - return; - } - - } -} \ No newline at end of file + } +} diff --git a/src/app/modules/base/service/sys/menu.ts b/src/app/modules/base/service/sys/menu.ts index 888059d..7b8e10b 100644 --- a/src/app/modules/base/service/sys/menu.ts +++ b/src/app/modules/base/service/sys/menu.ts @@ -12,140 +12,155 @@ import { BaseSysPermsService } from './perms'; */ @Provide() export class BaseSysMenuService extends BaseService { + @Inject() + ctx: Context; - @Inject() - ctx: Context; + @InjectEntityModel(BaseSysMenuEntity) + baseSysMenuEntity: Repository; - @InjectEntityModel(BaseSysMenuEntity) - baseSysMenuEntity: Repository; + @Inject() + baseSysPermsService: BaseSysPermsService; - @Inject() - baseSysPermsService: BaseSysPermsService; - - /** - * 获得所有菜单 - */ - async list() { - const menus = await this.getMenus(this.ctx.admin.roleIds, this.ctx.admin.username === 'admin'); - if (!_.isEmpty(menus)) { - menus.forEach(e => { - 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; - } - }); + /** + * 获得所有菜单 + */ + async list() { + const menus = await this.getMenus( + this.ctx.admin.roleIds, + this.ctx.admin.username === 'admin' + ); + if (!_.isEmpty(menus)) { + menus.forEach(e => { + 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; + }); } + return menus; + } - /** - * 修改之后 - * @param param - */ - async modifyAfter(param) { - if (param.id) { - await this.refreshPerms(param.id); - } + /** + * 修改之后 + * @param param + */ + async modifyAfter(param) { + if (param.id) { + await this.refreshPerms(param.id); } + } - /** - * 根据角色获得权限信息 - * @param {[]} roleIds 数组 - */ - async getPerms(roleIds) { - let perms = []; - if (!_.isEmpty(roleIds)) { - const result = await this.nativeQuery(` - SELECT a.perms FROM base_sys_menu a ${this.setSql(!roleIds.includes('1'), - 'JOIN base_sys_role_menu b on a.id = b.menuId AND b.roleId in (?)', [roleIds])} + /** + * 根据角色获得权限信息 + * @param {[]} roleIds 数组 + */ + async getPerms(roleIds) { + let perms = []; + if (!_.isEmpty(roleIds)) { + const result = await this.nativeQuery( + ` + SELECT a.perms FROM base_sys_menu a ${this.setSql( + !roleIds.includes('1'), + 'JOIN base_sys_role_menu b on a.id = b.menuId AND b.roleId in (?)', + [roleIds] + )} where 1=1 and a.perms is not NULL - `, [roleIds]); - 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); + `, + [roleIds] + ); + 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) { - return await this.nativeQuery(` + /** + * 获得用户菜单信息 + * @param roleIds + * @param isAdmin 是否是超管 + */ + async getMenus(roleIds, isAdmin) { + return await this.nativeQuery(` SELECT a.* FROM base_sys_menu a - ${this.setSql(!isAdmin, 'JOIN base_sys_role_menu b on a.id = b.menuId AND b.roleId in (?)', [roleIds])} + ${this.setSql( + !isAdmin, + 'JOIN base_sys_role_menu b on a.id = b.menuId AND b.roleId in (?)', + [roleIds] + )} GROUP BY a.id ORDER BY orderNum ASC`); - } + } - /** - * 删除 - * @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 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.find({ 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 id + */ + private async delChildMenu(id) { + await this.refreshPerms(id); + const delMenu = await this.baseSysMenuEntity.find({ 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 users = await this.nativeQuery('select b.userId from base_sys_role_menu a left join base_sys_user_role b on a.roleId = b.roleId where a.menuId = ? group by b.userId', [menuId]); - // 刷新admin权限 - await this.baseSysPermsService.refreshPerms(1); - if (!_.isEmpty(users)) { - // 刷新其他权限 - for (const user of users) { - await this.baseSysPermsService.refreshPerms(user.userId); - } - } + /** + * 更新权限 + * @param menuId + */ + async refreshPerms(menuId) { + const users = await this.nativeQuery( + 'select b.userId from base_sys_role_menu a left join base_sys_user_role b on a.roleId = b.roleId where a.menuId = ? group by b.userId', + [menuId] + ); + // 刷新admin权限 + await this.baseSysPermsService.refreshPerms(1); + if (!_.isEmpty(users)) { + // 刷新其他权限 + for (const user of users) { + await this.baseSysPermsService.refreshPerms(user.userId); + } } -} \ No newline at end of file + } +} diff --git a/src/app/modules/base/service/sys/param.ts b/src/app/modules/base/service/sys/param.ts index 0cd3390..5ac2b7d 100644 --- a/src/app/modules/base/service/sys/param.ts +++ b/src/app/modules/base/service/sys/param.ts @@ -9,53 +9,52 @@ import { BaseSysParamEntity } from '../../entity/sys/param'; */ @Provide() export class BaseSysParamService extends BaseService { + @InjectEntityModel(BaseSysParamEntity) + baseSysParamEntity: Repository; - @InjectEntityModel(BaseSysParamEntity) - baseSysParamEntity: Repository; - - @Inject('cool:cache') - coolCache: CoolCache; + @Inject('cool:cache') + coolCache: CoolCache; - /** - * 根据key获得对应的参数 - * @param key - */ - async dataByKey (key) { - let result = await this.coolCache.get(`param:${ key }`); - if (result) { - result = JSON.parse(result); - if (result.dataType !== 0) { - return JSON.parse(result.data); - } else { - return result.data; - } - } - return; + /** + * 根据key获得对应的参数 + * @param key + */ + async dataByKey(key) { + let result = await this.coolCache.get(`param:${key}`); + if (result) { + result = JSON.parse(result); + if (result.dataType !== 0) { + return JSON.parse(result.data); + } else { + return result.data; + } } + return; + } - /** - * 根据key获得对应的网页数据 - * @param key - */ - async htmlByKey (key) { - let html = '@content'; - let result = await this.coolCache.get(`param:${ key }`); - if (result) { - result = JSON.parse(result); - html = html.replace('@content', result.data); - } else { - html = html.replace('@content', 'key notfound'); - } - return html; + /** + * 根据key获得对应的网页数据 + * @param key + */ + async htmlByKey(key) { + let html = '@content'; + let result = await this.coolCache.get(`param:${key}`); + if (result) { + result = JSON.parse(result); + html = html.replace('@content', result.data); + } else { + html = html.replace('@content', 'key notfound'); } + return html; + } - /** - * 重新初始化缓存 - */ - async modifyAfter () { - const params = await this.baseSysParamEntity.find(); - for (const param of params) { - await this.coolCache.set(`param:${ param.keyName }`, JSON.stringify(param)); - } + /** + * 重新初始化缓存 + */ + async modifyAfter() { + const params = await this.baseSysParamEntity.find(); + for (const param of params) { + await this.coolCache.set(`param:${param.keyName}`, JSON.stringify(param)); } -} \ No newline at end of file + } +} diff --git a/src/app/modules/base/service/sys/perms.ts b/src/app/modules/base/service/sys/perms.ts index 753f045..6fc6c19 100644 --- a/src/app/modules/base/service/sys/perms.ts +++ b/src/app/modules/base/service/sys/perms.ts @@ -10,57 +10,64 @@ import { Context } from 'egg'; */ @Provide() export class BaseSysPermsService extends BaseService { + @Inject('cool:cache') + coolCache: CoolCache; - @Inject('cool:cache') - coolCache: CoolCache; + @Inject() + baseSysMenuService: BaseSysMenuService; - @Inject() - baseSysMenuService: BaseSysMenuService; - - @Inject() - baseSysRoleService: BaseSysRoleService; + @Inject() + baseSysRoleService: BaseSysRoleService; - @Inject() - baseSysDepartmentService: BaseSysDepartmentService; + @Inject() + baseSysDepartmentService: BaseSysDepartmentService; - @Inject() - ctx: Context; - + @Inject() + ctx: Context; - /** - * 刷新权限 - * @param userId 用户ID - */ - async refreshPerms(userId) { - const roleIds = await this.baseSysRoleService.getByUser(userId); - const perms = await this.baseSysMenuService.getPerms(roleIds); - await this.coolCache.set(`admin:perms:${userId}`, JSON.stringify(perms)); - // 更新部门权限 - const departments = await this.baseSysDepartmentService.getByRoleIds(roleIds, this.ctx.admin.username === 'admin'); - await this.coolCache.set(`admin:department:${userId}`, JSON.stringify(departments)); + /** + * 刷新权限 + * @param userId 用户ID + */ + async refreshPerms(userId) { + const roleIds = await this.baseSysRoleService.getByUser(userId); + const perms = await this.baseSysMenuService.getPerms(roleIds); + await this.coolCache.set(`admin:perms:${userId}`, JSON.stringify(perms)); + // 更新部门权限 + const departments = await this.baseSysDepartmentService.getByRoleIds( + roleIds, + this.ctx.admin.username === 'admin' + ); + await this.coolCache.set( + `admin:department:${userId}`, + JSON.stringify(departments) + ); + } + + /** + * 获得权限菜单 + * @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 = await this.coolCache.get(`admin:department:${userId}`); + if (department) { + return JSON.parse(department); + } else { + return []; } - - /** - * 获得权限菜单 - * @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 = await this.coolCache.get(`admin:department:${userId}`); - if (department) { - return JSON.parse(department); - } else { - return []; - } - } -} \ No newline at end of file + } +} diff --git a/src/app/modules/base/service/sys/role.ts b/src/app/modules/base/service/sys/role.ts index 34a8592..34353bb 100644 --- a/src/app/modules/base/service/sys/role.ts +++ b/src/app/modules/base/service/sys/role.ts @@ -15,105 +15,112 @@ import { Brackets } from 'typeorm'; */ @Provide() export class BaseSysRoleService extends BaseService { + @InjectEntityModel(BaseSysRoleEntity) + baseSysRoleEntity: Repository; - @InjectEntityModel(BaseSysRoleEntity) - baseSysRoleEntity: Repository; + @InjectEntityModel(BaseSysUserRoleEntity) + baseSysUserRoleEntity: Repository; - @InjectEntityModel(BaseSysUserRoleEntity) - baseSysUserRoleEntity: Repository; + @InjectEntityModel(BaseSysRoleMenuEntity) + baseSysRoleMenuEntity: Repository; - @InjectEntityModel(BaseSysRoleMenuEntity) - baseSysRoleMenuEntity: Repository; + @InjectEntityModel(BaseSysRoleDepartmentEntity) + baseSysRoleDepartmentEntity: Repository; - @InjectEntityModel(BaseSysRoleDepartmentEntity) - baseSysRoleDepartmentEntity: Repository; + @Inject() + baseSysPermsService: BaseSysPermsService; - @Inject() - baseSysPermsService: BaseSysPermsService; + /** + * 根据用户ID获得所有用户角色 + * @param userId + */ + async getByUser(userId: number): Promise { + const userRole = await this.baseSysUserRoleEntity.find({ 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); + } + } - /** - * 根据用户ID获得所有用户角色 - * @param userId - */ - async getByUser(userId: number): Promise { - const userRole = await this.baseSysUserRoleEntity.find({ userId }); - if (!_.isEmpty(userRole)) { - return userRole.map(e => { - return e.roleId; + /** + * 更新权限 + * @param roleId + * @param menuIdList + * @param departmentIds + */ + async updatePerms(roleId, menuIdList?, departmentIds = []) { + // 更新菜单权限 + await this.baseSysRoleMenuEntity.delete({ roleId }); + for (const e of menuIdList) { + await this.baseSysRoleMenuEntity.save({ roleId, menuId: e }); + } + // 更新部门权限 + await this.baseSysRoleDepartmentEntity.delete({ roleId }); + for (const departmentId of departmentIds) { + await this.baseSysRoleDepartmentEntity.save({ roleId, departmentId }); + } + // 刷新权限 + const userRoles = await this.baseSysUserRoleEntity.find({ roleId }); + for (const userRole of userRoles) { + await this.baseSysPermsService.refreshPerms(userRole.userId); + } + } + + /** + * 角色信息 + * @param id + */ + async info(id) { + const info = await this.baseSysRoleEntity.findOne({ id }); + if (info) { + const menus = await this.baseSysRoleMenuEntity.find( + id !== 1 ? { roleId: id } : {} + ); + const menuIdList = menus.map(e => { + return parseInt(e.menuId + ''); + }); + const departments = await this.baseSysRoleDepartmentEntity.find( + id !== 1 ? { roleId: id } : {} + ); + const departmentIdList = departments.map(e => { + return parseInt(e.departmentId + ''); + }); + return { + ...info, + menuIdList, + departmentIdList, + }; + } + return {}; + } + + async list() { + return this.baseSysRoleEntity + .createQueryBuilder() + .where( + new Brackets(qb => { + qb.where('id !=:id', { id: 1 }); // 超级管理员的角色不展示 + // 如果不是超管,只能看到自己新建的或者自己有的角色 + if (this.ctx.admin.username !== 'admin') { + qb.andWhere('(userId=:userId or id in (:roleId))', { + userId: this.ctx.admin.userId, + roleId: this.ctx.admin.roleIds, }); - } - 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 }); - for (const e of menuIdList) { - await this.baseSysRoleMenuEntity.save({ roleId, menuId: e }); - } - // 更新部门权限 - await this.baseSysRoleDepartmentEntity.delete({ roleId }); - for (const departmentId of departmentIds) { - await this.baseSysRoleDepartmentEntity.save({ roleId, departmentId }); - } - // 刷新权限 - const userRoles = await this.baseSysUserRoleEntity.find({ roleId }); - for (const userRole of userRoles) { - await this.baseSysPermsService.refreshPerms(userRole.userId); - } - } - - /** - * 角色信息 - * @param id - */ - async info(id) { - const info = await this.baseSysRoleEntity.findOne({ id }); - if (info) { - const menus = await this.baseSysRoleMenuEntity.find(id !== 1 ? { roleId: id } : {}); - const menuIdList = menus.map(e => { - return parseInt(e.menuId + ''); - }); - const departments = await this.baseSysRoleDepartmentEntity.find(id !== 1 ? { roleId: id } : {}); - const departmentIdList = departments.map(e => { - return parseInt(e.departmentId + ''); - }); - return { - ...info, - menuIdList, - departmentIdList, - }; - } - return {}; - } - - async list() { - return this.baseSysRoleEntity.createQueryBuilder().where(new Brackets(qb => { - qb.where('id !=:id', { id: 1 }); // 超级管理员的角色不展示 - // 如果不是超管,只能看到自己新建的或者自己有的角色 - if (this.ctx.admin.username !== 'admin') { - qb.andWhere('(userId=:userId or id in (:roleId))', { - userId: this.ctx.admin.userId, - roleId: this.ctx.admin.roleIds, - }); - } - })).getMany(); - } -} \ No newline at end of file + } + }) + ) + .getMany(); + } +} diff --git a/src/app/modules/base/service/sys/user.ts b/src/app/modules/base/service/sys/user.ts index 111e562..e91aa00 100644 --- a/src/app/modules/base/service/sys/user.ts +++ b/src/app/modules/base/service/sys/user.ts @@ -14,30 +14,31 @@ import { BaseSysDepartmentEntity } from '../../entity/sys/department'; */ @Provide() export class BaseSysUserService extends BaseService { + @InjectEntityModel(BaseSysUserEntity) + baseSysUserEntity: Repository; - @InjectEntityModel(BaseSysUserEntity) - baseSysUserEntity: Repository; + @InjectEntityModel(BaseSysUserRoleEntity) + baseSysUserRoleEntity: Repository; - @InjectEntityModel(BaseSysUserRoleEntity) - baseSysUserRoleEntity: Repository; + @InjectEntityModel(BaseSysDepartmentEntity) + baseSysDepartmentEntity: Repository; - @InjectEntityModel(BaseSysDepartmentEntity) - baseSysDepartmentEntity: Repository; + @Inject('cool:cache') + coolCache: CoolCache; - @Inject('cool:cache') - coolCache: CoolCache; + @Inject() + baseSysPermsService: BaseSysPermsService; - @Inject() - baseSysPermsService: BaseSysPermsService; - - /** - * 分页查询 - * @param query - */ - async page(query) { - const { keyWord, status, departmentIds = [] } = query; - const permsDepartmentArr = await this.baseSysPermsService.departmentIds(this.ctx.admin.userId); // 部门权限 - const sql = ` + /** + * 分页查询 + * @param query + */ + async page(query) { + const { keyWord, status, departmentIds = [] } = query; + const permsDepartmentArr = await this.baseSysPermsService.departmentIds( + this.ctx.admin.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, GROUP_CONCAT(c.name) AS roleName, @@ -48,145 +49,171 @@ export class BaseSysUserService extends BaseService { LEFT JOIN base_sys_role c ON b.roleId = c.id LEFT JOIN base_sys_department d on a.departmentId = d.id WHERE 1 = 1 - ${this.setSql(!_.isEmpty(departmentIds), 'and a.departmentId in (?)', [departmentIds])} + ${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(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 (?)', [!_.isEmpty(permsDepartmentArr) ? permsDepartmentArr : [null]])} + ${this.setSql( + this.ctx.admin.username !== 'admin', + 'and a.departmentId in (?)', + [!_.isEmpty(permsDepartmentArr) ? permsDepartmentArr : [null]] + )} GROUP BY a.id `; - return this.sqlRenderPage(sql, query); + return this.sqlRenderPage(sql, query); + } + + /** + * 移动部门 + * @param departmentId + * @param userIds + */ + async move(departmentId, userIds) { + await this.baseSysUserEntity + .createQueryBuilder() + .update() + .set({ departmentId }) + .where('id in (:userIds)', { userIds }) + .execute(); + } + + /** + * 获得个人信息 + */ + async person() { + const info = await this.baseSysUserEntity.findOne({ + id: this.ctx.admin.userId, + }); + delete info.password; + return info; + } + + /** + * 更新用户角色关系 + * @param user + */ + async updateUserRole(user) { + if (user.username === 'admin') { + throw new CoolCommException('非法操作~'); } - - /** - * 移动部门 - * @param departmentId - * @param userIds - */ - async move(departmentId, userIds) { - await this.baseSysUserEntity.createQueryBuilder() - .update().set({ departmentId }) - .where('id in (:userIds)', { userIds }) - .execute(); + 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); + } - /** - * 获得个人信息 - */ - async person() { - const info = await this.baseSysUserEntity.findOne({ id: this.ctx.admin.userId }); - delete info.password; - return info; + /** + * 新增 + * @param param + */ + async add(param) { + const exists = await this.baseSysUserEntity.findOne({ + username: param.username, + }); + if (!_.isEmpty(exists)) { + throw new CoolCommException('用户名已经存在~'); } + param.password = md5('123456'); // 默认密码 建议未改密码不能登陆 + await this.baseSysUserEntity.save(param); + await this.updateUserRole(param); + return param.id; + } - /** - * 更新用户角色关系 - * @param user - */ - async updateUserRole(user) { - 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); + /** + * 根据ID获得信息 + * @param id + */ + public async info(id) { + const info = await this.baseSysUserEntity.findOne({ id }); + const userRoles = await this.nativeQuery( + 'select a.roleId from base_sys_user_role a where a.userId = ?', + [id] + ); + const department = await this.baseSysDepartmentEntity.findOne({ + id: info.departmentId, + }); + if (info) { + delete info.password; + if (userRoles) { + info.roleIdList = userRoles.map(e => { + return parseInt(e.roleId); + }); + } } - - /** - * 新增 - * @param param - */ - async add(param) { - const exists = await this.baseSysUserEntity.findOne({ username: param.username }); - if (!_.isEmpty(exists)) { - throw new CoolCommException('用户名已经存在~'); - } - param.password = md5('123456'); // 默认密码 建议未改密码不能登陆 - await this.baseSysUserEntity.save(param); - await this.updateUserRole(param); - return param.id; + delete info.password; + if (department) { + info.departmentName = department.name; } + return info; + } - /** - * 根据ID获得信息 - * @param id - */ - public async info (id) { - const info = await this.baseSysUserEntity.findOne({ id }); - const userRoles = await this.nativeQuery('select a.roleId from base_sys_user_role a where a.userId = ?', [ id ]); - const department = await this.baseSysDepartmentEntity.findOne({ 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 userInfo = await this.baseSysUserEntity.findOne({ id: param.id }); + if (!userInfo) { + throw new CoolCommException('用户不存在'); + } + param.passwordV = userInfo.passwordV + 1; + await this.coolCache.set( + `admin:passwordVersion:${param.id}`, + param.passwordV + ); + } else { + delete param.password; } + await this.baseSysUserEntity.save(param); + } - /** - * 修改个人信息 - * @param param - */ - public async personUpdate (param) { - param.id = this.ctx.admin.userId; - if (!_.isEmpty(param.password)) { - param.password = md5(param.password); - const userInfo = await this.baseSysUserEntity.findOne({ id: param.id }); - if (!userInfo) { - throw new CoolCommException('用户不存在'); - } - param.passwordV = userInfo.passwordV + 1; - await this.coolCache.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('非法操作~'); } - - /** - * 修改 - * @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.ctx.repo.sys.User.findOne({ id: param.id }); - if (!userInfo) { - throw new CoolCommException('用户不存在'); - } - param.passwordV = userInfo.passwordV + 1; - await this.coolCache.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); + if (!_.isEmpty(param.password)) { + param.password = md5(param.password); + const userInfo = await this.ctx.repo.sys.User.findOne({ id: param.id }); + if (!userInfo) { + throw new CoolCommException('用户不存在'); + } + param.passwordV = userInfo.passwordV + 1; + await this.coolCache.set( + `admin:passwordVersion:${param.id}`, + param.passwordV + ); + } else { + delete param.password; } - - /** - * 禁用用户 - * @param userId - */ - async forbidden(userId) { - await this.coolCache.del(`admin:token:${userId}`); + if (param.status === 0) { + await this.forbidden(param.id); } + await this.baseSysUserEntity.save(param); + await this.updateUserRole(param); + } - -} \ No newline at end of file + /** + * 禁用用户 + * @param userId + */ + async forbidden(userId) { + await this.coolCache.del(`admin:token:${userId}`); + } +} diff --git a/src/app/modules/demo/controller/app/goods.ts b/src/app/modules/demo/controller/app/goods.ts index 4fedc03..925deae 100644 --- a/src/app/modules/demo/controller/app/goods.ts +++ b/src/app/modules/demo/controller/app/goods.ts @@ -11,10 +11,9 @@ import { BaseSysMenuEntity } from '../../../base/entity/sys/menu'; @Provide() @CoolController({ api: ['add', 'delete', 'update', 'info', 'list', 'page'], - entity: DemoAppGoodsEntity + entity: DemoAppGoodsEntity, }) export class DemoAppGoodsController extends BaseController { - @InjectEntityModel(BaseSysMenuEntity) baseSysMenuEntity: Repository; @@ -22,15 +21,15 @@ export class DemoAppGoodsController extends BaseController { async 123() { const ms = await this.baseSysMenuEntity.find(); for (const item of ms) { - if(item.perms){ - let a = item.perms.split(',') - a = a.map(e=>{ - return 'base:'+e; - }) - item.perms = a.join(',') - this.baseSysMenuEntity.update(item.id, item) + if (item.perms) { + let a = item.perms.split(','); + a = a.map(e => { + return 'base:' + e; + }); + item.perms = a.join(','); + this.baseSysMenuEntity.update(item.id, item); } } - return this.ok(122) + return this.ok(122); } -} \ No newline at end of file +} diff --git a/src/app/modules/demo/entity/goods.ts b/src/app/modules/demo/entity/goods.ts index e72b32c..41198dc 100644 --- a/src/app/modules/demo/entity/goods.ts +++ b/src/app/modules/demo/entity/goods.ts @@ -7,14 +7,12 @@ import { Column } from 'typeorm'; */ @EntityModel('demo_app_goods') export class DemoAppGoodsEntity extends BaseEntity { + @Column({ comment: '标题' }) + title: string; - @Column({ comment: '标题' }) - title: string; + @Column({ comment: '图片' }) + pic: string; - @Column({ comment: '图片' }) - pic: string; - - @Column({ comment: '价格', type: 'decimal', precision: 5, scale: 2 }) - price: number; - -} \ No newline at end of file + @Column({ comment: '价格', type: 'decimal', precision: 5, scale: 2 }) + price: number; +} diff --git a/src/app/modules/space/config.ts b/src/app/modules/space/config.ts new file mode 100644 index 0000000..9b24b94 --- /dev/null +++ b/src/app/modules/space/config.ts @@ -0,0 +1,16 @@ +import { Application } from 'egg'; +import { ModuleConfig } from 'midwayjs-cool-core'; + +/** + * 模块的配置 + */ +export default (app: Application) => { + return { + // 模块名称 + name: '文件空间', + // 模块描述 + description: '上传和管理文件资源', + // 中间件 + middlewares: [], + } as ModuleConfig; +}; diff --git a/src/app/modules/base/controller/admin/app/space/info.ts b/src/app/modules/space/controller/admin/info.ts similarity index 50% rename from src/app/modules/base/controller/admin/app/space/info.ts rename to src/app/modules/space/controller/admin/info.ts index b76f875..1194681 100644 --- a/src/app/modules/base/controller/admin/app/space/info.ts +++ b/src/app/modules/space/controller/admin/info.ts @@ -1,18 +1,16 @@ import { Provide } from '@midwayjs/decorator'; import { CoolController, BaseController } from 'midwayjs-cool-core'; -import { BaseAppSpaceInfoEntity } from '../../../../entity/app/space/info'; +import { BaseAppSpaceInfoEntity } from '../../../base/entity/app/space/info'; /** * 图片空间信息 */ @Provide() @CoolController({ - api: ['add', 'delete', 'update', 'info', 'list', 'page'], - entity: BaseAppSpaceInfoEntity, - pageQueryOp: { - fieldEq: ['type', 'classifyId'] - } + api: ['add', 'delete', 'update', 'info', 'list', 'page'], + entity: BaseAppSpaceInfoEntity, + pageQueryOp: { + fieldEq: ['type', 'classifyId'], + }, }) -export class BaseAppSpaceInfoController extends BaseController { - -} \ No newline at end of file +export class BaseAppSpaceInfoController extends BaseController {} diff --git a/src/app/modules/base/controller/admin/app/space/type.ts b/src/app/modules/space/controller/admin/type.ts similarity index 57% rename from src/app/modules/base/controller/admin/app/space/type.ts rename to src/app/modules/space/controller/admin/type.ts index 1c7bf65..3b955de 100644 --- a/src/app/modules/base/controller/admin/app/space/type.ts +++ b/src/app/modules/space/controller/admin/type.ts @@ -1,15 +1,13 @@ import { Provide } from '@midwayjs/decorator'; import { CoolController, BaseController } from 'midwayjs-cool-core'; -import { BaseAppSpaceTypeEntity } from '../../../../entity/app/space/type'; +import { BaseAppSpaceTypeEntity } from '../../../base/entity/app/space/type'; /** * 空间分类 */ @Provide() @CoolController({ - api: ['add', 'delete', 'update', 'info', 'list', 'page'], - entity: BaseAppSpaceTypeEntity + api: ['add', 'delete', 'update', 'info', 'list', 'page'], + entity: BaseAppSpaceTypeEntity, }) -export class BaseAppSpaceTypeController extends BaseController { - -} \ No newline at end of file +export class BaseAppSpaceTypeController extends BaseController {} diff --git a/src/app/modules/space/controller/说明.md b/src/app/modules/space/controller/说明.md new file mode 100644 index 0000000..440a373 --- /dev/null +++ b/src/app/modules/space/controller/说明.md @@ -0,0 +1 @@ +编写接口 \ No newline at end of file diff --git a/src/app/modules/space/entity/info.ts b/src/app/modules/space/entity/info.ts new file mode 100644 index 0000000..4852358 --- /dev/null +++ b/src/app/modules/space/entity/info.ts @@ -0,0 +1,18 @@ +import { EntityModel } from '@midwayjs/orm'; +import { BaseEntity } from 'midwayjs-cool-core'; +import { Column } from 'typeorm'; + +/** + * 文件空间信息 + */ +@EntityModel('base_app_space_info') +export class BaseAppSpaceInfoEntity extends BaseEntity { + @Column({ comment: '地址' }) + url: string; + + @Column({ comment: '类型' }) + type: string; + + @Column({ comment: '分类ID', type: 'bigint', nullable: true }) + classifyId: number; +} diff --git a/src/app/modules/space/entity/type.ts b/src/app/modules/space/entity/type.ts new file mode 100644 index 0000000..6a076d6 --- /dev/null +++ b/src/app/modules/space/entity/type.ts @@ -0,0 +1,15 @@ +import { EntityModel } from '@midwayjs/orm'; +import { BaseEntity } from 'midwayjs-cool-core'; +import { Column } from 'typeorm'; + +/** + * 图片空间信息分类 + */ +@EntityModel('base_app_space_type') +export class BaseAppSpaceTypeEntity extends BaseEntity { + @Column({ comment: '类别名称' }) + name: string; + + @Column({ comment: '父分类ID', type: 'tinyint', nullable: true }) + parentId: number; +} diff --git a/src/app/public/js/welcome.js b/src/app/public/js/welcome.js index 1b6f9d3..f185f65 100644 --- a/src/app/public/js/welcome.js +++ b/src/app/public/js/welcome.js @@ -1,13 +1,12 @@ - -let duration = 0.8; -let delay = 0.3; -let revealText = document.querySelector(".reveal"); -let letters = revealText.textContent.split(""); -revealText.textContent = ""; -let middle = letters.filter(e => e !== " ").length / 2; +const duration = 0.8; +const delay = 0.3; +const revealText = document.querySelector('.reveal'); +const letters = revealText.textContent.split(''); +revealText.textContent = ''; +const middle = letters.filter(e => e !== ' ').length / 2; letters.forEach((letter, i) => { - let span = document.createElement("span"); - span.textContent = letter; - span.style.animationDelay = `${delay + Math.abs(i - middle) * 0.1}s`; - revealText.append(span); + const span = document.createElement('span'); + span.textContent = letter; + span.style.animationDelay = `${delay + Math.abs(i - middle) * 0.1}s`; + revealText.append(span); }); diff --git a/src/config/config.default.ts b/src/config/config.default.ts index 977d5a3..624de35 100644 --- a/src/config/config.default.ts +++ b/src/config/config.default.ts @@ -14,9 +14,7 @@ export default (appInfo: EggAppInfo) => { // 模板渲染 用法 https://nunjucks.bootcss.com config.view = { - root: [ - path.join(appInfo.baseDir, 'app/view'), - ].join(','), + root: [path.join(appInfo.baseDir, 'app/view')].join(','), defaultViewEngine: 'nunjucks', defaultExtension: '.html', mapping: { @@ -37,7 +35,9 @@ export default (appInfo: EggAppInfo) => { // 修改默认的 favicon.ico config.siteFile = { - '/favicon.ico': fs.readFileSync(path.join(appInfo.baseDir, 'app/public/favicon.ico')), + '/favicon.ico': fs.readFileSync( + path.join(appInfo.baseDir, 'app/public/favicon.ico') + ), }; // 关闭安全校验 @@ -51,7 +51,7 @@ export default (appInfo: EggAppInfo) => { config.cool = { // 全局路由前缀 router: { - prefix: '' + prefix: '', }, // 单点登录 sso: false, @@ -64,7 +64,7 @@ export default (appInfo: EggAppInfo) => { // 2小时过期,需要用刷新token expire: 2 * 3600, // 15天内,如果没操作过就需要重新登录 - refreshExpire: 24 * 3600 * 15 + refreshExpire: 24 * 3600 * 15, }, }, // 分页配置 @@ -75,20 +75,20 @@ export default (appInfo: EggAppInfo) => { // 文件上传 file: { // 文件路径前缀 本地上传模式下 有效 - domain: 'https://cool-admin.cn.utools.club' - } - } + domain: 'https://admin.cn.utools.club', + }, + }; // 文件上传 config.multipart = { fileSize: '100mb', - mode: 'file' + mode: 'file', }; // 将egg日志替换成midway config.midwayFeature = { - replaceEggLogger: true - } + replaceEggLogger: true, + }; return config; }; diff --git a/src/config/config.local.ts b/src/config/config.local.ts index 766c683..c37f1ee 100644 --- a/src/config/config.local.ts +++ b/src/config/config.local.ts @@ -3,26 +3,26 @@ import { EggAppConfig, EggAppInfo, PowerPartial } from 'egg'; export type DefaultConfig = PowerPartial; export default (appInfo: EggAppInfo) => { - const config = {} as DefaultConfig; + const config = {} as DefaultConfig; - config.orm = { - type: 'mysql', - host: '127.0.0.1', - port: 3306, - username: 'root', - password: '123123', - database: 'cool', - // 自动建表 注意:线上部署的时候不要使用,有可能导致数据丢失 - synchronize: true, - // 打印日志 - logging: true, - } + config.orm = { + type: 'mysql', + host: '127.0.0.1', + port: 3306, + username: 'root', + password: '123123', + database: 'cool', + // 自动建表 注意:线上部署的时候不要使用,有可能导致数据丢失 + synchronize: true, + // 打印日志 + logging: true, + }; - config.logger = { - coreLogger: { - consoleLevel: 'INFO' - } - } + config.logger = { + coreLogger: { + consoleLevel: 'INFO', + }, + }; - return config; + return config; }; diff --git a/src/config/config.prod.ts b/src/config/config.prod.ts index 33c1b3b..4ce3e10 100644 --- a/src/config/config.prod.ts +++ b/src/config/config.prod.ts @@ -3,26 +3,26 @@ import { EggAppConfig, EggAppInfo, PowerPartial } from 'egg'; export type DefaultConfig = PowerPartial; export default (appInfo: EggAppInfo) => { - const config = {} as DefaultConfig; + const config = {} as DefaultConfig; - config.orm = { - type: 'mysql', - host: '127.0.0.1', - port: 3306, - username: 'root', - password: '123123', - database: 'cool-admin-next', - // 自动建表 注意:线上部署的时候不要使用,有可能导致数据丢失 - synchronize: false, - // 打印日志 - logging: false, - } + config.orm = { + type: 'mysql', + host: '127.0.0.1', + port: 3306, + username: 'root', + password: '123123', + database: 'cool-admin-next', + // 自动建表 注意:线上部署的时候不要使用,有可能导致数据丢失 + synchronize: false, + // 打印日志 + logging: false, + }; - config.logger = { - coreLogger: { - consoleLevel: 'ERROR' - } - } + config.logger = { + coreLogger: { + consoleLevel: 'ERROR', + }, + }; - return config; + return config; }; diff --git a/src/config/plugin.ts b/src/config/plugin.ts index f46230d..f8e751c 100755 --- a/src/config/plugin.ts +++ b/src/config/plugin.ts @@ -6,5 +6,5 @@ export default { nunjucks: { enable: true, package: 'egg-view-nunjucks', - } + }, } as EggPlugin; diff --git a/src/configuration.ts b/src/configuration.ts index ad89d0d..4cc2bb1 100644 --- a/src/configuration.ts +++ b/src/configuration.ts @@ -3,6 +3,7 @@ import { ILifeCycle, IMidwayContainer } from '@midwayjs/core'; import { Application } from 'egg'; import * as orm from '@midwayjs/orm'; import * as cool from 'midwayjs-cool-core'; +import * as redis from 'midwayjs-cool-redis'; @Configuration({ // 注意组件顺序 cool 有依赖orm组件, 所以必须放在,orm组件之后 cool的其他组件必须放在cool 核心组件之后 @@ -10,20 +11,17 @@ import * as cool from 'midwayjs-cool-core'; // 必须,不可移除, https://typeorm.io 打不开? https://typeorm.biunav.com/zh/ orm, // 必须,不可移除, cool-admin 官方组件 https://www.cool-js.com - cool - ] + cool, + redis, + ], }) export class ContainerLifeCycle implements ILifeCycle { - @App() app: Application; // 应用启动完成 async onReady(container?: IMidwayContainer) { - console.log(container.baseDir) - + console.log(container.baseDir); } // 应用停止 - async onStop() { - - } + async onStop() {} } diff --git a/src/welcome.ts b/src/welcome.ts index 5fe0263..98e53ba 100644 --- a/src/welcome.ts +++ b/src/welcome.ts @@ -8,12 +8,11 @@ import { CoolController, BaseController } from 'midwayjs-cool-core'; @Provide() @CoolController('/') export class WelcomeController extends BaseController { + @Inject() + ctx: Context; - @Inject() - ctx: Context; - - @Get('/') - public async welcome () { - await this.ctx.render('welcome', { text: 'HELLO COOL-ADMIN' }); - } -} \ No newline at end of file + @Get('/') + public async welcome() { + await this.ctx.render('welcome', { text: 'HELLO COOL-ADMIN' }); + } +} diff --git a/tsconfig.json b/tsconfig.json index a5037a3..ca72ae0 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -20,4 +20,4 @@ "node_modules", "test" ] -} \ No newline at end of file +}