midway-fatcms 0.0.1-beta.25 → 0.0.1-beta.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/dist/controller/home.controller.js +2 -1
  2. package/dist/controller/render/AppRenderController.js +2 -1
  3. package/dist/models/bizmodels.d.ts +1 -0
  4. package/dist/service/asyncTask/handler/ExportExcelAsyncTaskHandler.js +1 -1
  5. package/dist/service/crudstd/CrudStdService.d.ts +0 -6
  6. package/dist/service/crudstd/CrudStdService.js +13 -33
  7. package/package.json +1 -5
  8. package/src/config/config.default.ts +0 -207
  9. package/src/config/seed/aeskey.txt +0 -1
  10. package/src/config/utils.ts +0 -22
  11. package/src/configuration.ts +0 -109
  12. package/src/controller/base/BaseApiController.ts +0 -170
  13. package/src/controller/gateway/AnyApiGatewayController.ts +0 -33
  14. package/src/controller/gateway/AsyncTaskController.ts +0 -157
  15. package/src/controller/gateway/CrudMtdGatewayController.ts +0 -111
  16. package/src/controller/gateway/CrudStdGatewayController.ts +0 -101
  17. package/src/controller/gateway/DocGatewayController.ts +0 -173
  18. package/src/controller/gateway/FileController.ts +0 -109
  19. package/src/controller/gateway/ProxyApiGatewayController.ts +0 -47
  20. package/src/controller/gateway/PublicApiController.ts +0 -142
  21. package/src/controller/gateway/StaticController.ts +0 -298
  22. package/src/controller/helpers.controller.ts +0 -161
  23. package/src/controller/home.controller.ts +0 -64
  24. package/src/controller/manage/AnyApiMangeApi.ts +0 -66
  25. package/src/controller/manage/AppLogMangeApi.ts +0 -53
  26. package/src/controller/manage/AppMangeApi.ts +0 -53
  27. package/src/controller/manage/AppPageMangeApi.ts +0 -52
  28. package/src/controller/manage/AppSchemaHistoryApi.ts +0 -49
  29. package/src/controller/manage/CrudMethodsMangeApi.ts +0 -49
  30. package/src/controller/manage/CrudStandardDesignApi.ts +0 -346
  31. package/src/controller/manage/DataDictManageApi.ts +0 -78
  32. package/src/controller/manage/DeployManageApi.ts +0 -175
  33. package/src/controller/manage/DocLibManageApi.ts +0 -69
  34. package/src/controller/manage/DocManageApi.ts +0 -99
  35. package/src/controller/manage/FileManageApi.ts +0 -45
  36. package/src/controller/manage/LowCodeTplManageApi.ts +0 -52
  37. package/src/controller/manage/MenuManageApi.ts +0 -58
  38. package/src/controller/manage/ProxyApiMangeApi.ts +0 -52
  39. package/src/controller/manage/SuperAdminManageApi.ts +0 -139
  40. package/src/controller/manage/SysConfigMangeApi.ts +0 -95
  41. package/src/controller/manage/SystemInfoManageApi.ts +0 -53
  42. package/src/controller/manage/UserAccountManageApi.ts +0 -94
  43. package/src/controller/manage/WorkbenchMangeApi.ts +0 -72
  44. package/src/controller/myinfo/AuthController.ts +0 -108
  45. package/src/controller/myinfo/MyInfoController.ts +0 -32
  46. package/src/controller/render/AppRenderController.ts +0 -79
  47. package/src/controller/test.controller.ts +0 -37
  48. package/src/filter/default.filter.ts +0 -13
  49. package/src/filter/notfound.filter.ts +0 -10
  50. package/src/index.ts +0 -106
  51. package/src/interface.ts +0 -31
  52. package/src/libs/crud-pro/CrudPro.ts +0 -165
  53. package/src/libs/crud-pro/defaultConfigs.ts +0 -15
  54. package/src/libs/crud-pro/exceptions.ts +0 -124
  55. package/src/libs/crud-pro/interfaces.ts +0 -190
  56. package/src/libs/crud-pro/models/ExecuteContext.ts +0 -120
  57. package/src/libs/crud-pro/models/ExecuteContextFunc.ts +0 -96
  58. package/src/libs/crud-pro/models/FuncContext.ts +0 -21
  59. package/src/libs/crud-pro/models/RequestCfgModel.ts +0 -141
  60. package/src/libs/crud-pro/models/RequestModel.ts +0 -141
  61. package/src/libs/crud-pro/models/ResModel.ts +0 -19
  62. package/src/libs/crud-pro/models/ServiceHub.ts +0 -32
  63. package/src/libs/crud-pro/models/SqlCfgModel.ts +0 -52
  64. package/src/libs/crud-pro/models/SqlSegArg.ts +0 -13
  65. package/src/libs/crud-pro/models/Transaction.ts +0 -73
  66. package/src/libs/crud-pro/models/TransactionMySQL.ts +0 -79
  67. package/src/libs/crud-pro/models/TransactionPostgres.ts +0 -91
  68. package/src/libs/crud-pro/models/TransactionSqlServer.ts +0 -102
  69. package/src/libs/crud-pro/models/keys.ts +0 -159
  70. package/src/libs/crud-pro/services/CrudProCachedCfgService.ts +0 -83
  71. package/src/libs/crud-pro/services/CrudProExecuteFuncService.ts +0 -128
  72. package/src/libs/crud-pro/services/CrudProExecuteSqlService.ts +0 -262
  73. package/src/libs/crud-pro/services/CrudProFieldUpdateService.ts +0 -60
  74. package/src/libs/crud-pro/services/CrudProFieldValidateService.ts +0 -180
  75. package/src/libs/crud-pro/services/CrudProGenSqlCondition.ts +0 -354
  76. package/src/libs/crud-pro/services/CrudProGenSqlService.ts +0 -185
  77. package/src/libs/crud-pro/services/CrudProOriginToExecuteSql.ts +0 -393
  78. package/src/libs/crud-pro/services/CrudProServiceBase.ts +0 -94
  79. package/src/libs/crud-pro/services/CrudProTableMetaService.ts +0 -86
  80. package/src/libs/crud-pro/services/CurdProServiceHub.ts +0 -92
  81. package/src/libs/crud-pro/sql.txt +0 -120
  82. package/src/libs/crud-pro/utils/CompareUtils.ts +0 -23
  83. package/src/libs/crud-pro/utils/DatabaseName.ts +0 -60
  84. package/src/libs/crud-pro/utils/DateTimeUtils.ts +0 -20
  85. package/src/libs/crud-pro/utils/MemoryRefreshCache.ts +0 -64
  86. package/src/libs/crud-pro/utils/MessageParseUtils.ts +0 -33
  87. package/src/libs/crud-pro/utils/MixinUtils.ts +0 -285
  88. package/src/libs/crud-pro/utils/ModelUtils.ts +0 -55
  89. package/src/libs/crud-pro/utils/MultiKeyMap.ts +0 -72
  90. package/src/libs/crud-pro/utils/SqlFuncUtils.ts +0 -29
  91. package/src/libs/crud-pro/utils/TypeUtils.ts +0 -188
  92. package/src/libs/crud-pro/utils/ValidateUtils.ts +0 -165
  93. package/src/libs/crud-pro/utils/pool/MySQLUtils.ts +0 -20
  94. package/src/libs/crud-pro/utils/pool/PostgresUtils.ts +0 -22
  95. package/src/libs/crud-pro/utils/pool/SqlServerUtils.ts +0 -22
  96. package/src/libs/crud-pro/utils/sqlConvert/convertColumnName.ts +0 -26
  97. package/src/libs/crud-pro/utils/sqlConvert/convertMix.ts +0 -26
  98. package/src/libs/crud-pro/utils/sqlConvert/convertMsSql.ts +0 -11
  99. package/src/libs/crud-pro/utils/sqlConvert/convertPgSql.ts +0 -11
  100. package/src/libs/crud-pro/utils/sqlConvert/convertPgType.ts +0 -129
  101. package/src/libs/global-config/global-config.ts +0 -78
  102. package/src/libs/utils/common-dto.ts +0 -52
  103. package/src/libs/utils/crypto-utils.ts +0 -50
  104. package/src/libs/utils/errorToString.ts +0 -61
  105. package/src/libs/utils/fatcms-request.ts +0 -103
  106. package/src/libs/utils/functions.ts +0 -73
  107. package/src/libs/utils/ordernum-utils.ts +0 -14
  108. package/src/libs/utils/parseConfig.ts +0 -54
  109. package/src/libs/utils/parseCreateSql.ts +0 -91
  110. package/src/libs/utils/render-utils.ts +0 -184
  111. package/src/middleware/forbidden.middleware.ts +0 -52
  112. package/src/middleware/global.middleware.ts +0 -280
  113. package/src/middleware/permission.middleware.ts +0 -80
  114. package/src/middleware/tx.middleware.ts +0 -30
  115. package/src/models/AsyncTaskModel.ts +0 -82
  116. package/src/models/RedisKeys.ts +0 -13
  117. package/src/models/SystemEntities.ts +0 -115
  118. package/src/models/SystemPerm.ts +0 -105
  119. package/src/models/SystemTables.ts +0 -27
  120. package/src/models/bizmodels.ts +0 -120
  121. package/src/models/contextLogger.ts +0 -132
  122. package/src/models/devops.ts +0 -17
  123. package/src/models/userSession.ts +0 -216
  124. package/src/schedule/anonymousContext.ts +0 -73
  125. package/src/schedule/index.ts +0 -12
  126. package/src/schedule/runSchedule.ts +0 -82
  127. package/src/schedule/scheduleNames.ts +0 -21
  128. package/src/service/AuthService.ts +0 -272
  129. package/src/service/EnumInfoService.ts +0 -130
  130. package/src/service/FileCenterService.ts +0 -395
  131. package/src/service/SysConfigService.ts +0 -37
  132. package/src/service/UserAccountService.ts +0 -107
  133. package/src/service/UserSessionService.ts +0 -78
  134. package/src/service/VisitStatService.ts +0 -166
  135. package/src/service/WorkbenchService.ts +0 -165
  136. package/src/service/anyapi/AnyApiSandboxService.ts +0 -121
  137. package/src/service/anyapi/AnyApiService.ts +0 -186
  138. package/src/service/asyncTask/AsyncTaskRunnerService.ts +0 -266
  139. package/src/service/asyncTask/AsyncTaskService.ts +0 -21
  140. package/src/service/asyncTask/handler/ExcelInfoModel.ts +0 -11
  141. package/src/service/asyncTask/handler/ExportExcelAsyncTaskHandler.ts +0 -245
  142. package/src/service/asyncTask/handler/ExportExcelByInnerHttpHandler.ts +0 -147
  143. package/src/service/asyncTask/handler/ExportExcelByStdCrudHandler.ts +0 -138
  144. package/src/service/base/ApiBaseService.ts +0 -42
  145. package/src/service/base/ApiRateLimiter.ts +0 -59
  146. package/src/service/base/BaseService.ts +0 -100
  147. package/src/service/base/RedisCacheService.ts +0 -38
  148. package/src/service/crudstd/CrudStdActionService.ts +0 -27
  149. package/src/service/crudstd/CrudStdConstant.ts +0 -62
  150. package/src/service/crudstd/CrudStdRelationService.ts +0 -78
  151. package/src/service/crudstd/CrudStdService.ts +0 -283
  152. package/src/service/curd/CrudProQuick.ts +0 -131
  153. package/src/service/curd/CurdMixByAccountService.ts +0 -90
  154. package/src/service/curd/CurdMixByDictService.ts +0 -114
  155. package/src/service/curd/CurdMixByLinkToCustomService.ts +0 -219
  156. package/src/service/curd/CurdMixBySysConfigService.ts +0 -78
  157. package/src/service/curd/CurdMixByWorkbenchService.ts +0 -71
  158. package/src/service/curd/CurdMixService.ts +0 -97
  159. package/src/service/curd/CurdMixUtils.ts +0 -311
  160. package/src/service/curd/CurdProService.ts +0 -229
  161. package/src/service/curd/fixCfgModel.ts +0 -139
  162. package/src/service/proxyapi/ProxyApiLoadService.ts +0 -174
  163. package/src/service/proxyapi/ProxyApiService.ts +0 -262
  164. package/src/service/proxyapi/ProxyApiUtils.ts +0 -32
  165. package/src/service/proxyapi/RouteHandler.ts +0 -8
  166. package/src/service/proxyapi/RouteTrie.ts +0 -74
  167. package/src/service/proxyapi/WeightedRandom.ts +0 -37
  168. package/src/service/proxyapi/WeightedRoundRobin.ts +0 -44
  169. package/src/views/404_app.html +0 -31
  170. package/src/views/404_workbench.html +0 -34
  171. package/src/views/static/favicon.ico +0 -0
