e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
1
|
using System.Text.RegularExpressions;
|
a60a45f4
李曜臣
2026-07-21
|
2
|
using FoodLabeling.Th.Application.Contracts.Dtos.MultiTenancy;
|
a60a45f4
李曜臣
2026-07-21
|
3
|
using FoodLabeling.Th.Application.Contracts.IServices;
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
4
|
using FoodLabeling.Th.Application.Contracts.Options;
|
a60a45f4
李曜臣
2026-07-21
|
5
|
using FoodLabeling.Th.Application.MultiTenancy;
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
6
7
|
using FoodLabeling.Th.Domain.Entities;
using FoodLabeling.Th.Domain.Shared.Helpers;
|
a60a45f4
李曜臣
2026-07-21
|
8
|
using Microsoft.AspNetCore.Authorization;
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
9
|
using Microsoft.AspNetCore.Mvc;
|
a60a45f4
李曜臣
2026-07-21
|
10
|
using Microsoft.Extensions.Options;
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
11
12
13
|
using SqlSugar;
using Volo.Abp;
using Volo.Abp.Application.Dtos;
|
a60a45f4
李曜臣
2026-07-21
|
14
|
using Volo.Abp.Application.Services;
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
15
16
|
using Volo.Abp.Caching;
using Volo.Abp.Domain.Entities;
|
a60a45f4
李曜臣
2026-07-21
|
17
|
using Volo.Abp.MultiTenancy;
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
18
19
20
21
|
using Volo.Abp.Uow;
using Yi.Framework.Rbac.Domain.Entities;
using Yi.Framework.Rbac.Domain.Helpers;
using Yi.Framework.Rbac.Domain.Shared.Consts;
|
a60a45f4
李曜臣
2026-07-21
|
22
|
using Yi.Framework.Rbac.Domain.Shared.Options;
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
23
|
using Yi.Framework.SqlSugarCore.Abstractions;
|
a60a45f4
李曜臣
2026-07-21
|
24
|
using Yi.Framework.TenantManagement.Application.Contracts;
|
a60a45f4
李曜臣
2026-07-21
|
25
|
using Yi.Framework.TenantManagement.Application.Contracts.Dtos;
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
26
|
using Yi.Framework.TenantManagement.Domain;
|
a60a45f4
李曜臣
2026-07-21
|
27
28
29
|
namespace FoodLabeling.Th.Application.Services;
|
a60a45f4
李曜臣
2026-07-21
|
30
|
/// <summary>
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
31
|
/// 泰额版多租户:租户下拉、公司列表与管理员凭据管理
|
a60a45f4
李曜臣
2026-07-21
|
32
|
/// </summary>
|
a60a45f4
李曜臣
2026-07-21
|
33
|
public class ThMultiTenancyAppService : ApplicationService, IThMultiTenancyAppService
|
a60a45f4
李曜臣
2026-07-21
|
34
|
{
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
35
36
37
38
39
40
41
42
43
|
private static readonly Guid ProtectedDefaultTenantId = Guid.Parse("11111111-1111-1111-1111-111111111111");
private const string ProtectedDefaultTenantName = "Default";
private static readonly HashSet<string> ProtectedDatabaseNames = new(StringComparer.OrdinalIgnoreCase)
{
"antis-foodlabeling-host",
"antis-foodlabeling-us"
};
private static readonly Regex SafeDatabaseNameRegex =
new(@"^[a-zA-Z0-9][a-zA-Z0-9_\-]{0,63}$", RegexOptions.Compiled);
|
a60a45f4
李曜臣
2026-07-21
|
44
45
|
private readonly ITenantService _tenantService;
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
46
47
48
|
private readonly ISqlSugarRepository<TenantAggregateRoot, Guid> _tenantRepository;
private readonly ISqlSugarRepository<ThTenantAdminCredentialEntity, Guid> _credentialRepository;
private readonly ISqlSugarRepository<ThTenantMenuPermissionEntity, string> _menuPermissionRepository;
|
a60a45f4
李曜臣
2026-07-21
|
49
|
private readonly TenantSelectCredentialCipher _credentialCipher;
|
a60a45f4
李曜臣
2026-07-21
|
50
|
private readonly RbacOptions _rbacOptions;
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
51
52
53
|
private readonly FoodLabelingThTenantDatabaseOptions _tenantDatabaseOptions;
private readonly DbConnOptions _dbConnOptions;
private readonly IDistributedCache<TenantCacheItem> _tenantCache;
|
a60a45f4
李曜臣
2026-07-21
|
54
55
|
public ThMultiTenancyAppService(
|
a60a45f4
李曜臣
2026-07-21
|
56
|
ITenantService tenantService,
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
57
58
59
|
ISqlSugarRepository<TenantAggregateRoot, Guid> tenantRepository,
ISqlSugarRepository<ThTenantAdminCredentialEntity, Guid> credentialRepository,
ISqlSugarRepository<ThTenantMenuPermissionEntity, string> menuPermissionRepository,
|
a60a45f4
李曜臣
2026-07-21
|
60
|
TenantSelectCredentialCipher credentialCipher,
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
61
62
63
64
|
IOptions<RbacOptions> rbacOptions,
IOptions<FoodLabelingThTenantDatabaseOptions> tenantDatabaseOptions,
IOptions<DbConnOptions> dbConnOptions,
IDistributedCache<TenantCacheItem> tenantCache)
|
a60a45f4
李曜臣
2026-07-21
|
65
|
{
|
a60a45f4
李曜臣
2026-07-21
|
66
|
_tenantService = tenantService;
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
67
68
69
|
_tenantRepository = tenantRepository;
_credentialRepository = credentialRepository;
_menuPermissionRepository = menuPermissionRepository;
|
a60a45f4
李曜臣
2026-07-21
|
70
|
_credentialCipher = credentialCipher;
|
a60a45f4
李曜臣
2026-07-21
|
71
|
_rbacOptions = rbacOptions.Value;
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
72
73
74
|
_tenantDatabaseOptions = tenantDatabaseOptions.Value;
_dbConnOptions = dbConnOptions.Value;
_tenantCache = tenantCache;
|
a60a45f4
李曜臣
2026-07-21
|
75
76
|
}
|
a60a45f4
李曜臣
2026-07-21
|
77
|
/// <summary>
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
78
79
80
|
/// 主库表(DefaultTenantTable)读写须将 CurrentTenant 置空
/// </summary>
private IDisposable UseHostTenantScope() => CurrentTenant.Change(null);
|
a60a45f4
李曜臣
2026-07-21
|
81
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
82
|
/// <summary>
|
a60a45f4
李曜臣
2026-07-21
|
83
|
/// 获取登录页可选租户列表(含默认管理员加密凭据)
|
a60a45f4
李曜臣
2026-07-21
|
84
|
/// </summary>
|
a60a45f4
李曜臣
2026-07-21
|
85
|
/// <remarks>
|
a60a45f4
李曜臣
2026-07-21
|
86
|
/// 供 Web 登录页租户下拉使用;匿名可访问。不返回租户 Id 与数据库连接串。
|
a60a45f4
李曜臣
2026-07-21
|
87
|
///
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
|
/// 示例响应:
/// ```json
/// [
/// {
/// "name": "Default",
/// "creationTime": "2026-01-01T08:00:00",
/// "loginAccount": "admin",
/// "password": "Base64CipherText",
/// "passwordSalt": "Base64Iv"
/// }
/// ]
/// ```
///
/// 字段说明:
/// - name: 租户名称,登录时可传 tenantName
/// - creationTime: 租户创建时间
/// - loginAccount: 管理员登录账号,优先读凭据表,否则为 admin
/// - password: 优先读凭据表 AES 密文,否则 RbacOptions.AdminPassword 加密后返回
/// - passwordSalt: AES IV(Base64),前端解密时使用
/// </remarks>
/// <returns>租户下拉列表</returns>
/// <response code="200">成功返回租户列表</response>
/// <response code="500">加密配置缺失或服务器错误</response>
[AllowAnonymous]
public virtual async Task<List<ThTenantSelectDto>> GetTenantSelectAsync()
{
var page = await _tenantService.GetListAsync(new TenantGetListInput
{
SkipCount = 0,
MaxResultCount = 500
});
var credentialMap = await LoadCredentialMapAsync(page.Items.Select(x => x.Id).ToList());
|
a60a45f4
李曜臣
2026-07-21
|
121
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
|
return page.Items
.Select(x =>
{
credentialMap.TryGetValue(x.Id, out var credential);
var resolved = ResolveEncryptedCredential(credential);
return new ThTenantSelectDto
{
Name = x.Name,
CreationTime = x.CreationTime,
LoginAccount = resolved.LoginAccount,
Password = resolved.Password,
PasswordSalt = resolved.PasswordSalt
};
})
.OrderBy(x => x.Name)
.ToList();
}
/// <summary>
/// 平台管理员分页获取公司(租户)列表及可回显加密凭据
/// </summary>
/// <remarks>
/// 需登录;查询主库 YiTenant,密码优先读 fl_th_tenant_admin_credential,否则回退 RbacOptions.AdminPassword 再 AES 加密返回。
///
/// 示例请求(GET,query/data):
/// ```json
/// {
/// "keyword": "测试",
/// "skipCount": 0,
/// "maxResultCount": 20
/// }
/// ```
///
|
a60a45f4
李曜臣
2026-07-21
|
155
|
/// 示例响应:
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
|
/// ```json
/// {
/// "totalCount": 1,
/// "items": [
/// {
/// "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
/// "name": "测试公司",
/// "creationTime": "2026-01-01T08:00:00",
/// "loginAccount": "admin",
/// "password": "Base64CipherText",
/// "passwordSalt": "Base64Iv"
/// }
/// ]
/// }
/// ```
///
/// 参数说明:
/// - keyword/name: 租户名称模糊匹配(keyword 优先)
/// - skipCount: 跳过条数
/// - maxResultCount: 每页条数
/// </remarks>
/// <param name="input">分页与筛选条件</param>
/// <returns>分页公司列表</returns>
/// <response code="200">成功返回分页列表</response>
/// <response code="401">未登录</response>
/// <response code="500">服务器错误</response>
[Authorize]
[HttpGet("th-multi-tenancy/company-list")]
public virtual async Task<PagedResultDto<ThCompanyListItemDto>> GetCompanyListAsync(ThCompanyListInput input)
{
var nameFilter = !string.IsNullOrWhiteSpace(input.Keyword) ? input.Keyword : input.Name;
var page = await _tenantService.GetListAsync(new TenantGetListInput
{
Name = nameFilter,
SkipCount = input.SkipCount,
MaxResultCount = input.MaxResultCount
});
var tenantIds = page.Items.Select(x => x.Id).ToList();
var credentialMap = await LoadCredentialMapAsync(tenantIds);
var menuPermissionMap = await LoadMenuPermissionMapAsync(tenantIds);
|
a60a45f4
李曜臣
2026-07-21
|
198
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
|
var items = page.Items.Select(x =>
{
credentialMap.TryGetValue(x.Id, out var credential);
var resolved = ResolveEncryptedCredential(credential);
menuPermissionMap.TryGetValue(x.Id, out var menuKeys);
return new ThCompanyListItemDto
{
Id = x.Id,
Name = x.Name,
CreationTime = x.CreationTime,
LoginAccount = resolved.LoginAccount,
Password = resolved.Password,
PasswordSalt = resolved.PasswordSalt,
MenuPermissionKeys = menuKeys ?? new List<string>()
};
}).ToList();
return new PagedResultDto<ThCompanyListItemDto>(page.TotalCount, items);
}
/// <summary>
/// 修改公司(租户)默认管理员登录账号与/或密码
/// </summary>
/// <remarks>
/// 需登录。password/passwordSalt 均为空时不改密码;有 password 时必须带 passwordSalt,后端解密后再写入租户库 User 哈希。
///
/// 示例请求:
|
a60a45f4
李曜臣
2026-07-21
|
226
|
/// ```json
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
|
/// {
/// "tenantId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
/// "loginAccount": "admin",
/// "password": "Base64CipherText",
/// "passwordSalt": "Base64Iv"
/// }
/// ```
///
/// 参数说明:
/// - tenantId: 租户 Id(必填)
/// - loginAccount: 新登录账号(可选)
/// - password: AES 加密新密码(可选)
/// - passwordSalt: AES IV(改密时必填)
/// </remarks>
/// <param name="input">租户 Id 与待修改凭据</param>
/// <returns>无内容</returns>
/// <response code="200">修改成功</response>
/// <response code="400">参数错误或账号重复</response>
/// <response code="401">未登录</response>
/// <response code="404">租户或管理员不存在</response>
/// <response code="500">服务器错误</response>
[Authorize]
[HttpPut("th-multi-tenancy/company-admin")]
public virtual async Task UpdateCompanyAdminAsync(ThUpdateCompanyAdminInputVo input)
{
if (input.TenantId == Guid.Empty)
{
throw new UserFriendlyException("租户 Id 不能为空");
}
|
a60a45f4
李曜臣
2026-07-21
|
256
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
257
258
259
260
261
|
var hasPassword = !string.IsNullOrWhiteSpace(input.Password);
if (hasPassword && string.IsNullOrWhiteSpace(input.PasswordSalt))
{
throw new UserFriendlyException("修改密码时必须提供 passwordSalt");
}
|
a60a45f4
李曜臣
2026-07-21
|
262
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
|
TenantAggregateRoot tenant;
ThTenantAdminCredentialEntity? existingCredential;
using (UseHostTenantScope())
{
tenant = await _tenantRepository.FindAsync(input.TenantId)
?? throw new UserFriendlyException("租户不存在");
// 主键列 TenantId 映射到实体 Id,用 Queryable 按 Id 查询
var credentials = await _credentialRepository._DbQueryable
.Where(c => c.Id == input.TenantId)
.Take(1)
.ToListAsync();
existingCredential = credentials.FirstOrDefault();
}
var currentLoginAccount = existingCredential?.LoginAccount?.Trim()
?? ThTenantSelectConsts.DefaultAdminLoginAccount;
var newLoginAccount = !string.IsNullOrWhiteSpace(input.LoginAccount)
? input.LoginAccount.Trim()
: currentLoginAccount;
string? plainPassword = null;
if (hasPassword)
{
plainPassword = _credentialCipher.DecryptPassword(input.Password!, input.PasswordSalt!);
}
|
a60a45f4
李曜臣
2026-07-21
|
288
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
289
290
291
|
var (connectionString, dbType) = await ResolveTenantBusinessConnectionAsync(tenant);
using var tenantDb = TenantBusinessDatabaseAccessor.CreateClient(connectionString, dbType);
TenantBusinessDatabaseAccessor.EnsureDatabaseReachable(tenantDb, input.TenantId);
|
a60a45f4
李曜臣
2026-07-21
|
292
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
293
294
295
296
297
298
|
var adminUsers = await tenantDb.Queryable<UserAggregateRoot>()
.Where(u => u.UserName == currentLoginAccount && !u.IsDeleted)
.Take(1)
.ToListAsync();
var adminUser = adminUsers.FirstOrDefault()
?? throw new UserFriendlyException("未找到租户管理员账号");
|
a60a45f4
李曜臣
2026-07-21
|
299
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
300
301
302
303
304
305
306
|
if (!string.Equals(newLoginAccount, currentLoginAccount, StringComparison.OrdinalIgnoreCase))
{
if (await tenantDb.Queryable<UserAggregateRoot>().AnyAsync(u =>
u.UserName == newLoginAccount && u.Id != adminUser.Id && !u.IsDeleted))
{
throw new UserFriendlyException(UserConst.Exist);
}
|
a60a45f4
李曜臣
2026-07-21
|
307
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
308
309
310
311
312
|
await tenantDb.Updateable<UserAggregateRoot>()
.SetColumns(u => u.UserName == newLoginAccount)
.Where(u => u.Id == adminUser.Id)
.ExecuteCommandAsync();
}
|
a60a45f4
李曜臣
2026-07-21
|
313
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
|
if (plainPassword != null)
{
UserPasswordHelper.ApplyPlainPassword(adminUser, plainPassword);
await tenantDb.Updateable<UserAggregateRoot>()
.SetColumns(u => u.EncryPassword.Password == adminUser.EncryPassword.Password)
.SetColumns(u => u.EncryPassword.Salt == adminUser.EncryPassword.Salt)
.Where(u => u.Id == adminUser.Id)
.ExecuteCommandAsync();
}
await UpsertCredentialAsync(
input.TenantId,
newLoginAccount,
passwordChanged: plainPassword != null,
plainPassword,
existingCredential);
}
|
a60a45f4
李曜臣
2026-07-21
|
331
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
|
/// <summary>
/// 获取 SaaS 菜单权限树
/// </summary>
/// <remarks>
/// 供平台管理员配置租户菜单权限时使用;Key 与前端 saas-menu-tree 一致。
///
/// 示例响应:
/// ```json
/// [
/// {
/// "key": "dashboard",
/// "title": "仪表盘",
/// "children": [
/// { "key": "dashboard:analytics", "title": "数据分析" }
/// ]
|
a60a45f4
李曜臣
2026-07-21
|
347
|
/// }
|
a60a45f4
李曜臣
2026-07-21
|
348
|
/// ]
|
a60a45f4
李曜臣
2026-07-21
|
349
|
/// ```
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
350
351
352
353
354
355
356
357
358
359
360
|
/// </remarks>
/// <returns>SaaS 菜单权限树</returns>
/// <response code="200">成功返回权限树</response>
/// <response code="401">未登录</response>
/// <response code="500">服务器错误</response>
[Authorize]
[HttpGet("th-multi-tenancy/menu-permission-tree")]
public virtual Task<List<ThSaasMenuPermissionTreeNodeDto>> GetMenuPermissionTreeAsync()
{
return Task.FromResult(CloneTree(ThSaasMenuPermissionCatalog.Tree));
}
|
a60a45f4
李曜臣
2026-07-21
|
361
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
362
363
364
365
366
|
/// <summary>
/// 获取公司(租户)已分配的 SaaS 菜单权限
/// </summary>
/// <remarks>
/// 需登录;读取主库 fl_th_tenant_menu_permission。
|
a60a45f4
李曜臣
2026-07-21
|
367
|
///
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
|
/// 示例请求(GET,query/data):
/// ```json
/// { "tenantId": "3fa85f64-5717-4562-b3fc-2c963f66afa6" }
/// ```
///
/// 示例响应:
/// ```json
/// {
/// "tenantId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
/// "menuPermissionKeys": ["dashboard", "labeling:labels"]
/// }
/// ```
///
/// 参数说明:
/// - tenantId: 租户 Id(必填)
/// </remarks>
/// <param name="tenantId">租户 Id</param>
/// <returns>租户菜单权限</returns>
/// <response code="200">成功返回菜单权限</response>
/// <response code="400">租户 Id 无效</response>
/// <response code="401">未登录</response>
/// <response code="404">租户不存在</response>
/// <response code="500">服务器错误</response>
[Authorize]
[HttpGet("th-multi-tenancy/company-menus")]
public virtual async Task<ThCompanyMenusDto> GetCompanyMenusAsync([FromQuery] Guid tenantId)
{
await EnsureTenantExistsAsync(tenantId);
var keys = await LoadMenuPermissionKeysAsync(tenantId);
return new ThCompanyMenusDto
{
TenantId = tenantId,
MenuPermissionKeys = keys
};
}
|
a60a45f4
李曜臣
2026-07-21
|
403
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
|
/// <summary>
/// 覆盖式设置公司(租户)SaaS 菜单权限
/// </summary>
/// <remarks>
/// 需登录;写入主库 fl_th_tenant_menu_permission(先删后插)。非法 permission key 将报错。
///
/// 示例请求:
/// ```json
/// {
/// "tenantId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
/// "menuPermissionKeys": ["dashboard", "labeling:labels"]
/// }
/// ```
///
/// 参数说明:
/// - tenantId: 租户 Id(必填)
/// - menuPermissionKeys: 菜单权限 Key 列表(覆盖式,可为空表示清空)
/// </remarks>
/// <param name="input">租户 Id 与菜单权限 Key 列表</param>
/// <returns>无内容</returns>
/// <response code="200">设置成功</response>
/// <response code="400">参数错误或存在非法 permission key</response>
/// <response code="401">未登录</response>
/// <response code="404">租户不存在</response>
/// <response code="500">服务器错误</response>
[Authorize]
[HttpPut("th-multi-tenancy/company-menus")]
[UnitOfWork]
public virtual async Task UpdateCompanyMenusAsync([FromBody] ThUpdateCompanyMenusInputVo input)
{
if (input.TenantId == Guid.Empty)
{
throw new UserFriendlyException("租户 Id 不能为空");
}
|
a60a45f4
李曜臣
2026-07-21
|
438
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
439
|
await EnsureTenantExistsAsync(input.TenantId);
|
a60a45f4
李曜臣
2026-07-21
|
440
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
441
442
443
444
445
446
|
var normalizedKeys = NormalizePermissionKeys(input.MenuPermissionKeys);
var invalidKeys = ThSaasMenuPermissionCatalog.FindInvalidKeys(normalizedKeys);
if (invalidKeys.Count > 0)
{
throw new UserFriendlyException($"存在非法菜单权限 Key:{string.Join(", ", invalidKeys)}");
}
|
a60a45f4
李曜臣
2026-07-21
|
447
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
448
449
450
|
using (UseHostTenantScope())
{
await _menuPermissionRepository.DeleteAsync(x => x.TenantId == input.TenantId);
|
a60a45f4
李曜臣
2026-07-21
|
451
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
452
453
454
455
|
if (normalizedKeys.Count == 0)
{
return;
}
|
a60a45f4
李曜臣
2026-07-21
|
456
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
457
458
459
460
461
462
463
464
465
466
467
468
|
var now = DateTime.Now;
var entities = normalizedKeys.Select(key => new ThTenantMenuPermissionEntity
{
Id = YitIdHelper.NextId().ToString(),
TenantId = input.TenantId,
PermissionKey = key,
CreationTime = now
}).ToList();
await _menuPermissionRepository.InsertRangeAsync(entities);
}
}
|
a60a45f4
李曜臣
2026-07-21
|
469
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
|
/// <summary>
/// 获取租户内角色及已绑定菜单 Id
/// </summary>
/// <remarks>
/// 需登录;在指定租户业务库查询 Role / RoleMenu。
///
/// 示例请求(GET,query/data):
/// ```json
/// { "tenantId": "3fa85f64-5717-4562-b3fc-2c963f66afa6" }
/// ```
///
/// 示例响应:
/// ```json
/// [
/// {
/// "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
/// "roleName": "管理员",
/// "roleCode": "admin",
/// "state": true,
/// "menuIds": ["11111111-1111-1111-1111-111111111111"]
/// }
/// ]
/// ```
///
/// 参数说明:
/// - tenantId: 租户 Id(必填)
|
a60a45f4
李曜臣
2026-07-21
|
496
|
/// </remarks>
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
|
/// <param name="tenantId">租户 Id</param>
/// <returns>角色及菜单绑定列表</returns>
/// <response code="200">成功返回角色列表</response>
/// <response code="400">租户 Id 无效</response>
/// <response code="401">未登录</response>
/// <response code="404">租户不存在</response>
/// <response code="500">服务器错误</response>
[Authorize]
[HttpGet("th-multi-tenancy/company-roles")]
public virtual async Task<List<ThCompanyRoleItemDto>> GetCompanyRolesAsync([FromQuery] Guid tenantId)
{
var tenant = await EnsureTenantExistsAsync(tenantId);
var (connectionString, dbType) = await ResolveTenantBusinessConnectionAsync(tenant);
using var tenantDb = TenantBusinessDatabaseAccessor.CreateClient(connectionString, dbType);
TenantBusinessDatabaseAccessor.EnsureDatabaseReachable(tenantDb, tenantId);
|
a60a45f4
李曜臣
2026-07-21
|
512
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
513
514
515
516
|
var roles = await tenantDb.Queryable<RoleAggregateRoot>()
.Where(r => !r.IsDeleted)
.OrderBy(r => r.OrderNum)
.ToListAsync();
|
a60a45f4
李曜臣
2026-07-21
|
517
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
518
519
520
521
|
if (roles.Count == 0)
{
return new List<ThCompanyRoleItemDto>();
}
|
a60a45f4
李曜臣
2026-07-21
|
522
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
523
524
525
526
|
var roleIds = roles.Select(r => r.Id).ToList();
var roleMenuLinks = await tenantDb.Queryable<RoleMenuEntity>()
.Where(rm => roleIds.Contains(rm.RoleId))
.ToListAsync();
|
a60a45f4
李曜臣
2026-07-21
|
527
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
528
529
530
531
532
|
var menuIdsByRole = roleMenuLinks
.GroupBy(x => x.RoleId)
.ToDictionary(
g => g.Key,
g => g.Select(x => x.MenuId.ToString()).ToList());
|
a60a45f4
李曜臣
2026-07-21
|
533
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
534
535
536
537
538
539
540
541
542
543
544
|
return roles.Select(role => new ThCompanyRoleItemDto
{
Id = role.Id,
RoleName = role.RoleName,
RoleCode = role.RoleCode,
State = role.State,
MenuIds = menuIdsByRole.TryGetValue(role.Id, out var menuIds)
? menuIds
: new List<string>()
}).ToList();
}
|
a60a45f4
李曜臣
2026-07-21
|
545
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
|
/// <summary>
/// 覆盖式设置租户内角色的菜单绑定
/// </summary>
/// <remarks>
/// 需登录;在指定租户业务库覆盖写入 RoleMenu,逻辑对齐 RbacRoleMenuAppService.Set。
///
/// 示例请求:
/// ```json
/// {
/// "tenantId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
/// "roleId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
/// "menuIds": ["11111111-1111-1111-1111-111111111111"]
/// }
/// ```
///
/// 参数说明:
/// - tenantId: 租户 Id(必填)
/// - roleId: 角色 Id(必填)
/// - menuIds: 菜单 Id 列表(覆盖式,可为空表示清空)
/// </remarks>
/// <param name="input">租户、角色与菜单 Id 列表</param>
/// <returns>无内容</returns>
/// <response code="200">设置成功</response>
/// <response code="400">参数错误或菜单 Id 无效</response>
/// <response code="401">未登录</response>
/// <response code="404">租户或角色不存在</response>
/// <response code="500">服务器错误</response>
[Authorize]
[HttpPut("th-multi-tenancy/company-role-menus")]
[UnitOfWork]
public virtual async Task UpdateCompanyRoleMenusAsync([FromBody] ThUpdateCompanyRoleMenusInputVo input)
|
a60a45f4
李曜臣
2026-07-21
|
577
|
{
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
578
579
580
581
|
if (input.TenantId == Guid.Empty)
{
throw new UserFriendlyException("租户 Id 不能为空");
}
|
a60a45f4
李曜臣
2026-07-21
|
582
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
|
if (input.RoleId == Guid.Empty)
{
throw new UserFriendlyException("角色 Id 不能为空");
}
var tenant = await EnsureTenantExistsAsync(input.TenantId);
var menuIds = ParseMenuIds(input.MenuIds);
var (connectionString, dbType) = await ResolveTenantBusinessConnectionAsync(tenant);
using var tenantDb = TenantBusinessDatabaseAccessor.CreateClient(connectionString, dbType);
TenantBusinessDatabaseAccessor.EnsureDatabaseReachable(tenantDb, input.TenantId);
var roles = await tenantDb.Queryable<RoleAggregateRoot>()
.Where(x => x.Id == input.RoleId && !x.IsDeleted)
.Take(1)
.ToListAsync();
var role = roles.FirstOrDefault();
if (role is null)
|
a60a45f4
李曜臣
2026-07-21
|
600
|
{
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
601
602
|
throw new UserFriendlyException("角色不存在");
}
|
a60a45f4
李曜臣
2026-07-21
|
603
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
|
if (menuIds.Count == 0)
{
await tenantDb.Deleteable<RoleMenuEntity>()
.Where(x => x.RoleId == input.RoleId)
.ExecuteCommandAsync();
return;
}
var existMenuIds = await tenantDb.Queryable<MenuAggregateRoot>()
.Where(x => !x.IsDeleted)
.Where(x => menuIds.Contains(x.Id))
.Select(x => x.Id)
.ToListAsync();
var missingMenuIds = menuIds.Except(existMenuIds).ToList();
if (missingMenuIds.Count > 0)
{
throw new UserFriendlyException(
$"存在无效或未删除的菜单 Id:{string.Join(", ", missingMenuIds)}");
}
|
a60a45f4
李曜臣
2026-07-21
|
624
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
625
626
627
|
await tenantDb.Deleteable<RoleMenuEntity>()
.Where(x => x.RoleId == input.RoleId)
.ExecuteCommandAsync();
|
a60a45f4
李曜臣
2026-07-21
|
628
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
|
var entities = existMenuIds.Select(menuId =>
{
var entity = new RoleMenuEntity
{
RoleId = input.RoleId,
MenuId = menuId
};
EntityHelper.TrySetId(entity, () => GuidGenerator.Create());
return entity;
}).ToList();
if (entities.Count > 0)
{
await tenantDb.Insertable(entities).ExecuteCommandAsync();
}
}
|
a60a45f4
李曜臣
2026-07-21
|
645
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
|
/// <summary>
/// 删除公司(租户),可选 DROP 对应业务库
/// </summary>
/// <remarks>
/// 需登录。在主库 scope 执行:校验非 Default 租户后,按 dropDatabase 决定是否 DROP 业务库;
/// 删除 YiTenant(软删)及 fl_th_tenant_admin_credential、fl_th_tenant_menu_permission 附属记录,并清理租户缓存。
///
/// 受保护规则:禁止删除 Name=Default 或 Id=11111111-1111-1111-1111-111111111111;
/// 禁止 DROP antis-foodlabeling-host、antis-foodlabeling-us;
/// 连接串为空或库名解析/校验失败时仅删主库记录,不 DROP。
///
/// 示例请求(DELETE):
/// ```
/// DELETE /api/app/th-multi-tenancy/company/3a227b24-3d9b-ea2d-81f3-6c4fedccb1d2?dropDatabase=true
/// ```
///
/// 示例响应:
/// ```json
/// {
/// "tenantId": "3a227b24-3d9b-ea2d-81f3-6c4fedccb1d2",
/// "name": "中国麦当劳公司",
/// "databaseName": "antis-foodlabeling-t46d56528",
/// "databaseDropped": true,
/// "tenantDeleted": true,
/// "message": null
/// }
/// ```
///
/// 参数说明:
/// - tenantId: 租户 Id(路径参数,必填)
/// - dropDatabase: 是否 DROP 业务库,默认 true
/// </remarks>
/// <param name="tenantId">租户 Id</param>
/// <param name="dropDatabase">是否 DROP 业务库</param>
/// <returns>删除执行结果</returns>
/// <response code="200">删除成功或部分跳过 DROP 时返回结果</response>
/// <response code="400">租户 Id 无效或受保护租户</response>
/// <response code="401">未登录</response>
/// <response code="404">租户不存在</response>
/// <response code="500">DROP 或删除失败</response>
[Authorize]
[HttpDelete("th-multi-tenancy/company/{tenantId}")]
[UnitOfWork]
public virtual async Task<ThDeleteCompanyResultDto> DeleteCompanyAsync(
[FromRoute] Guid tenantId,
[FromQuery] bool dropDatabase = true)
{
if (tenantId == Guid.Empty)
{
throw new UserFriendlyException("租户 Id 不能为空");
}
|
a60a45f4
李曜臣
2026-07-21
|
697
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
698
|
EnsureTenantDeletable(tenantId, null);
|
a60a45f4
李曜臣
2026-07-21
|
699
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
700
701
702
703
704
705
|
TenantAggregateRoot tenant;
using (UseHostTenantScope())
{
tenant = await _tenantRepository.FindAsync(tenantId)
?? throw new UserFriendlyException("租户不存在");
}
|
a60a45f4
李曜臣
2026-07-21
|
706
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
707
|
EnsureTenantDeletable(tenant.Id, tenant.Name);
|
a60a45f4
李曜臣
2026-07-21
|
708
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
709
710
711
712
713
714
715
|
var databaseName = ExtractConnectionValue(tenant.TenantConnectionString, "database");
var result = new ThDeleteCompanyResultDto
{
TenantId = tenant.Id,
Name = tenant.Name,
DatabaseName = databaseName
};
|
a60a45f4
李曜臣
2026-07-21
|
716
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
717
718
719
720
|
if (dropDatabase)
{
var dropDecision = EvaluateDatabaseDrop(databaseName);
if (dropDecision.CanDrop)
|
a60a45f4
李曜臣
2026-07-21
|
721
|
{
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
722
723
724
725
726
727
728
729
730
731
732
733
|
ExecuteDropDatabase(tenant.DbType, dropDecision.PrivilegedConnectionString!, databaseName!);
result.DatabaseDropped = true;
}
else
{
result.Message = dropDecision.SkipReason;
}
}
else
{
result.Message = "dropDatabase=false,已跳过 DROP DATABASE";
}
|
a60a45f4
李曜臣
2026-07-21
|
734
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
735
736
|
await _tenantService.DeleteAsync(new[] { tenantId });
result.TenantDeleted = true;
|
a60a45f4
李曜臣
2026-07-21
|
737
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
738
739
740
741
742
743
744
745
746
747
748
749
750
|
using (UseHostTenantScope())
{
await _credentialRepository._Db.Ado.ExecuteCommandAsync(
"DELETE FROM `fl_th_tenant_admin_credential` WHERE `TenantId` = @TenantId",
new List<SugarParameter> { new("@TenantId", tenantId.ToString()) });
await _menuPermissionRepository.DeleteAsync(x => x.TenantId == tenantId);
}
await RemoveTenantCacheAsync(tenant.Id, tenant.Name);
return result;
}
|
a60a45f4
李曜臣
2026-07-21
|
751
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
|
/// <inheritdoc />
public virtual Task<ThCurrentTenantDto> GetCurrentTenantAsync()
{
return Task.FromResult(new ThCurrentTenantDto
{
TenantId = CurrentTenant.Id,
TenantName = CurrentTenant.Name
});
}
private async Task<Dictionary<Guid, ThTenantAdminCredentialEntity>> LoadCredentialMapAsync(
IReadOnlyCollection<Guid> tenantIds)
{
if (tenantIds.Count == 0)
{
return new Dictionary<Guid, ThTenantAdminCredentialEntity>();
}
using (UseHostTenantScope())
{
var list = await _credentialRepository._DbQueryable
.Where(c => tenantIds.Contains(c.Id))
.ToListAsync();
return list.ToDictionary(c => c.Id);
}
}
private (string LoginAccount, string Password, string PasswordSalt) ResolveEncryptedCredential(
ThTenantAdminCredentialEntity? credential)
{
if (credential != null
&& !string.IsNullOrEmpty(credential.PasswordCipher)
&& !string.IsNullOrEmpty(credential.PasswordIv))
{
var loginAccount = string.IsNullOrWhiteSpace(credential.LoginAccount)
? ThTenantSelectConsts.DefaultAdminLoginAccount
: credential.LoginAccount;
return (loginAccount, credential.PasswordCipher, credential.PasswordIv);
}
var plainPassword = _rbacOptions.AdminPassword ?? string.Empty;
var encrypted = _credentialCipher.EncryptPassword(plainPassword);
var account = string.IsNullOrWhiteSpace(credential?.LoginAccount)
? ThTenantSelectConsts.DefaultAdminLoginAccount
: credential!.LoginAccount;
return (account, encrypted.Password, encrypted.PasswordSalt);
}
private async Task UpsertCredentialAsync(
Guid tenantId,
string loginAccount,
bool passwordChanged,
string? plainPassword,
ThTenantAdminCredentialEntity? existingCredential)
{
string passwordCipher;
string passwordIv;
if (passwordChanged)
{
var encrypted = _credentialCipher.EncryptPassword(plainPassword!);
passwordCipher = encrypted.Password;
passwordIv = encrypted.PasswordSalt;
}
else if (existingCredential != null
&& !string.IsNullOrEmpty(existingCredential.PasswordCipher)
&& !string.IsNullOrEmpty(existingCredential.PasswordIv))
{
passwordCipher = existingCredential.PasswordCipher;
passwordIv = existingCredential.PasswordIv;
}
else
{
var encrypted = _credentialCipher.EncryptPassword(_rbacOptions.AdminPassword ?? string.Empty);
passwordCipher = encrypted.Password;
passwordIv = encrypted.PasswordSalt;
}
using (UseHostTenantScope())
{
var now = DateTime.Now;
// 使用 Ado 参数化写入,避免实体映射差异导致 Insertable NRE
if (existingCredential == null)
{
await _credentialRepository._Db.Ado.ExecuteCommandAsync(
@"INSERT INTO `fl_th_tenant_admin_credential`
(`TenantId`, `LoginAccount`, `PasswordCipher`, `PasswordIv`, `LastModificationTime`)
VALUES (@TenantId, @LoginAccount, @PasswordCipher, @PasswordIv, @LastModificationTime)",
new List<SugarParameter>
{
new("@TenantId", tenantId.ToString()),
new("@LoginAccount", loginAccount),
new("@PasswordCipher", passwordCipher),
new("@PasswordIv", passwordIv),
new("@LastModificationTime", now)
});
return;
}
await _credentialRepository._Db.Ado.ExecuteCommandAsync(
@"UPDATE `fl_th_tenant_admin_credential`
SET `LoginAccount` = @LoginAccount,
`PasswordCipher` = @PasswordCipher,
`PasswordIv` = @PasswordIv,
`LastModificationTime` = @LastModificationTime
WHERE `TenantId` = @TenantId",
new List<SugarParameter>
|
a60a45f4
李曜臣
2026-07-21
|
859
|
{
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
860
861
862
863
864
865
866
867
|
new("@TenantId", tenantId.ToString()),
new("@LoginAccount", loginAccount),
new("@PasswordCipher", passwordCipher),
new("@PasswordIv", passwordIv),
new("@LastModificationTime", now)
});
}
}
|
a60a45f4
李曜臣
2026-07-21
|
868
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
869
870
871
872
873
874
|
private async Task<TenantAggregateRoot> EnsureTenantExistsAsync(Guid tenantId)
{
if (tenantId == Guid.Empty)
{
throw new UserFriendlyException("租户 Id 不能为空");
}
|
a60a45f4
李曜臣
2026-07-21
|
875
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
876
877
878
879
880
881
|
using (UseHostTenantScope())
{
return await _tenantRepository.FindAsync(tenantId)
?? throw new UserFriendlyException("租户不存在");
}
}
|
a60a45f4
李曜臣
2026-07-21
|
882
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
883
884
885
886
887
888
889
890
891
892
893
|
/// <summary>
/// 解析租户业务库连接串(必要时按配置回填主库 YiTenant),供直连 SqlSugar 使用。
/// </summary>
private Task<(string ConnectionString, DbType DbType)> ResolveTenantBusinessConnectionAsync(
TenantAggregateRoot tenant)
{
return TenantBusinessDatabaseAccessor.ResolveConnectionAsync(
tenant,
_tenantDatabaseOptions,
PersistTenantConnectionStringAsync);
}
|
a60a45f4
李曜臣
2026-07-21
|
894
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
895
896
897
898
899
900
901
|
private async Task PersistTenantConnectionStringAsync(TenantAggregateRoot tenant)
{
using (UseHostTenantScope())
{
await _tenantRepository.UpdateAsync(tenant);
}
}
|
a60a45f4
李曜臣
2026-07-21
|
902
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
903
904
905
906
907
908
909
910
911
912
913
|
private async Task<List<string>> LoadMenuPermissionKeysAsync(Guid tenantId)
{
using (UseHostTenantScope())
{
return await _menuPermissionRepository._DbQueryable
.Where(x => x.TenantId == tenantId)
.OrderBy(x => x.CreationTime)
.Select(x => x.PermissionKey)
.ToListAsync();
}
}
|
a60a45f4
李曜臣
2026-07-21
|
914
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
915
916
917
918
919
920
921
|
private async Task<Dictionary<Guid, List<string>>> LoadMenuPermissionMapAsync(
IReadOnlyCollection<Guid> tenantIds)
{
if (tenantIds.Count == 0)
{
return new Dictionary<Guid, List<string>>();
}
|
a60a45f4
李曜臣
2026-07-21
|
922
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
923
924
925
926
927
928
929
930
931
932
933
934
935
|
using (UseHostTenantScope())
{
var list = await _menuPermissionRepository._DbQueryable
.Where(x => tenantIds.Contains(x.TenantId))
.ToListAsync();
return list
.GroupBy(x => x.TenantId)
.ToDictionary(
g => g.Key,
g => g.Select(x => x.PermissionKey).Distinct(StringComparer.OrdinalIgnoreCase).ToList());
}
}
|
a60a45f4
李曜臣
2026-07-21
|
936
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
937
938
939
940
941
942
|
private static List<string> NormalizePermissionKeys(IEnumerable<string>? keys)
{
if (keys == null)
{
return new List<string>();
}
|
a60a45f4
李曜臣
2026-07-21
|
943
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
944
945
946
947
|
return keys
.Where(x => !string.IsNullOrWhiteSpace(x))
.Select(x => x.Trim())
.Distinct(StringComparer.OrdinalIgnoreCase)
|
a60a45f4
李曜臣
2026-07-21
|
948
|
.ToList();
|
a60a45f4
李曜臣
2026-07-21
|
949
950
|
}
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
951
952
953
954
955
956
|
private static List<Guid> ParseMenuIds(IEnumerable<string>? menuIds)
{
if (menuIds == null)
{
return new List<Guid>();
}
|
a60a45f4
李曜臣
2026-07-21
|
957
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
958
959
|
var result = new List<Guid>();
var invalid = new List<string>();
|
a60a45f4
李曜臣
2026-07-21
|
960
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
961
962
963
964
965
966
967
968
969
970
971
|
foreach (var raw in menuIds.Where(x => !string.IsNullOrWhiteSpace(x)).Select(x => x.Trim()).Distinct())
{
if (Guid.TryParse(raw, out var id))
{
result.Add(id);
}
else
{
invalid.Add(raw);
}
}
|
a60a45f4
李曜臣
2026-07-21
|
972
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
973
974
975
976
|
if (invalid.Count > 0)
{
throw new UserFriendlyException($"菜单 Id 格式无效:{string.Join(", ", invalid)}");
}
|
a60a45f4
李曜臣
2026-07-21
|
977
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
978
979
980
981
982
|
return result;
}
private static List<ThSaasMenuPermissionTreeNodeDto> CloneTree(
IEnumerable<ThSaasMenuPermissionTreeNodeDto> nodes)
|
a60a45f4
李曜臣
2026-07-21
|
983
|
{
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
984
985
986
987
988
989
990
|
return nodes.Select(node => new ThSaasMenuPermissionTreeNodeDto
{
Key = node.Key,
Title = node.Title,
Children = node.Children == null ? null : CloneTree(node.Children)
}).ToList();
}
|
a60a45f4
李曜臣
2026-07-21
|
991
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
992
993
994
995
996
997
|
private static void EnsureTenantDeletable(Guid tenantId, string? tenantName)
{
if (tenantId == ProtectedDefaultTenantId)
{
throw new UserFriendlyException("禁止删除 Default 租户");
}
|
a60a45f4
李曜臣
2026-07-21
|
998
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
999
|
if (string.Equals(tenantName, ProtectedDefaultTenantName, StringComparison.Ordinal))
|
a60a45f4
李曜臣
2026-07-21
|
1000
|
{
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
1001
1002
1003
|
throw new UserFriendlyException("禁止删除 Default 租户");
}
}
|
a60a45f4
李曜臣
2026-07-21
|
1004
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
1005
1006
1007
1008
1009
1010
1011
|
private (bool CanDrop, string? PrivilegedConnectionString, string? SkipReason) EvaluateDatabaseDrop(
string? databaseName)
{
if (string.IsNullOrWhiteSpace(databaseName))
{
return (false, null, "连接串为空或库名解析失败,已跳过 DROP DATABASE,仅删除主库记录");
}
|
a60a45f4
李曜臣
2026-07-21
|
1012
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
|
if (!SafeDatabaseNameRegex.IsMatch(databaseName))
{
return (false, null, "库名格式不符合安全规则,已跳过 DROP DATABASE,仅删除主库记录");
}
if (ProtectedDatabaseNames.Contains(databaseName))
{
return (false, null, $"库名 {databaseName} 为受保护库,已跳过 DROP DATABASE,仅删除主库记录");
}
var privilegedConnectionString = ResolvePrivilegedConnectionString();
if (string.IsNullOrWhiteSpace(privilegedConnectionString))
{
return (false, null, "未配置高权限连接串,已跳过 DROP DATABASE,仅删除主库记录");
}
return (true, privilegedConnectionString, null);
}
private string? ResolvePrivilegedConnectionString()
{
if (!string.IsNullOrWhiteSpace(_dbConnOptions.AdminConnectionString))
{
return _dbConnOptions.AdminConnectionString;
}
|
a60a45f4
李曜臣
2026-07-21
|
1038
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
|
return _dbConnOptions.Url;
}
private static void ExecuteDropDatabase(DbType dbType, string connectionString, string databaseName)
{
using var db = new SqlSugarClient(new ConnectionConfig
{
ConfigId = $"tenant-drop-db-{databaseName}-{Guid.NewGuid():N}",
DbType = dbType,
ConnectionString = connectionString,
IsAutoCloseConnection = true
|
a60a45f4
李曜臣
2026-07-21
|
1050
1051
|
});
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
1052
|
db.Ado.ExecuteCommand($"DROP DATABASE IF EXISTS `{databaseName}`");
|
a60a45f4
李曜臣
2026-07-21
|
1053
1054
|
}
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
|
private async Task RemoveTenantCacheAsync(Guid tenantId, string tenantName)
{
await _tenantCache.RemoveAsync(TenantCacheItem.CalculateCacheKey(tenantId, null!));
if (!string.IsNullOrWhiteSpace(tenantName))
{
await _tenantCache.RemoveAsync(TenantCacheItem.CalculateCacheKey(null, tenantName));
}
}
private static string? ExtractConnectionValue(string connectionString, string key)
{
if (string.IsNullOrWhiteSpace(connectionString))
{
return null;
}
|
a60a45f4
李曜臣
2026-07-21
|
1070
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
1071
1072
1073
1074
1075
1076
1077
1078
1079
|
var prefix = key + "=";
foreach (var segment in connectionString.Split(';', StringSplitOptions.RemoveEmptyEntries))
{
var part = segment.Trim();
if (part.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
{
return part[prefix.Length..].Trim();
}
}
|
a60a45f4
李曜臣
2026-07-21
|
1080
|
|
e41dfa09
李曜臣
泰鄂版菜单;租户列表
|
1081
1082
1083
|
return null;
}
}
|