@@ -1,78 +0,0 @@
1
- import { Inject, Provide } from '@midwayjs/core';
2
- import { Context } from '@midwayjs/koa';
3
- import { parseJsonObject } from '@/libs/utils/functions';
4
- import { ISessionInfo, SESSION_ID_KEY, sessionCookieCfg } from '@/models/userSession';
5
- import { RedisCacheService } from './base/RedisCacheService';
6
- import { RedisKeys } from '@/models/RedisKeys';
7
-
8
- function pickUserAvatar(avatar: any): string {
9
- if (!avatar) {
10
- return null;
11
- }
12
- if (typeof avatar === 'string') {
13
- if (avatar.startsWith('http') || avatar.startsWith('/')) {
14
- return avatar;
15
- }
16
- const obj = parseJsonObject(avatar);
17
- if (!obj) {
18
- return null;
19
- }
20
- if (Array.isArray(obj)) {
21
- return pickUserAvatar(obj[0]);
22
- }
23
- return pickUserAvatar(obj);
24
- }
25
-
26
- if (avatar && avatar.imgURL) {
27
- return avatar.imgURL;
28
- }
29
- if (avatar && avatar.downloadURL) {
30
- return avatar.downloadURL;
31
- }
32
- return null;
33
- }
34
-
35
- const SESSION_KEEP_TIME_SECOND: number = 3600 * 24 * 30;
36
-
37
- const toCacheKey = (sessionId: string): string => {
38
- return `${RedisKeys.USER_SESSION_PREFIX}${sessionId}`;
39
- };
40
-
41
- @Provide()
42
- export class UserSessionService {
43
- @Inject()
44
- private ctx: Context;
45
-
46
- @Inject()
47
- private redisCacheService: RedisCacheService;
48
-
49
- public async saveUserSession(sessionInfo: ISessionInfo) {
50
- sessionInfo.avatar = pickUserAvatar(sessionInfo.avatar);
51
- const sessionId = sessionInfo.sessionId;
52
- await this.redisCacheService.setJsonObject(toCacheKey(sessionId), sessionInfo, SESSION_KEEP_TIME_SECOND);
53
- }
54
-
55
- /**
56
- * 移除Session
57
- * @param sessionId
58
- */
59
- public async removeUserSession(sessionId: string) {
60
- return await this.redisCacheService.removeItem(toCacheKey(sessionId));
61
- }
62
-
63
- private async getCurrentUserSessionForMiddleware1(sessionId: string): Promise<ISessionInfo> {
64
- if (!sessionId) {
65
- return null;
66
- }
67
- return await this.redisCacheService.getJsonObject(toCacheKey(sessionId));
68
- }
69
-
70
- /**
71
- * 专门给中间件点调用的
72
- */
73
- public async getCurrentUserSessionForMiddleware(): Promise<ISessionInfo> {
74
- const cookies = this.ctx.cookies;
75
- const sessionId = cookies.get(SESSION_ID_KEY, sessionCookieCfg);
76
- return this.getCurrentUserSessionForMiddleware1(sessionId);
77
- }
78
- }
@@ -1,166 +0,0 @@
1
- import { Inject, Provide } from '@midwayjs/core';
2
- import { Context } from '@midwayjs/koa';
3
- import { IScheduleService } from '@/interface';
4
- import { BaseService } from './base/BaseService';
5
- import { CurdProService } from './curd/CurdProService';
6
- import { SystemTables } from '@/models/SystemTables';
7
- import { KeysOfSimpleSQL } from '@/libs/crud-pro/models/keys';
8
- import { FILE_GET_TYPES } from '@/models/bizmodels';
9
- import { CommonResult } from '@/libs/utils/common-dto';
10
- import { GLOBAL_STATIC_CONFIG } from '@/libs/global-config/global-config';
11
- import { RedisKeys } from '@/models/RedisKeys';
12
-
13
- // 3天 的秒数
14
- const EXPIRE_TIME = 3 * 24 * 60 * 60;
15
-
16
- const STAT_TYPES = {
17
- pv: 'pv',
18
- uv_ip: 'uv_ip',
19
- uv_uid: 'uv_uid',
20
- };
21
-
22
- @Provide()
23
- export class VisitStatService extends BaseService implements IScheduleService {
24
- @Inject()
25
- protected ctx: Context;
26
-
27
- @Inject()
28
- private curdProService: CurdProService;
29
-
30
- async runBySchedule(): Promise<any> {
31
- const hours = new Date().getHours();
32
- this.logInfo('[VisitStatService] runBySchedule called, hours = ' + hours);
33
- return this.flushVisitStatToDB();
34
- }
35
-
36
- async flushVisitStatToDB(): Promise<any> {
37
- const { SystemDbName, SystemDbType } = GLOBAL_STATIC_CONFIG.getConfig();
38
-
39
- // 统计昨天的数据。
40
- const stat_date = new Date(Date.now() - 24 * 3600 * 1000).toISOString().split('T')[0];
41
-
42
- const lockKey = `${RedisKeys.VISIT_STAT_LOCK_PREFIX}${stat_date}`;
43
- // 每天只能执行一次
44
- const client = this.redisService;
45
- const nxRes = await client.set(lockKey, 1, 'EX', EXPIRE_TIME, 'NX');
46
- if (nxRes !== 'OK') {
47
- this.logInfo('[VisitStatService] flushVisitStatToDB 每天只能执行一次 ');
48
- return CommonResult.errorRes('每天只能执行一次');
49
- }
50
-
51
- this.logInfo('[VisitStatService] flushVisitStatToDB start ');
52
-
53
- let totalCount = 0;
54
- let successCount = 0;
55
-
56
- try {
57
- const keys = await client.keys(`${RedisKeys.VISIT_STAT_DATE_PREFIX}${stat_date}::*`);
58
- // `vs_${date}::${req_host}::${resource_type}::${stat_type}::${resource}`;
59
- totalCount = keys.length;
60
-
61
- for (const key of keys) {
62
- try {
63
- const parts = key.split('::');
64
- if (parts.length === 5) {
65
- const req_host = parts[1];
66
- const resource_type = parts[2];
67
- const stat_type = parts[3];
68
- const stat_resource = parts[4];
69
-
70
- let stat_count: number;
71
- if (stat_type === STAT_TYPES.uv_ip || stat_type === STAT_TYPES.uv_uid) {
72
- stat_count = await client.scard(key);
73
- } else {
74
- stat_count = parseInt(await client.get(key)) || 0;
75
- }
76
-
77
- await this.curdProService.executeCrudByCfg(
78
- {
79
- data: {
80
- stat_date,
81
- stat_resource,
82
- stat_type,
83
- resource_type,
84
- stat_count,
85
- req_host,
86
- },
87
- },
88
- {
89
- sqlSimpleName: KeysOfSimpleSQL.SIMPLE_INSERT,
90
- sqlDatabase: SystemDbName,
91
- sqlDbType: SystemDbType,
92
- sqlTable: SystemTables.sys_visit_stats,
93
- }
94
- );
95
-
96
- await client.del(key);
97
- successCount++;
98
- }
99
- } catch (e) {
100
- this.logError('[VisitStatService] flushVisitStatToDB: key = ' + key, e);
101
- console.log('[VisitStatService] flushVisitStatToDB: key = ' + key, e);
102
- }
103
- }
104
- } catch (error) {
105
- this.logError('[VisitStatService] flushVisitStatToDB', error);
106
- console.log('[VisitStatService] flushVisitStatToDB', error);
107
- }
108
-
109
- this.logInfo('[VisitStatService] flushVisitStatToDB end ');
110
-
111
- return CommonResult.successRes({ successCount, totalCount });
112
- }
113
-
114
- /**
115
- * 统计请求数据
116
- */
117
- async trackRequest(resource: string, resourceType: string) {
118
- // 文件下载定制
119
- if (resource.startsWith('/ns/gw/file/get/')) {
120
- for (let i = 0; i < FILE_GET_TYPES.length; i++) {
121
- const fileGetType = FILE_GET_TYPES[i];
122
- const pathPrefix = `/ns/gw/file/get/${fileGetType}/`;
123
- if (resource.startsWith(pathPrefix)) {
124
- const res2 = resource.substring(pathPrefix.length);
125
- return this.trackRequestImpl(res2, fileGetType);
126
- }
127
- }
128
- }
129
-
130
- // 文档访问定制
131
- if (resource.startsWith('/ns/app/doc-editor/libview')) {
132
- const { docLibId, docId } = this.ctx.query || {};
133
- return this.trackRequestImpl(`${docLibId},${docId}`, 'docLibView');
134
- }
135
-
136
- return this.trackRequestImpl(resource, resourceType);
137
- }
138
-
139
- private async trackRequestImpl(resource: string, resource_type: string) {
140
- const client = this.redisService;
141
- const ip = this.ctx.headers['x-real-ip'];
142
- const userSession = this.ctx.userSession;
143
- const req_host = this.ctx?.request?.host || 'null'; // 域名
144
- const date = new Date().toISOString().split('T')[0];
145
-
146
- const toDateResourceKey = (stat_type: string): string => {
147
- return `${RedisKeys.VISIT_STAT_DATE_PREFIX}${date}::${req_host}::${resource_type}::${stat_type}::${resource}`;
148
- };
149
-
150
- const pv_key = toDateResourceKey(STAT_TYPES.pv);
151
- const uv_ip_key = toDateResourceKey(STAT_TYPES.uv_ip);
152
- const uv_uid_key = toDateResourceKey(STAT_TYPES.uv_uid);
153
-
154
- // 统计 PV
155
- await Promise.all([client.incr(pv_key), client.expire(pv_key, EXPIRE_TIME)]);
156
-
157
- // IP 访问 UV
158
- await Promise.all([client.sadd(uv_ip_key, `${ip}`), client.expire(uv_ip_key, EXPIRE_TIME)]);
159
-
160
- if (userSession && userSession.isLogin()) {
161
- const accountId = userSession.getSessionInfo().accountId;
162
- // 统计 UV
163
- await Promise.all([client.sadd(uv_uid_key, accountId), client.expire(uv_uid_key, EXPIRE_TIME)]);
164
- }
165
- }
166
- }
@@ -1,165 +0,0 @@
1
- import { Inject, Provide } from '@midwayjs/core';
2
- import { Context } from '@midwayjs/koa';
3
- import { KeysOfSimpleSQL } from '@/libs/crud-pro/models/keys';
4
- import { SystemTables } from '@/models/SystemTables';
5
- import { BaseService } from './base/BaseService';
6
- // import { LRUCache } from 'lru-cache';
7
- import { CurdProService } from './curd/CurdProService';
8
- import { CommonException } from '@/libs/crud-pro/exceptions';
9
- import { parseJsonObject } from '@/libs/utils/functions';
10
- import { IWorkbenchEntity } from '@/models/SystemEntities';
11
- import { IScheduleService } from '@/interface';
12
- import { getDebugWorkbenchCode } from '@/libs/utils/fatcms-request';
13
- import { MixinUtils } from '@/libs/crud-pro/utils/MixinUtils';
14
- import { GLOBAL_STATIC_CONFIG } from '@/libs/global-config/global-config';
15
- //
16
- // const lruCache = new LRUCache<string, any>({
17
- // max: 500,
18
- // ttl: 1000 * 60 * 60,
19
- // ttlAutopurge: true,
20
- // });
21
-
22
- const lruCache = new Map<string, any>();
23
-
24
- const CACHE_KEY_WORKBENCH_LIST = 'CACHE_KEY_WORKBENCH_LIST';
25
- const CACHE_KEY_DOMAIN_MAP = 'CACHE_KEY_DOMAIN_MAP';
26
-
27
- @Provide()
28
- export class WorkbenchService extends BaseService implements IScheduleService {
29
- @Inject()
30
- ctx: Context;
31
-
32
- @Inject()
33
- private curdProService: CurdProService;
34
-
35
- public clearCache() {
36
- lruCache.set(CACHE_KEY_WORKBENCH_LIST, null);
37
- lruCache.set(CACHE_KEY_DOMAIN_MAP, null);
38
- }
39
-
40
- public async runBySchedule() {
41
- await this.getAllWorkbenchInfoMap(true);
42
- }
43
-
44
- public async getAllWorkbenchInfoList(isForceRefresh?: boolean): Promise<IWorkbenchEntity[]> {
45
- const { SystemDbName, SystemDbType } = GLOBAL_STATIC_CONFIG.getConfig();
46
-
47
- let listData = lruCache.get(CACHE_KEY_WORKBENCH_LIST);
48
- if (!listData || isForceRefresh === true) {
49
- const reqJson = { condition: {}, pageSize: 1000, limit: 1000 };
50
- const res = await this.curdProService.executeCrudByCfg(reqJson, {
51
- sqlTable: SystemTables.sys_workbench,
52
- sqlSimpleName: KeysOfSimpleSQL.SIMPLE_QUERY,
53
- sqlDatabase: SystemDbName,
54
- sqlDbType: SystemDbType,
55
- });
56
- listData = res.getResRows();
57
- lruCache.set(CACHE_KEY_WORKBENCH_LIST, listData);
58
- }
59
- return listData;
60
- }
61
-
62
- public async getAllWorkbenchInfoMap(isForceRefresh?: boolean): Promise<Record<any, IWorkbenchEntity>> {
63
- let listData: any[];
64
- let domainMap = lruCache.get(CACHE_KEY_DOMAIN_MAP);
65
- if (!domainMap || isForceRefresh === true) {
66
- listData = await this.getAllWorkbenchInfoList(isForceRefresh);
67
- const domainMap1 = MixinUtils.toMap(listData, (e: any) => e.workbench_domain); // 主域名。其他两个域名。
68
- const domainMap2 = MixinUtils.toMap(listData, (e: any) => e.workbench_domain2);
69
- const domainMap3 = MixinUtils.toMap(listData, (e: any) => e.workbench_domain3);
70
- domainMap = { ...domainMap1, ...domainMap2, ...domainMap3 };
71
- lruCache.set(CACHE_KEY_DOMAIN_MAP, domainMap);
72
- }
73
- return domainMap;
74
- }
75
-
76
- public isMatchWorkbenchCode(workbench_code_array: string | string[], workbench_code: string): boolean {
77
- if (workbench_code_array === '*') {
78
- return true;
79
- }
80
- const supportWorkbenchArray = parseJsonObject(workbench_code_array)
81
- .map(s => s.trim())
82
- .filter(Boolean);
83
-
84
- return supportWorkbenchArray.includes('*') || supportWorkbenchArray.includes(workbench_code);
85
- }
86
-
87
- /**
88
- * 获取当前请求的域名所对应的站点信息
89
- */
90
- public async getCurrentHostWorkbenchInfo(): Promise<IWorkbenchEntity> {
91
- // 本地调试模式
92
- if (this.isEnableDebug() && this.isLocalEnv()) {
93
- const debugWorkbenchCode = getDebugWorkbenchCode(this.ctx);
94
- if (!debugWorkbenchCode) {
95
- throw new CommonException('本地环境调试时需要使用ModHeader浏览器插件,指定站点编码');
96
- }
97
- const list = await this.getAllWorkbenchInfoList();
98
- for (let i = 0; i < list.length; i++) {
99
- const workbenchInfo = list[i];
100
- if (workbenchInfo.workbench_code === debugWorkbenchCode) {
101
- return workbenchInfo;
102
- }
103
- }
104
- return null;
105
- }
106
-
107
- //正式环境: 根据域名获取站点配置
108
- const host = this.getCurrentHost();
109
- const domainMap = await this.getAllWorkbenchInfoMap();
110
- const workbenchInfo = domainMap[host];
111
- if (workbenchInfo) {
112
- return workbenchInfo;
113
- }
114
- return domainMap['*']; // 最后兜底
115
- }
116
-
117
- private getCurrentHost(): string {
118
- const host = this.ctx.request.host;
119
- if (!host) {
120
- throw new CommonException('GET_CURRENT_HOST_ERROR', '获取当前域名失败');
121
- }
122
- return host;
123
- }
124
-
125
- public async isSupportCurrentWorkbench(workbench_code_array: string | string[]): Promise<boolean> {
126
- // 本地调试模式
127
- if (this.isEnableDebug() && this.isLocalEnv()) {
128
- return true;
129
- }
130
-
131
- if (!workbench_code_array) {
132
- throw new CommonException('IS_SUPPORT_CURRENT_WORKBENCH', '未配置支持的站点字段');
133
- }
134
-
135
- const workbench = await this.getCurrentHostWorkbenchInfo();
136
- if (!workbench) {
137
- throw new CommonException('WORKBENCH_IS_NOT_FOUND', '站点未找到');
138
- }
139
-
140
- const curWorkbenchCode = workbench.workbench_code;
141
- return this.isMatchWorkbenchCode(workbench_code_array, curWorkbenchCode);
142
- }
143
-
144
- public async isSupportCurrentHostForForMiddleware(): Promise<string | boolean> {
145
- // 本地调试模式
146
- if (this.isEnableDebug() && this.isLocalEnv()) {
147
- return true;
148
- }
149
-
150
- const host = this.getCurrentHost();
151
-
152
- const workbenchInfo = await this.getCurrentHostWorkbenchInfo();
153
-
154
- if (!workbenchInfo || workbenchInfo.status !== 1) {
155
- this.logInfo(`域名不存在 host=${host}`);
156
- const infos = {
157
- host,
158
- errorInfo: `ERR_FATCMS_REFUSED <br/> 域名配置不存在 host=${host}`,
159
- };
160
- this.ctx.status = 404;
161
- return this.ctx.render('404_workbench', infos);
162
- }
163
- return true;
164
- }
165
- }
@@ -1,121 +0,0 @@
1
- import { Inject, Provide } from '@midwayjs/core';
2
- import { Context } from '@midwayjs/koa';
3
- import * as vm from 'node:vm';
4
- import { LRUCache } from 'lru-cache';
5
- import { BaseService } from '../base/BaseService';
6
- import { CurdMixService } from '../curd/CurdMixService';
7
- import { ISysAnyApiEntity } from '../../models/SystemEntities';
8
- import axios from 'axios';
9
- import * as _ from 'lodash';
10
- import * as moment from 'moment';
11
- import * as nodemailer from 'nodemailer';
12
-
13
- const scriptCacheOptions = {
14
- max: 500,
15
- ttl: 1000 * 60 * 5,
16
- allowStale: false,
17
- updateAgeOnGet: true,
18
- updateAgeOnHas: true,
19
- };
20
-
21
- const scriptCache = new LRUCache<string, vm.Script>(scriptCacheOptions);
22
-
23
- function getCompiledScript(anyApi: ISysAnyApiEntity, code: string): vm.Script {
24
- const { id, func_code_md5 } = anyApi;
25
- const cacheKey = id + '_' + func_code_md5;
26
- const oldScript = scriptCache.get(cacheKey);
27
- if (oldScript) {
28
- return oldScript;
29
- }
30
- const script = new vm.Script(code);
31
- scriptCache.set(cacheKey, script);
32
- return script;
33
- }
34
-
35
- export interface IRunInSandboxParams {
36
- body: any;
37
- query: any;
38
- headers: any;
39
- params?: any;
40
- }
41
-
42
- @Provide()
43
- export class AnyApiSandboxService extends BaseService {
44
- @Inject()
45
- protected ctx: Context;
46
-
47
- @Inject()
48
- private curdMixService: CurdMixService;
49
-
50
- public async runInSandbox(anyApi: ISysAnyApiEntity, allParams: IRunInSandboxParams) {
51
- const { func_code, method } = anyApi;
52
-
53
- return new Promise((resolve, reject) => {
54
- const logger = this.getPrefixContextLogger(`[AnyApiSandboxService][method=${method}]`);
55
- // 创建一个沙盒上下文
56
- const proc = process;
57
- const newContext = {
58
- sandbox: {
59
- allParams,
60
- logger,
61
- moment,
62
- axios,
63
- nodemailer,
64
- _,
65
- userSession: this.ctx.userSession,
66
- ctx: this.ctx,
67
- curdMixService: this.curdMixService,
68
- redisService: this.redisService,
69
- publicOSSService: this.getPublicOSSService(),
70
- privateOSSService: this.getPrivateOSSService(),
71
- returnSuccess: resolve,
72
- returnError: reject,
73
- processInfo: {
74
- version: proc.version,
75
- versions: proc.versions,
76
- env: process.env,
77
- argv: process.argv,
78
- cwd: process.cwd(),
79
- },
80
- },
81
- console: logger,
82
- JSON: JSON,
83
- };
84
-
85
- const nextLine100 = new Array(10).fill('\n').join('');
86
- const bindCode = this.toBindCodeString('httpController', newContext, 'sandbox');
87
- const code = `
88
- (async () => {
89
- ${nextLine100}${func_code}; // 必须有一个 class HttpController { async handleRequest(params){} }
90
- ${nextLine100}
91
- try {
92
- const httpController = new HttpController();
93
- ${bindCode}
94
- const res = await httpController.handleRequest(sandbox.allParams.params);
95
- sandbox.returnSuccess(res);
96
- } catch (e) {
97
- sandbox.returnError(e)
98
- }
99
- })(); `;
100
-
101
- try {
102
- const script = getCompiledScript(anyApi, code);
103
- script.runInNewContext(newContext, {
104
- filename: 'method',
105
- timeout: anyApi.timeout_ms || 1000 * 60 * 5,
106
- });
107
- } catch (e) {
108
- reject(e);
109
- }
110
- });
111
- }
112
-
113
- private toBindCodeString(toName: string, newContext: any, fromName: any): string {
114
- const keys = Object.keys(newContext[fromName]);
115
- return keys
116
- .map(key => {
117
- return `${toName}.${key} = ${fromName}.${key};\n`;
118
- })
119
- .join('');
120
- }
121
- }