Commit 1e73afce94042720e82913946fe0e6b555434244
1 parent
04a4c455
代码优化
Showing
42 changed files
with
1430 additions
and
232 deletions
泰额版/Food Labeling Management Code/Yi.Abp.Net8/framework/Yi.Framework.SqlSugarCore.Abstractions/DbConnOptions.cs
| ... | ... | @@ -60,6 +60,12 @@ namespace Yi.Framework.SqlSugarCore.Abstractions |
| 60 | 60 | public bool EnabledSaasMultiTenancy { get; set; } = false; |
| 61 | 61 | |
| 62 | 62 | /// <summary> |
| 63 | + /// 高权限账号连接串(可选)。用于 CREATE DATABASE;为空则使用 <see cref="Url"/>。 | |
| 64 | + /// 阿里云 RDS 业务账号常无 CREATE 权限,可填高权限账号连接串仅用于建库。 | |
| 65 | + /// </summary> | |
| 66 | + public string? AdminConnectionString { get; set; } | |
| 67 | + | |
| 68 | + /// <summary> | |
| 63 | 69 | /// 是否开启更新并发乐观锁 |
| 64 | 70 | /// </summary> |
| 65 | 71 | public bool EnabledConcurrencyException { get;set; } = false; | ... | ... |
泰额版/Food Labeling Management Code/Yi.Abp.Net8/framework/Yi.Framework.SqlSugarCore/SqlSugarDbContextFactory.cs
| ... | ... | @@ -223,10 +223,13 @@ namespace Yi.Framework.SqlSugarCore |
| 223 | 223 | /// <returns>数据库类型</returns> |
| 224 | 224 | protected virtual DbType GetCurrentDbType(string tenantName) |
| 225 | 225 | { |
| 226 | - return tenantName == ConnectionStrings.DefaultConnectionStringName | |
| 227 | - ? DbConnectionOptions.DbType!.Value | |
| 228 | - : GetDbTypeFromTenantName(tenantName) | |
| 229 | - ?? throw new ArgumentException($"无法从租户名称{tenantName}中解析数据库类型"); | |
| 226 | + if (tenantName == ConnectionStrings.DefaultConnectionStringName) | |
| 227 | + { | |
| 228 | + return DbConnectionOptions.DbType!.Value; | |
| 229 | + } | |
| 230 | + | |
| 231 | + // 优先解析 Name@DbType 约定;普通租户名(如中文名)无法解析时回退全局 DbType | |
| 232 | + return GetDbTypeFromTenantName(tenantName) ?? DbConnectionOptions.DbType!.Value; | |
| 230 | 233 | } |
| 231 | 234 | |
| 232 | 235 | /// <summary> |
| ... | ... | @@ -247,9 +250,7 @@ namespace Yi.Framework.SqlSugarCore |
| 247 | 250 | } |
| 248 | 251 | |
| 249 | 252 | var dbTypeString = name[(atIndex + 1)..]; |
| 250 | - return Enum.TryParse<DbType>(dbTypeString, out var dbType) | |
| 251 | - ? dbType | |
| 252 | - : throw new ArgumentException($"不支持的数据库类型: {dbTypeString}"); | |
| 253 | + return Enum.TryParse<DbType>(dbTypeString, out var dbType) ? dbType : null; | |
| 253 | 254 | } |
| 254 | 255 | |
| 255 | 256 | /// <summary> | ... | ... |
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/AllScopeBindingHelper.cs
| ... | ... | @@ -110,6 +110,14 @@ public static class AllScopeBindingHelper |
| 110 | 110 | bool hasArrayInPayload) |
| 111 | 111 | { |
| 112 | 112 | var ids = LabelEntityPartnerScopeHelper.NormalizePartnerIds(partnerIds, companyIds); |
| 113 | + | |
| 114 | + // 显式 SPECIFIED 时保留指定 Company 落库,不因「全选当前全部 Company」而归档为 ALL(与 Location 维度一致)。 | |
| 115 | + if (string.Equals(declaredType?.Trim(), ScopeSpecified, StringComparison.OrdinalIgnoreCase) | |
| 116 | + && ids.Count > 0) | |
| 117 | + { | |
| 118 | + return (ScopeSpecified, ids); | |
| 119 | + } | |
| 120 | + | |
| 113 | 121 | var allPartners = await ResolveAllPartnerIdsAsync(db); |
| 114 | 122 | var isFull = ids.Count > 0 && IsFullIdSelection(ids, allPartners); |
| 115 | 123 | var type = ResolveDimensionType(declaredType, ids, hasArrayInPayload, isFull); |
| ... | ... | @@ -173,6 +181,12 @@ public static class AllScopeBindingHelper |
| 173 | 181 | return true; |
| 174 | 182 | } |
| 175 | 183 | |
| 184 | + // 显式 SPECIFIED 时保留指定范围落库,不因「全选当前 Company 下门店」而归档为 ALL。 | |
| 185 | + if (string.Equals(declaredAvailabilityType?.Trim(), ScopeSpecified, StringComparison.OrdinalIgnoreCase)) | |
| 186 | + { | |
| 187 | + return false; | |
| 188 | + } | |
| 189 | + | |
| 176 | 190 | var merged = await LocationScopeBindingHelper.MergeToLocationIdsAsync( |
| 177 | 191 | db, |
| 178 | 192 | (IReadOnlyList<string>?)null, | ... | ... |
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/LabelEntityPartnerScopeHelper.cs
| ... | ... | @@ -259,10 +259,42 @@ public static class LabelEntityPartnerScopeHelper |
| 259 | 259 | var hasTable = HasPartnerTableForKind(schema, kind); |
| 260 | 260 | var hasColumn = HasPartnerColumnForKind(schema, kind); |
| 261 | 261 | |
| 262 | + // 主表 AppliedPartnerType 列已迁移但静态缓存未感知关联表时(常见于迁移后首访 GET),刷新后再读。 | |
| 263 | + if (!hasTable && hasColumn) | |
| 264 | + { | |
| 265 | + schema = await RefreshSchemaCacheAsync(db); | |
| 266 | + hasTable = HasPartnerTableForKind(schema, kind); | |
| 267 | + hasColumn = HasPartnerColumnForKind(schema, kind); | |
| 268 | + } | |
| 269 | + | |
| 262 | 270 | var partnerLinks = hasTable |
| 263 | 271 | ? await LoadPartnerLinksAsync(db, kind, ids) |
| 264 | 272 | : new List<(string EntityId, string PartnerId)>(); |
| 265 | 273 | |
| 274 | + if (partnerLinks.Count == 0 && hasColumn) | |
| 275 | + { | |
| 276 | + var hasSpecifiedWithoutLinks = false; | |
| 277 | + foreach (var entityId in ids) | |
| 278 | + { | |
| 279 | + var storedType = await GetAppliedPartnerTypeAsync(db, kind, entityId); | |
| 280 | + if (string.Equals(storedType, ScopeSpecified, StringComparison.OrdinalIgnoreCase)) | |
| 281 | + { | |
| 282 | + hasSpecifiedWithoutLinks = true; | |
| 283 | + break; | |
| 284 | + } | |
| 285 | + } | |
| 286 | + | |
| 287 | + if (hasSpecifiedWithoutLinks && !hasTable) | |
| 288 | + { | |
| 289 | + schema = await RefreshSchemaCacheAsync(db); | |
| 290 | + hasTable = HasPartnerTableForKind(schema, kind); | |
| 291 | + if (hasTable) | |
| 292 | + { | |
| 293 | + partnerLinks = await LoadPartnerLinksAsync(db, kind, ids); | |
| 294 | + } | |
| 295 | + } | |
| 296 | + } | |
| 297 | + | |
| 266 | 298 | var partnerIdSet = partnerLinks.Select(x => x.PartnerId).Distinct(StringComparer.Ordinal).ToList(); |
| 267 | 299 | var partnerNameById = await LoadPartnerNameMapAsync(db, partnerIdSet); |
| 268 | 300 | |
| ... | ... | @@ -439,31 +471,13 @@ public static class LabelEntityPartnerScopeHelper |
| 439 | 471 | } |
| 440 | 472 | |
| 441 | 473 | /// <summary> |
| 442 | - /// 由 Query partnerId 或可见门店范围解析列表 Company 筛选 Id;均未限时返回 <c>null</c>。 | |
| 474 | + /// 由 Query <c>partnerId</c> 解析列表 Company 筛选 Id;未传则返回 <c>null</c>(Region/Location 筛选由门店范围单独处理)。 | |
| 443 | 475 | /// </summary> |
| 444 | - public static async Task<List<string>?> ResolveListPartnerIdsAsync( | |
| 476 | + public static Task<List<string>?> ResolveListPartnerIdsAsync( | |
| 445 | 477 | ISqlSugarClient db, |
| 446 | 478 | string? partnerId, |
| 447 | - List<string>? scopedLocationIds) | |
| 448 | - { | |
| 449 | - var fromQuery = await ResolveScopedPartnerIdsForListAsync(db, partnerId); | |
| 450 | - if (fromQuery is not null) | |
| 451 | - { | |
| 452 | - return fromQuery; | |
| 453 | - } | |
| 454 | - | |
| 455 | - if (scopedLocationIds is null) | |
| 456 | - { | |
| 457 | - return null; | |
| 458 | - } | |
| 459 | - | |
| 460 | - if (scopedLocationIds.Count == 0) | |
| 461 | - { | |
| 462 | - return new List<string>(); | |
| 463 | - } | |
| 464 | - | |
| 465 | - return await LocationScopeBindingHelper.ResolvePartnerIdsFromLocationIdsAsync(db, scopedLocationIds); | |
| 466 | - } | |
| 479 | + List<string>? scopedLocationIds) => | |
| 480 | + ResolveScopedPartnerIdsForListAsync(db, partnerId); | |
| 467 | 481 | |
| 468 | 482 | /// <summary>单元测试或切换库后调用。</summary> |
| 469 | 483 | public static void ResetSchemaCacheForTests() => _cachedSchema = null; | ... | ... |
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/LocationScopeBindingHelper.cs
| ... | ... | @@ -215,37 +215,22 @@ public static class LocationScopeBindingHelper |
| 215 | 215 | return exists ? new List<string> { locId } : new List<string>(); |
| 216 | 216 | } |
| 217 | 217 | |
| 218 | - var gid = groupId?.Trim(); | |
| 218 | + var groupIds = ParseScopeIdsFromQuery(groupId); | |
| 219 | 219 | var pid = partnerId?.Trim(); |
| 220 | 220 | |
| 221 | - if (string.IsNullOrWhiteSpace(pid) && string.IsNullOrWhiteSpace(gid)) | |
| 221 | + if (string.IsNullOrWhiteSpace(pid) && groupIds.Count == 0) | |
| 222 | 222 | { |
| 223 | 223 | return null; |
| 224 | 224 | } |
| 225 | 225 | |
| 226 | - var q = db.Queryable<LocationAggregateRoot>().Where(x => !x.IsDeleted); | |
| 227 | - | |
| 228 | - if (!string.IsNullOrWhiteSpace(gid)) | |
| 226 | + if (groupIds.Count > 0) | |
| 229 | 227 | { |
| 230 | - var g = await db.Queryable<FlGroupDbEntity>() | |
| 231 | - .FirstAsync(x => !x.IsDeleted && x.Id == gid); | |
| 232 | - if (g is null) | |
| 233 | - { | |
| 234 | - return new List<string>(); | |
| 235 | - } | |
| 228 | + return await ResolveLocationIdsFromGroupIdsAsync(db, groupIds); | |
| 229 | + } | |
| 236 | 230 | |
| 237 | - var gName = g.GroupName?.Trim() ?? string.Empty; | |
| 238 | - var partner = await db.Queryable<FlPartnerDbEntity>() | |
| 239 | - .FirstAsync(x => !x.IsDeleted && x.Id == g.PartnerId); | |
| 240 | - if (partner is null) | |
| 241 | - { | |
| 242 | - return new List<string>(); | |
| 243 | - } | |
| 231 | + var q = db.Queryable<LocationAggregateRoot>().Where(x => !x.IsDeleted); | |
| 244 | 232 | |
| 245 | - var pName = partner.PartnerName?.Trim() ?? string.Empty; | |
| 246 | - q = q.Where(x => x.GroupName == gName && x.Partner == pName); | |
| 247 | - } | |
| 248 | - else if (!string.IsNullOrWhiteSpace(pid)) | |
| 233 | + if (!string.IsNullOrWhiteSpace(pid)) | |
| 249 | 234 | { |
| 250 | 235 | var partner = await db.Queryable<FlPartnerDbEntity>() |
| 251 | 236 | .FirstAsync(x => !x.IsDeleted && x.Id == pid); |
| ... | ... | @@ -282,13 +267,13 @@ public static class LocationScopeBindingHelper |
| 282 | 267 | return exists ? new List<string> { locId } : new List<string>(); |
| 283 | 268 | } |
| 284 | 269 | |
| 285 | - var gid = groupId?.Trim(); | |
| 286 | - if (string.IsNullOrWhiteSpace(gid)) | |
| 270 | + var groupIds = ParseScopeIdsFromQuery(groupId); | |
| 271 | + if (groupIds.Count == 0) | |
| 287 | 272 | { |
| 288 | 273 | return null; |
| 289 | 274 | } |
| 290 | 275 | |
| 291 | - return await ResolveLocationIdsFromGroupIdsAsync(db, new List<string> { gid }); | |
| 276 | + return await ResolveLocationIdsFromGroupIdsAsync(db, groupIds); | |
| 292 | 277 | } |
| 293 | 278 | |
| 294 | 279 | /// <summary> |
| ... | ... | @@ -640,6 +625,20 @@ public static class LocationScopeBindingHelper |
| 640 | 625 | } |
| 641 | 626 | |
| 642 | 627 | /// <summary> |
| 628 | + /// 解析 Query 中的 Id 参数(支持逗号分隔多值,如多个 Region GroupId)。 | |
| 629 | + /// </summary> | |
| 630 | + public static List<string> ParseScopeIdsFromQuery(string? raw) | |
| 631 | + { | |
| 632 | + if (string.IsNullOrWhiteSpace(raw)) | |
| 633 | + { | |
| 634 | + return new List<string>(); | |
| 635 | + } | |
| 636 | + | |
| 637 | + var parts = raw.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); | |
| 638 | + return NormalizeIds(parts); | |
| 639 | + } | |
| 640 | + | |
| 641 | + /// <summary> | |
| 643 | 642 | /// Company Admin 在其绑定 Company 下新建 Region 后,将该 Region 下已有门店追加写入 <c>userlocation</c>(不删除已有绑定)。 |
| 644 | 643 | /// </summary> |
| 645 | 644 | public static async Task TryAutoBindCompanyAdminToNewRegionAsync( | ... | ... |
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/DbModels/MenuDbEntity.cs
| 1 | 1 | using SqlSugar; |
| 2 | +using Yi.Framework.SqlSugarCore.Abstractions; | |
| 2 | 3 | |
| 3 | 4 | namespace FoodLabeling.Application.Services.DbModels; |
| 4 | 5 | |
| 5 | 6 | /// <summary> |
| 6 | 7 | /// menu 表映射(兼容数字/字符串类型的 Id、ParentId) |
| 8 | +/// 禁止参与 CodeFirst,完整表结构由 RBAC MenuAggregateRoot 创建 | |
| 7 | 9 | /// </summary> |
| 10 | +[IgnoreCodeFirst] | |
| 8 | 11 | [SugarTable("menu")] |
| 9 | 12 | public class MenuDbEntity |
| 10 | 13 | { | ... | ... |
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/DbModels/RoleDbEntity.cs
| 1 | 1 | using SqlSugar; |
| 2 | +using Yi.Framework.SqlSugarCore.Abstractions; | |
| 2 | 3 | |
| 3 | 4 | namespace FoodLabeling.Application.Services.DbModels; |
| 4 | 5 | |
| 5 | 6 | /// <summary> |
| 6 | 7 | /// Role 表映射(用于 SqlSugar 直查,避免走仓储 IDataPermission) |
| 8 | +/// 字段不全,禁止参与 CodeFirst,否则会建成缺列的 Role 表导致 Seed 失败 | |
| 7 | 9 | /// </summary> |
| 10 | +[IgnoreCodeFirst] | |
| 8 | 11 | [SugarTable("Role")] |
| 9 | 12 | public class RoleDbEntity |
| 10 | 13 | { | ... | ... |
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/DbModels/RoleMenuDbEntity.cs
| 1 | 1 | using SqlSugar; |
| 2 | +using Yi.Framework.SqlSugarCore.Abstractions; | |
| 2 | 3 | |
| 3 | 4 | namespace FoodLabeling.Application.Services.DbModels; |
| 4 | 5 | |
| 5 | 6 | /// <summary> |
| 6 | 7 | /// rolemenu 表映射(兼容字符串类型 RoleId/MenuId) |
| 8 | +/// 禁止参与 CodeFirst,完整表结构由 RBAC RoleMenuEntity 创建 | |
| 7 | 9 | /// </summary> |
| 10 | +[IgnoreCodeFirst] | |
| 8 | 11 | [SugarTable("rolemenu")] |
| 9 | 12 | public class RoleMenuDbEntity |
| 10 | 13 | { | ... | ... |
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/DbModels/UserLocationDbEntity.cs
| 1 | 1 | using SqlSugar; |
| 2 | +using Yi.Framework.SqlSugarCore.Abstractions; | |
| 2 | 3 | |
| 3 | 4 | namespace FoodLabeling.Application.Services.DbModels; |
| 4 | 5 | |
| 5 | 6 | /// <summary> |
| 6 | 7 | /// userlocation 表映射(成员-门店关联) |
| 8 | +/// 禁止参与 CodeFirst,避免与领域实体建表冲突 | |
| 7 | 9 | /// </summary> |
| 10 | +[IgnoreCodeFirst] | |
| 8 | 11 | [SugarTable("userlocation")] |
| 9 | 12 | public class UserLocationDbEntity |
| 10 | 13 | { | ... | ... |
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelCategoryAppService.cs
| ... | ... | @@ -275,6 +275,7 @@ public class LabelCategoryAppService : ApplicationService, ILabelCategoryAppServ |
| 275 | 275 | State = x.State, |
| 276 | 276 | ButtonAppearance = x.ButtonAppearance, |
| 277 | 277 | AvailabilityType = x.AvailabilityType, |
| 278 | + AppliedPartnerType = x.AppliedPartnerType, | |
| 278 | 279 | OrderNum = x.OrderNum |
| 279 | 280 | }; |
| 280 | 281 | } | ... | ... |
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application.Contracts/Dtos/Auth/ThWebLoginInputVo.cs
| ... | ... | @@ -7,8 +7,11 @@ namespace FoodLabeling.Th.Application.Contracts.Dtos.Auth; |
| 7 | 7 | /// </summary> |
| 8 | 8 | public class ThWebLoginInputVo |
| 9 | 9 | { |
| 10 | - [Required] | |
| 11 | - public Guid TenantId { get; set; } | |
| 10 | + /// <summary>租户 Id(与 TenantName 二选一;tenant-select 不再返回 Id 时传 TenantName)</summary> | |
| 11 | + public Guid? TenantId { get; set; } | |
| 12 | + | |
| 13 | + /// <summary>租户名称(与 TenantId 二选一)</summary> | |
| 14 | + public string? TenantName { get; set; } | |
| 12 | 15 | |
| 13 | 16 | [Required] |
| 14 | 17 | public string UserName { get; set; } = string.Empty; | ... | ... |
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application.Contracts/Dtos/MultiTenancy/ThProvisionTenantInputVo.cs
| ... | ... | @@ -15,11 +15,18 @@ public class ThProvisionTenantInputVo |
| 15 | 15 | /// </summary> |
| 16 | 16 | public string? TenantConnectionString { get; set; } |
| 17 | 17 | |
| 18 | + /// <summary> | |
| 19 | + /// 可选:租户库名片段(替换 DatabaseNameTemplate 中的 {tenant});为空则从 Name 清洗,纯中文等则 hash 兜底 | |
| 20 | + /// </summary> | |
| 21 | + public string? DatabaseKey { get; set; } | |
| 22 | + | |
| 18 | 23 | /// <summary>数据库类型,与 SqlSugar.DbType 枚举值一致,默认 0=MySql</summary> |
| 19 | 24 | public int DbType { get; set; } |
| 20 | 25 | |
| 21 | 26 | /// <summary> |
| 22 | - /// 创建后是否立即执行 CodeFirst 建库建表(等同 PUT tenant/init/{id}) | |
| 27 | + /// 创建后是否触发业务库 CodeFirst 初始化(建库 + 建表 + Seed)。 | |
| 28 | + /// 为 true 时在后台异步执行,HTTP 立即返回;未完成前出参 DatabaseInitializing=true、DatabaseInitialized=false。 | |
| 29 | + /// 同步补跑请调用 initialize-tenant-database 或 PUT tenant/init/{id}。 | |
| 23 | 30 | /// </summary> |
| 24 | 31 | public bool InitializeDatabase { get; set; } = true; |
| 25 | 32 | } | ... | ... |
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application.Contracts/Dtos/MultiTenancy/ThProvisionTenantOutputDto.cs
| ... | ... | @@ -10,5 +10,9 @@ public class ThProvisionTenantOutputDto |
| 10 | 10 | |
| 11 | 11 | public string TenantConnectionString { get; set; } = string.Empty; |
| 12 | 12 | |
| 13 | + /// <summary>业务库建库/建表/Seed 是否已完成</summary> | |
| 13 | 14 | public bool DatabaseInitialized { get; set; } |
| 15 | + | |
| 16 | + /// <summary>业务库初始化是否已在后台进行中(与 DatabaseInitialized 互斥:进行中时为 true)</summary> | |
| 17 | + public bool DatabaseInitializing { get; set; } | |
| 14 | 18 | } | ... | ... |
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application.Contracts/Dtos/MultiTenancy/ThTenantSelectDto.cs
| 1 | 1 | namespace FoodLabeling.Th.Application.Contracts.Dtos.MultiTenancy; |
| 2 | 2 | |
| 3 | +/// <summary> | |
| 4 | +/// 登录页租户下拉项(不含租户 Id 与连接串) | |
| 5 | +/// </summary> | |
| 3 | 6 | public class ThTenantSelectDto |
| 4 | 7 | { |
| 5 | - public Guid Id { get; set; } | |
| 6 | - | |
| 8 | + /// <summary>租户名称</summary> | |
| 7 | 9 | public string Name { get; set; } = string.Empty; |
| 10 | + | |
| 11 | + /// <summary>租户创建时间(平台主库 yitenant)</summary> | |
| 12 | + public DateTime CreationTime { get; set; } | |
| 13 | + | |
| 14 | + /// <summary>默认管理员登录账号(种子 UserName=admin)</summary> | |
| 15 | + public string LoginAccount { get; set; } = string.Empty; | |
| 16 | + | |
| 17 | + /// <summary>AES-CBC 加密后的默认管理员密码(Base64 密文)</summary> | |
| 18 | + public string Password { get; set; } = string.Empty; | |
| 19 | + | |
| 20 | + /// <summary>AES IV(Base64),前端解密 password 时使用</summary> | |
| 21 | + public string PasswordSalt { get; set; } = string.Empty; | |
| 8 | 22 | } | ... | ... |
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application.Contracts/IServices/IThTenantProvisioningAppService.cs
| ... | ... | @@ -9,12 +9,12 @@ namespace FoodLabeling.Th.Application.Contracts.IServices; |
| 9 | 9 | public interface IThTenantProvisioningAppService : IApplicationService |
| 10 | 10 | { |
| 11 | 11 | /// <summary> |
| 12 | - /// 在平台主库登记租户,并按配置生成/使用独立库连接串;可选自动建库建表 | |
| 12 | + /// 在平台主库登记租户,并按配置生成/使用独立库连接串;可选触发后台建库建表 | |
| 13 | 13 | /// </summary> |
| 14 | 14 | Task<ThProvisionTenantOutputDto> ProvisionAsync(ThProvisionTenantInputVo input); |
| 15 | 15 | |
| 16 | 16 | /// <summary> |
| 17 | - /// 对已有租户执行业务库 CodeFirst(建库 + 业务表,不含 yitenant) | |
| 17 | + /// 对已有租户同步执行业务库 CodeFirst(建库 + 业务表 + Seed);耗时较长,已配置 10 分钟请求超时 | |
| 18 | 18 | /// </summary> |
| 19 | 19 | Task InitializeTenantDatabaseAsync(Guid tenantId); |
| 20 | 20 | } | ... | ... |
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application.Contracts/Options/FoodLabelingThTenantSelectCryptoOptions.cs
0 → 100644
| 1 | +namespace FoodLabeling.Th.Application.Contracts.Options; | |
| 2 | + | |
| 3 | +/// <summary> | |
| 4 | +/// 租户下拉接口密码加密配置(appsettings FoodLabeling:TenantSelectCrypto) | |
| 5 | +/// </summary> | |
| 6 | +public class FoodLabelingThTenantSelectCryptoOptions | |
| 7 | +{ | |
| 8 | + public const string SectionName = "FoodLabeling:TenantSelectCrypto"; | |
| 9 | + | |
| 10 | + /// <summary> | |
| 11 | + /// 前后端约定的 AES 密钥原文;后端使用 SHA256 派生 32 字节 AES-256 Key | |
| 12 | + /// </summary> | |
| 13 | + public string SecretKey { get; set; } = string.Empty; | |
| 14 | +} | ... | ... |
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application/FoodLabelingThApplicationModule.cs
| ... | ... | @@ -28,5 +28,8 @@ public class FoodLabelingThApplicationModule : AbpModule |
| 28 | 28 | |
| 29 | 29 | Configure<FoodLabelingThMultiTenancyOptions>( |
| 30 | 30 | configuration.GetSection(FoodLabelingThMultiTenancyOptions.SectionName)); |
| 31 | + | |
| 32 | + Configure<FoodLabelingThTenantSelectCryptoOptions>( | |
| 33 | + configuration.GetSection(FoodLabelingThTenantSelectCryptoOptions.SectionName)); | |
| 31 | 34 | } |
| 32 | 35 | } | ... | ... |
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application/MultiTenancy/IThTenantDatabaseBackgroundInitializer.cs
0 → 100644
| 1 | +namespace FoodLabeling.Th.Application.MultiTenancy; | |
| 2 | + | |
| 3 | +/// <summary> | |
| 4 | +/// 租户业务库后台初始化(建库 + CodeFirst + Seed) | |
| 5 | +/// </summary> | |
| 6 | +public interface IThTenantDatabaseBackgroundInitializer | |
| 7 | +{ | |
| 8 | + /// <summary> | |
| 9 | + /// 将初始化任务入队;同一租户并发仅执行一次。 | |
| 10 | + /// </summary> | |
| 11 | + void Enqueue(Guid tenantId); | |
| 12 | +} | ... | ... |
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application/MultiTenancy/TenantDatabaseConnectionStringBuilder.cs
| 1 | +using System.Security.Cryptography; | |
| 2 | +using System.Text; | |
| 1 | 3 | using System.Text.RegularExpressions; |
| 2 | 4 | using FoodLabeling.Th.Application.Contracts.Options; |
| 3 | 5 | using SqlSugar; |
| ... | ... | @@ -9,30 +11,44 @@ namespace FoodLabeling.Th.Application.MultiTenancy; |
| 9 | 11 | /// </summary> |
| 10 | 12 | public static class TenantDatabaseConnectionStringBuilder |
| 11 | 13 | { |
| 14 | + private const int FallbackHashLength = 8; | |
| 12 | 15 | private static readonly Regex SafeNameRegex = new(@"[^a-z0-9_]", RegexOptions.Compiled); |
| 13 | 16 | |
| 14 | - public static string NormalizeTenantDatabaseKey(string tenantName) | |
| 17 | + /// <summary> | |
| 18 | + /// 将租户名或显式 DatabaseKey 规范化为 MySQL 库名片段(小写字母、数字、下划线)。 | |
| 19 | + /// 纯中文等非 ASCII 名称在清洗为空时,使用基于名称的稳定 hash 兜底(t + 8 位十六进制)。 | |
| 20 | + /// </summary> | |
| 21 | + public static string NormalizeTenantDatabaseKey(string tenantName, string? explicitDatabaseKey = null) | |
| 15 | 22 | { |
| 16 | - var key = tenantName.Trim().ToLowerInvariant(); | |
| 17 | - key = SafeNameRegex.Replace(key, "_"); | |
| 18 | - key = Regex.Replace(key, "_+", "_").Trim('_'); | |
| 23 | + if (!string.IsNullOrWhiteSpace(explicitDatabaseKey)) | |
| 24 | + { | |
| 25 | + return NormalizeSanitizedKey(explicitDatabaseKey.Trim(), "DatabaseKey 无效,无法生成数据库名"); | |
| 26 | + } | |
| 27 | + | |
| 28 | + var key = SanitizeToDatabaseKey(tenantName); | |
| 19 | 29 | if (string.IsNullOrEmpty(key)) |
| 20 | 30 | { |
| 21 | - throw new ArgumentException("租户名称无效,无法生成数据库名"); | |
| 31 | + key = BuildStableFallbackKey(tenantName); | |
| 22 | 32 | } |
| 23 | 33 | |
| 24 | 34 | return key; |
| 25 | 35 | } |
| 26 | 36 | |
| 27 | - public static string BuildDatabaseName(FoodLabelingThTenantDatabaseOptions options, string tenantName) | |
| 37 | + public static string BuildDatabaseName( | |
| 38 | + FoodLabelingThTenantDatabaseOptions options, | |
| 39 | + string tenantName, | |
| 40 | + string? databaseKey = null) | |
| 28 | 41 | { |
| 29 | - var key = NormalizeTenantDatabaseKey(tenantName); | |
| 42 | + var key = NormalizeTenantDatabaseKey(tenantName, databaseKey); | |
| 30 | 43 | return options.DatabaseNameTemplate.Replace("{tenant}", key, StringComparison.OrdinalIgnoreCase); |
| 31 | 44 | } |
| 32 | 45 | |
| 33 | - public static string BuildMySqlConnectionString(FoodLabelingThTenantDatabaseOptions options, string tenantName) | |
| 46 | + public static string BuildMySqlConnectionString( | |
| 47 | + FoodLabelingThTenantDatabaseOptions options, | |
| 48 | + string tenantName, | |
| 49 | + string? databaseKey = null) | |
| 34 | 50 | { |
| 35 | - var database = BuildDatabaseName(options, tenantName); | |
| 51 | + var database = BuildDatabaseName(options, tenantName, databaseKey); | |
| 36 | 52 | return |
| 37 | 53 | $"server={options.Server};port={options.Port};database={database};uid={options.UserId};pwd={options.Password};CharSet={options.CharSet};"; |
| 38 | 54 | } |
| ... | ... | @@ -41,4 +57,32 @@ public static class TenantDatabaseConnectionStringBuilder |
| 41 | 57 | { |
| 42 | 58 | return Enum.TryParse<DbType>(configuredDbType, true, out var dbType) ? dbType : DbType.MySql; |
| 43 | 59 | } |
| 60 | + | |
| 61 | + private static string SanitizeToDatabaseKey(string value) | |
| 62 | + { | |
| 63 | + var key = value.Trim().ToLowerInvariant(); | |
| 64 | + key = SafeNameRegex.Replace(key, "_"); | |
| 65 | + return Regex.Replace(key, "_+", "_").Trim('_'); | |
| 66 | + } | |
| 67 | + | |
| 68 | + private static string NormalizeSanitizedKey(string value, string invalidMessage) | |
| 69 | + { | |
| 70 | + var key = SanitizeToDatabaseKey(value); | |
| 71 | + if (string.IsNullOrEmpty(key)) | |
| 72 | + { | |
| 73 | + throw new ArgumentException(invalidMessage); | |
| 74 | + } | |
| 75 | + | |
| 76 | + return key; | |
| 77 | + } | |
| 78 | + | |
| 79 | + /// <summary> | |
| 80 | + /// 基于租户名称生成稳定、可重复的短 key,避免纯非 ASCII 名称清洗后为空。 | |
| 81 | + /// </summary> | |
| 82 | + private static string BuildStableFallbackKey(string tenantName) | |
| 83 | + { | |
| 84 | + var hashBytes = SHA256.HashData(Encoding.UTF8.GetBytes(tenantName.Trim())); | |
| 85 | + var hex = Convert.ToHexString(hashBytes).ToLowerInvariant(); | |
| 86 | + return "t" + hex[..FallbackHashLength]; | |
| 87 | + } | |
| 44 | 88 | } | ... | ... |
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application/MultiTenancy/TenantResolveHelper.cs
| ... | ... | @@ -9,6 +9,44 @@ namespace FoodLabeling.Th.Application.MultiTenancy; |
| 9 | 9 | /// </summary> |
| 10 | 10 | public static class TenantResolveHelper |
| 11 | 11 | { |
| 12 | + /// <summary> | |
| 13 | + /// 按租户 Id 或租户名称解析配置;二者至少提供一个 | |
| 14 | + /// </summary> | |
| 15 | + public static async Task<TenantConfiguration> ResolveTenantAsync( | |
| 16 | + ITenantStore tenantStore, | |
| 17 | + ICurrentTenant currentTenant, | |
| 18 | + Guid? tenantId, | |
| 19 | + string? tenantName) | |
| 20 | + { | |
| 21 | + if (tenantId.HasValue && tenantId.Value != Guid.Empty) | |
| 22 | + { | |
| 23 | + return await ResolveTenantAsync(tenantStore, currentTenant, tenantId.Value); | |
| 24 | + } | |
| 25 | + | |
| 26 | + if (!string.IsNullOrWhiteSpace(tenantName)) | |
| 27 | + { | |
| 28 | + TenantConfiguration? config; | |
| 29 | + using (currentTenant.Change(null)) | |
| 30 | + { | |
| 31 | + config = await tenantStore.FindAsync(tenantName.Trim()); | |
| 32 | + } | |
| 33 | + | |
| 34 | + if (config is null) | |
| 35 | + { | |
| 36 | + throw new UserFriendlyException("租户不存在或已停用"); | |
| 37 | + } | |
| 38 | + | |
| 39 | + if (string.IsNullOrWhiteSpace(config.ConnectionStrings?.Default)) | |
| 40 | + { | |
| 41 | + throw new UserFriendlyException("租户未配置业务库连接串"); | |
| 42 | + } | |
| 43 | + | |
| 44 | + return config; | |
| 45 | + } | |
| 46 | + | |
| 47 | + throw new UserFriendlyException("请指定租户 Id 或租户名称"); | |
| 48 | + } | |
| 49 | + | |
| 12 | 50 | public static async Task<TenantConfiguration> ResolveTenantAsync( |
| 13 | 51 | ITenantStore tenantStore, |
| 14 | 52 | ICurrentTenant currentTenant, | ... | ... |
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application/MultiTenancy/TenantSelectCredentialCipher.cs
0 → 100644
| 1 | +using System.Security.Cryptography; | |
| 2 | +using System.Text; | |
| 3 | +using FoodLabeling.Th.Application.Contracts.Options; | |
| 4 | +using Microsoft.Extensions.Options; | |
| 5 | +using Volo.Abp; | |
| 6 | +using Volo.Abp.DependencyInjection; | |
| 7 | + | |
| 8 | +namespace FoodLabeling.Th.Application.MultiTenancy; | |
| 9 | + | |
| 10 | +/// <summary> | |
| 11 | +/// 租户下拉默认管理员密码 AES-CBC 加密(随机 IV 作为 passwordSalt 返回前端) | |
| 12 | +/// </summary> | |
| 13 | +public class TenantSelectCredentialCipher : ITransientDependency | |
| 14 | +{ | |
| 15 | + private readonly byte[] _key; | |
| 16 | + | |
| 17 | + public TenantSelectCredentialCipher(IOptions<FoodLabelingThTenantSelectCryptoOptions> options) | |
| 18 | + { | |
| 19 | + var secretKey = options.Value.SecretKey?.Trim(); | |
| 20 | + if (string.IsNullOrEmpty(secretKey)) | |
| 21 | + { | |
| 22 | + throw new AbpException("未配置 FoodLabeling:TenantSelectCrypto:SecretKey"); | |
| 23 | + } | |
| 24 | + | |
| 25 | + _key = SHA256.HashData(Encoding.UTF8.GetBytes(secretKey)); | |
| 26 | + } | |
| 27 | + | |
| 28 | + /// <summary> | |
| 29 | + /// 加密明文密码,返回 Base64 密文与 Base64 IV(passwordSalt) | |
| 30 | + /// </summary> | |
| 31 | + public (string Password, string PasswordSalt) EncryptPassword(string plainPassword) | |
| 32 | + { | |
| 33 | + if (plainPassword is null) | |
| 34 | + { | |
| 35 | + throw new ArgumentNullException(nameof(plainPassword)); | |
| 36 | + } | |
| 37 | + | |
| 38 | + var iv = RandomNumberGenerator.GetBytes(16); | |
| 39 | + using var aes = Aes.Create(); | |
| 40 | + aes.Key = _key; | |
| 41 | + aes.IV = iv; | |
| 42 | + aes.Mode = CipherMode.CBC; | |
| 43 | + aes.Padding = PaddingMode.PKCS7; | |
| 44 | + | |
| 45 | + using var encryptor = aes.CreateEncryptor(); | |
| 46 | + var plainBytes = Encoding.UTF8.GetBytes(plainPassword); | |
| 47 | + var cipherBytes = encryptor.TransformFinalBlock(plainBytes, 0, plainBytes.Length); | |
| 48 | + | |
| 49 | + return (Convert.ToBase64String(cipherBytes), Convert.ToBase64String(iv)); | |
| 50 | + } | |
| 51 | +} | ... | ... |
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application/MultiTenancy/ThTenantDatabaseBackgroundInitializer.cs
0 → 100644
| 1 | +using System.Collections.Concurrent; | |
| 2 | +using Microsoft.Extensions.DependencyInjection; | |
| 3 | +using Microsoft.Extensions.Logging; | |
| 4 | +using Volo.Abp.DependencyInjection; | |
| 5 | +using Yi.Framework.TenantManagement.Application.Contracts; | |
| 6 | + | |
| 7 | +namespace FoodLabeling.Th.Application.MultiTenancy; | |
| 8 | + | |
| 9 | +/// <summary> | |
| 10 | +/// 使用独立 DI Scope 在后台执行 <see cref="ITenantService.InitAsync"/>,避免阻塞 HTTP 请求。 | |
| 11 | +/// </summary> | |
| 12 | +public class ThTenantDatabaseBackgroundInitializer | |
| 13 | + : IThTenantDatabaseBackgroundInitializer, ISingletonDependency | |
| 14 | +{ | |
| 15 | + private readonly IServiceScopeFactory _scopeFactory; | |
| 16 | + private readonly ILogger<ThTenantDatabaseBackgroundInitializer> _logger; | |
| 17 | + private static readonly ConcurrentDictionary<Guid, byte> Running = new(); | |
| 18 | + | |
| 19 | + public ThTenantDatabaseBackgroundInitializer( | |
| 20 | + IServiceScopeFactory scopeFactory, | |
| 21 | + ILogger<ThTenantDatabaseBackgroundInitializer> logger) | |
| 22 | + { | |
| 23 | + _scopeFactory = scopeFactory; | |
| 24 | + _logger = logger; | |
| 25 | + } | |
| 26 | + | |
| 27 | + /// <inheritdoc /> | |
| 28 | + public void Enqueue(Guid tenantId) | |
| 29 | + { | |
| 30 | + if (!Running.TryAdd(tenantId, 0)) | |
| 31 | + { | |
| 32 | + _logger.LogInformation("租户 {TenantId} 业务库初始化已在进行中,跳过重复入队", tenantId); | |
| 33 | + return; | |
| 34 | + } | |
| 35 | + | |
| 36 | + _ = Task.Run(() => RunInitAsync(tenantId)); | |
| 37 | + } | |
| 38 | + | |
| 39 | + private async Task RunInitAsync(Guid tenantId) | |
| 40 | + { | |
| 41 | + try | |
| 42 | + { | |
| 43 | + _logger.LogInformation("租户 {TenantId} 业务库后台初始化开始", tenantId); | |
| 44 | + | |
| 45 | + using var scope = _scopeFactory.CreateScope(); | |
| 46 | + var tenantService = scope.ServiceProvider.GetRequiredService<ITenantService>(); | |
| 47 | + await tenantService.InitAsync(tenantId); | |
| 48 | + | |
| 49 | + _logger.LogInformation("租户 {TenantId} 业务库后台初始化完成", tenantId); | |
| 50 | + } | |
| 51 | + catch (Exception ex) | |
| 52 | + { | |
| 53 | + _logger.LogError(ex, "租户 {TenantId} 业务库后台初始化失败", tenantId); | |
| 54 | + } | |
| 55 | + finally | |
| 56 | + { | |
| 57 | + Running.TryRemove(tenantId, out _); | |
| 58 | + } | |
| 59 | + } | |
| 60 | +} | ... | ... |
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application/MultiTenancy/ThTenantSelectConsts.cs
0 → 100644
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application/Services/ThMultiTenancyAppService.cs
| 1 | -using FoodLabeling.Th.Application.Contracts.Dtos.MultiTenancy; | |
| 2 | -using FoodLabeling.Th.Application.Contracts.IServices; | |
| 3 | -using Microsoft.AspNetCore.Authorization; | |
| 4 | -using Volo.Abp.Application.Services; | |
| 5 | -using Volo.Abp.MultiTenancy; | |
| 6 | -using Yi.Framework.TenantManagement.Application.Contracts; | |
| 7 | -using Yi.Framework.TenantManagement.Application.Contracts.Dtos; | |
| 8 | - | |
| 9 | -namespace FoodLabeling.Th.Application.Services; | |
| 10 | - | |
| 11 | -/// <summary> | |
| 12 | -/// 泰额版多租户:租户下拉与当前租户上下文 | |
| 13 | -/// </summary> | |
| 14 | -public class ThMultiTenancyAppService : ApplicationService, IThMultiTenancyAppService | |
| 15 | -{ | |
| 16 | - private readonly ITenantService _tenantService; | |
| 17 | - | |
| 18 | - public ThMultiTenancyAppService(ITenantService tenantService) | |
| 19 | - { | |
| 20 | - _tenantService = tenantService; | |
| 21 | - } | |
| 22 | - | |
| 23 | - /// <inheritdoc /> | |
| 24 | - [AllowAnonymous] | |
| 25 | - public virtual async Task<List<ThTenantSelectDto>> GetTenantSelectAsync() | |
| 26 | - { | |
| 27 | - var page = await _tenantService.GetListAsync(new TenantGetListInput | |
| 28 | - { | |
| 29 | - SkipCount = 1, | |
| 30 | - MaxResultCount = 500 | |
| 31 | - }); | |
| 32 | - return page.Items | |
| 33 | - .Select(x => new ThTenantSelectDto { Id = x.Id, Name = x.Name }) | |
| 34 | - .OrderBy(x => x.Name) | |
| 35 | - .ToList(); | |
| 36 | - } | |
| 37 | - | |
| 38 | - /// <inheritdoc /> | |
| 39 | - public virtual Task<ThCurrentTenantDto> GetCurrentTenantAsync() | |
| 40 | - { | |
| 41 | - return Task.FromResult(new ThCurrentTenantDto | |
| 42 | - { | |
| 43 | - TenantId = CurrentTenant.Id, | |
| 44 | - TenantName = CurrentTenant.Name | |
| 45 | - }); | |
| 46 | - } | |
| 47 | -} | |
| 1 | +using FoodLabeling.Th.Application.Contracts.Dtos.MultiTenancy; | |
| 2 | +using FoodLabeling.Th.Application.Contracts.IServices; | |
| 3 | +using FoodLabeling.Th.Application.MultiTenancy; | |
| 4 | +using Microsoft.AspNetCore.Authorization; | |
| 5 | +using Microsoft.Extensions.Options; | |
| 6 | +using Volo.Abp.Application.Services; | |
| 7 | +using Volo.Abp.MultiTenancy; | |
| 8 | +using Yi.Framework.Rbac.Domain.Shared.Options; | |
| 9 | +using Yi.Framework.TenantManagement.Application.Contracts; | |
| 10 | +using Yi.Framework.TenantManagement.Application.Contracts.Dtos; | |
| 11 | + | |
| 12 | +namespace FoodLabeling.Th.Application.Services; | |
| 13 | + | |
| 14 | +/// <summary> | |
| 15 | +/// 泰额版多租户:租户下拉与当前租户上下文 | |
| 16 | +/// </summary> | |
| 17 | +public class ThMultiTenancyAppService : ApplicationService, IThMultiTenancyAppService | |
| 18 | +{ | |
| 19 | + private readonly ITenantService _tenantService; | |
| 20 | + private readonly TenantSelectCredentialCipher _credentialCipher; | |
| 21 | + private readonly RbacOptions _rbacOptions; | |
| 22 | + | |
| 23 | + public ThMultiTenancyAppService( | |
| 24 | + ITenantService tenantService, | |
| 25 | + TenantSelectCredentialCipher credentialCipher, | |
| 26 | + IOptions<RbacOptions> rbacOptions) | |
| 27 | + { | |
| 28 | + _tenantService = tenantService; | |
| 29 | + _credentialCipher = credentialCipher; | |
| 30 | + _rbacOptions = rbacOptions.Value; | |
| 31 | + } | |
| 32 | + | |
| 33 | + /// <summary> | |
| 34 | + /// 获取登录页可选租户列表(含默认管理员加密凭据) | |
| 35 | + /// </summary> | |
| 36 | + /// <remarks> | |
| 37 | + /// 供 Web 登录页租户下拉使用;匿名可访问。不返回租户 Id 与数据库连接串。 | |
| 38 | + /// | |
| 39 | + /// 示例响应: | |
| 40 | + /// ```json | |
| 41 | + /// [ | |
| 42 | + /// { | |
| 43 | + /// "name": "Default", | |
| 44 | + /// "creationTime": "2026-01-01T08:00:00", | |
| 45 | + /// "loginAccount": "admin", | |
| 46 | + /// "password": "Base64CipherText", | |
| 47 | + /// "passwordSalt": "Base64Iv" | |
| 48 | + /// } | |
| 49 | + /// ] | |
| 50 | + /// ``` | |
| 51 | + /// | |
| 52 | + /// 字段说明: | |
| 53 | + /// - name: 租户名称,登录时可传 tenantName | |
| 54 | + /// - creationTime: 租户创建时间 | |
| 55 | + /// - loginAccount: 种子管理员账号(UserName=admin,亦可用 admin@example.com 登录) | |
| 56 | + /// - password: RbacOptions.AdminPassword 经 AES-CBC 加密后的 Base64 密文 | |
| 57 | + /// - passwordSalt: AES IV(Base64),前端解密时使用 | |
| 58 | + /// </remarks> | |
| 59 | + /// <returns>租户下拉列表</returns> | |
| 60 | + /// <response code="200">成功返回租户列表</response> | |
| 61 | + /// <response code="500">加密配置缺失或服务器错误</response> | |
| 62 | + [AllowAnonymous] | |
| 63 | + public virtual async Task<List<ThTenantSelectDto>> GetTenantSelectAsync() | |
| 64 | + { | |
| 65 | + var page = await _tenantService.GetListAsync(new TenantGetListInput | |
| 66 | + { | |
| 67 | + SkipCount = 1, | |
| 68 | + MaxResultCount = 500 | |
| 69 | + }); | |
| 70 | + | |
| 71 | + var adminPlainPassword = _rbacOptions.AdminPassword ?? string.Empty; | |
| 72 | + return page.Items | |
| 73 | + .Select(x => | |
| 74 | + { | |
| 75 | + var encrypted = _credentialCipher.EncryptPassword(adminPlainPassword); | |
| 76 | + return new ThTenantSelectDto | |
| 77 | + { | |
| 78 | + Name = x.Name, | |
| 79 | + CreationTime = x.CreationTime, | |
| 80 | + LoginAccount = ThTenantSelectConsts.DefaultAdminLoginAccount, | |
| 81 | + Password = encrypted.Password, | |
| 82 | + PasswordSalt = encrypted.PasswordSalt | |
| 83 | + }; | |
| 84 | + }) | |
| 85 | + .OrderBy(x => x.Name) | |
| 86 | + .ToList(); | |
| 87 | + } | |
| 88 | + | |
| 89 | + /// <inheritdoc /> | |
| 90 | + public virtual Task<ThCurrentTenantDto> GetCurrentTenantAsync() | |
| 91 | + { | |
| 92 | + return Task.FromResult(new ThCurrentTenantDto | |
| 93 | + { | |
| 94 | + TenantId = CurrentTenant.Id, | |
| 95 | + TenantName = CurrentTenant.Name | |
| 96 | + }); | |
| 97 | + } | |
| 98 | +} | |
| 99 | + | |
| 48 | 100 | \ No newline at end of file | ... | ... |
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application/Services/ThTenantProvisioningAppService.cs
| ... | ... | @@ -3,11 +3,13 @@ using FoodLabeling.Th.Application.Contracts.IServices; |
| 3 | 3 | using FoodLabeling.Th.Application.Contracts.Options; |
| 4 | 4 | using FoodLabeling.Th.Application.MultiTenancy; |
| 5 | 5 | using Microsoft.AspNetCore.Authorization; |
| 6 | +using Microsoft.AspNetCore.Http.Timeouts; | |
| 6 | 7 | using Microsoft.Extensions.Options; |
| 7 | 8 | using SqlSugar; |
| 8 | 9 | using Volo.Abp; |
| 9 | 10 | using Volo.Abp.Application.Services; |
| 10 | 11 | using Volo.Abp.MultiTenancy; |
| 12 | +using Volo.Abp.Uow; | |
| 11 | 13 | using Yi.Framework.TenantManagement.Application.Contracts; |
| 12 | 14 | using Yi.Framework.TenantManagement.Application.Contracts.Dtos; |
| 13 | 15 | |
| ... | ... | @@ -16,17 +18,42 @@ namespace FoodLabeling.Th.Application.Services; |
| 16 | 18 | /// <summary> |
| 17 | 19 | /// 泰额版租户独立库开通(平台主库 yitenant + 租户业务库) |
| 18 | 20 | /// </summary> |
| 21 | +/// <remarks> | |
| 22 | +/// 脏数据修复(业务库 antis-foodlabeling-us 误写入的 YiTenant 迁回主库 antis-foodlabeling-host,名称冲突则跳过): | |
| 23 | +/// <code> | |
| 24 | +/// INSERT INTO `antis-foodlabeling-host`.YiTenant | |
| 25 | +/// (Id, Name, TenantConnectionString, DbType, EntityVersion, | |
| 26 | +/// ConcurrencyStamp, CreationTime, CreatorId, | |
| 27 | +/// LastModificationTime, LastModifierId, IsDeleted, DeleterId, DeletionTime) | |
| 28 | +/// SELECT u.Id, u.Name, u.TenantConnectionString, u.DbType, u.EntityVersion, | |
| 29 | +/// u.ConcurrencyStamp, u.CreationTime, u.CreatorId, | |
| 30 | +/// u.LastModificationTime, u.LastModifierId, u.IsDeleted, u.DeleterId, u.DeletionTime | |
| 31 | +/// FROM `antis-foodlabeling-us`.YiTenant u | |
| 32 | +/// WHERE u.Name IN ('mike', '中国麦当劳公司') | |
| 33 | +/// AND NOT EXISTS ( | |
| 34 | +/// SELECT 1 FROM `antis-foodlabeling-host`.YiTenant h WHERE h.Name = u.Name OR h.Id = u.Id | |
| 35 | +/// ); | |
| 36 | +/// -- 确认主库可查后再按需清理业务库副本(谨慎执行): | |
| 37 | +/// -- DELETE FROM `antis-foodlabeling-us`.YiTenant WHERE Name IN ('mike', '中国麦当劳公司'); | |
| 38 | +/// </code> | |
| 39 | +/// </remarks> | |
| 19 | 40 | [Authorize] |
| 20 | 41 | public class ThTenantProvisioningAppService : ApplicationService, IThTenantProvisioningAppService |
| 21 | 42 | { |
| 43 | + /// <summary>同步初始化路径请求超时策略名,与 Web 模块 <c>ThTenantDatabaseInit</c> 一致</summary> | |
| 44 | + public const string TenantDatabaseInitRequestTimeoutPolicy = "ThTenantDatabaseInit"; | |
| 45 | + | |
| 22 | 46 | private readonly ITenantService _tenantService; |
| 47 | + private readonly IThTenantDatabaseBackgroundInitializer _backgroundInitializer; | |
| 23 | 48 | private readonly FoodLabelingThTenantDatabaseOptions _dbOptions; |
| 24 | 49 | |
| 25 | 50 | public ThTenantProvisioningAppService( |
| 26 | 51 | ITenantService tenantService, |
| 52 | + IThTenantDatabaseBackgroundInitializer backgroundInitializer, | |
| 27 | 53 | IOptions<FoodLabelingThTenantDatabaseOptions> dbOptions) |
| 28 | 54 | { |
| 29 | 55 | _tenantService = tenantService; |
| 56 | + _backgroundInitializer = backgroundInitializer; | |
| 30 | 57 | _dbOptions = dbOptions.Value; |
| 31 | 58 | } |
| 32 | 59 | |
| ... | ... | @@ -39,29 +66,42 @@ public class ThTenantProvisioningAppService : ApplicationService, IThTenantProvi |
| 39 | 66 | } |
| 40 | 67 | |
| 41 | 68 | var connectionString = string.IsNullOrWhiteSpace(input.TenantConnectionString) |
| 42 | - ? TenantDatabaseConnectionStringBuilder.BuildMySqlConnectionString(_dbOptions, input.Name) | |
| 69 | + ? TenantDatabaseConnectionStringBuilder.BuildMySqlConnectionString( | |
| 70 | + _dbOptions, | |
| 71 | + input.Name, | |
| 72 | + input.DatabaseKey) | |
| 43 | 73 | : input.TenantConnectionString.Trim(); |
| 44 | 74 | |
| 45 | 75 | var databaseName = ExtractDatabaseName(connectionString) |
| 46 | - ?? TenantDatabaseConnectionStringBuilder.BuildDatabaseName(_dbOptions, input.Name); | |
| 76 | + ?? TenantDatabaseConnectionStringBuilder.BuildDatabaseName( | |
| 77 | + _dbOptions, | |
| 78 | + input.Name, | |
| 79 | + input.DatabaseKey); | |
| 47 | 80 | |
| 48 | 81 | // 平台主库写入 yitenant(CurrentTenant 为空时走 DbConnOptions 主库) |
| 49 | 82 | var dbType = Enum.IsDefined(typeof(DbType), input.DbType) |
| 50 | 83 | ? (DbType)input.DbType |
| 51 | 84 | : DbType.MySql; |
| 52 | 85 | |
| 53 | - var created = await _tenantService.CreateAsync(new TenantCreateInput | |
| 86 | + // YiTenant 必须写入主库;Create 与 Init 分事务提交,Init 经 TenantStore 读主库需可见记录 | |
| 87 | + TenantGetOutputDto created; | |
| 88 | + using (CurrentTenant.Change(null)) | |
| 89 | + using (var uow = UnitOfWorkManager.Begin(requiresNew: true, isTransactional: true)) | |
| 54 | 90 | { |
| 55 | - Name = input.Name.Trim(), | |
| 56 | - TenantConnectionString = connectionString, | |
| 57 | - DbType = dbType | |
| 58 | - }); | |
| 91 | + created = await _tenantService.CreateAsync(new TenantCreateInput | |
| 92 | + { | |
| 93 | + Name = input.Name.Trim(), | |
| 94 | + TenantConnectionString = connectionString, | |
| 95 | + DbType = dbType | |
| 96 | + }); | |
| 97 | + await uow.CompleteAsync(); | |
| 98 | + } | |
| 59 | 99 | |
| 60 | - var initialized = false; | |
| 100 | + var initializing = false; | |
| 61 | 101 | if (input.InitializeDatabase) |
| 62 | 102 | { |
| 63 | - await _tenantService.InitAsync(created.Id); | |
| 64 | - initialized = true; | |
| 103 | + _backgroundInitializer.Enqueue(created.Id); | |
| 104 | + initializing = true; | |
| 65 | 105 | } |
| 66 | 106 | |
| 67 | 107 | return new ThProvisionTenantOutputDto |
| ... | ... | @@ -70,11 +110,13 @@ public class ThTenantProvisioningAppService : ApplicationService, IThTenantProvi |
| 70 | 110 | Name = created.Name, |
| 71 | 111 | DatabaseName = databaseName, |
| 72 | 112 | TenantConnectionString = connectionString, |
| 73 | - DatabaseInitialized = initialized | |
| 113 | + DatabaseInitialized = false, | |
| 114 | + DatabaseInitializing = initializing | |
| 74 | 115 | }; |
| 75 | 116 | } |
| 76 | 117 | |
| 77 | 118 | /// <inheritdoc /> |
| 119 | + [RequestTimeout(TenantDatabaseInitRequestTimeoutPolicy)] | |
| 78 | 120 | public virtual Task InitializeTenantDatabaseAsync(Guid tenantId) |
| 79 | 121 | { |
| 80 | 122 | return _tenantService.InitAsync(tenantId); | ... | ... |
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application/Services/ThWebAuthAppService.cs
| 1 | 1 | using FoodLabeling.Th.Application.Contracts.Dtos.Auth; |
| 2 | + | |
| 2 | 3 | using FoodLabeling.Th.Application.Contracts.IServices; |
| 4 | + | |
| 3 | 5 | using FoodLabeling.Th.Application.MultiTenancy; |
| 6 | + | |
| 4 | 7 | using Lazy.Captcha.Core; |
| 8 | + | |
| 5 | 9 | using Microsoft.AspNetCore.Authorization; |
| 10 | + | |
| 6 | 11 | using Microsoft.AspNetCore.Mvc; |
| 12 | + | |
| 7 | 13 | using Microsoft.Extensions.Options; |
| 14 | + | |
| 8 | 15 | using SqlSugar; |
| 16 | + | |
| 9 | 17 | using Volo.Abp; |
| 18 | + | |
| 10 | 19 | using Volo.Abp.Application.Services; |
| 20 | + | |
| 11 | 21 | using Volo.Abp.MultiTenancy; |
| 22 | + | |
| 12 | 23 | using Yi.Framework.Rbac.Domain.Entities; |
| 24 | + | |
| 13 | 25 | using Yi.Framework.Rbac.Domain.Managers; |
| 26 | + | |
| 14 | 27 | using Yi.Framework.Rbac.Domain.Shared.Consts; |
| 28 | + | |
| 15 | 29 | using Yi.Framework.Rbac.Domain.Shared.Options; |
| 30 | + | |
| 16 | 31 | using Yi.Framework.SqlSugarCore.Abstractions; |
| 17 | 32 | |
| 33 | + | |
| 34 | + | |
| 18 | 35 | namespace FoodLabeling.Th.Application.Services; |
| 19 | 36 | |
| 37 | + | |
| 38 | + | |
| 20 | 39 | /// <summary> |
| 40 | + | |
| 21 | 41 | /// 泰额版 Web 管理端登录:租户库校验 + RBAC 全量 Token(含 TenantId Claim) |
| 42 | + | |
| 22 | 43 | /// </summary> |
| 44 | + | |
| 23 | 45 | public class ThWebAuthAppService : ApplicationService, IThWebAuthAppService |
| 46 | + | |
| 24 | 47 | { |
| 48 | + | |
| 25 | 49 | private readonly IAccountManager _accountManager; |
| 50 | + | |
| 26 | 51 | private readonly ISqlSugarRepository<UserAggregateRoot, Guid> _userRepository; |
| 52 | + | |
| 27 | 53 | private readonly ICaptcha _captcha; |
| 54 | + | |
| 28 | 55 | private readonly RbacOptions _rbacOptions; |
| 56 | + | |
| 29 | 57 | private readonly ITenantStore _tenantStore; |
| 30 | 58 | |
| 59 | + | |
| 60 | + | |
| 31 | 61 | public ThWebAuthAppService( |
| 62 | + | |
| 32 | 63 | IAccountManager accountManager, |
| 64 | + | |
| 33 | 65 | ISqlSugarRepository<UserAggregateRoot, Guid> userRepository, |
| 66 | + | |
| 34 | 67 | ICaptcha captcha, |
| 68 | + | |
| 35 | 69 | IOptions<RbacOptions> rbacOptions, |
| 70 | + | |
| 36 | 71 | ITenantStore tenantStore) |
| 72 | + | |
| 37 | 73 | { |
| 74 | + | |
| 38 | 75 | _accountManager = accountManager; |
| 76 | + | |
| 39 | 77 | _userRepository = userRepository; |
| 78 | + | |
| 40 | 79 | _captcha = captcha; |
| 80 | + | |
| 41 | 81 | _rbacOptions = rbacOptions.Value; |
| 82 | + | |
| 42 | 83 | _tenantStore = tenantStore; |
| 84 | + | |
| 43 | 85 | } |
| 44 | 86 | |
| 45 | - /// <inheritdoc /> | |
| 87 | + | |
| 88 | + | |
| 89 | + /// <summary> | |
| 90 | + | |
| 91 | + /// Web 管理端登录 | |
| 92 | + | |
| 93 | + /// </summary> | |
| 94 | + | |
| 95 | + /// <remarks> | |
| 96 | + | |
| 97 | + /// 校验租户后在租户独立库验证账号,签发含 TenantId 与 RBAC 权限的 JWT。 | |
| 98 | + | |
| 99 | + /// | |
| 100 | + | |
| 101 | + /// 示例请求(tenant-select 不再返回 Id 时使用 tenantName): | |
| 102 | + | |
| 103 | + /// ```json | |
| 104 | + | |
| 105 | + /// { | |
| 106 | + | |
| 107 | + /// "tenantName": "Default", | |
| 108 | + | |
| 109 | + /// "userName": "admin", | |
| 110 | + | |
| 111 | + /// "password": "123456", | |
| 112 | + | |
| 113 | + /// "uuid": null, | |
| 114 | + | |
| 115 | + /// "code": null | |
| 116 | + | |
| 117 | + /// } | |
| 118 | + | |
| 119 | + /// ``` | |
| 120 | + | |
| 121 | + /// | |
| 122 | + | |
| 123 | + /// 参数说明: | |
| 124 | + | |
| 125 | + /// - tenantId: 可选,租户 Guid(与 tenantName 二选一) | |
| 126 | + | |
| 127 | + /// - tenantName: 可选,租户名称(与 tenantId 二选一) | |
| 128 | + | |
| 129 | + /// - userName: 登录账号或邮箱 | |
| 130 | + | |
| 131 | + /// - password: 明文密码 | |
| 132 | + | |
| 133 | + /// </remarks> | |
| 134 | + | |
| 135 | + /// <param name="input">登录参数</param> | |
| 136 | + | |
| 137 | + /// <returns>Token 与租户信息</returns> | |
| 138 | + | |
| 139 | + /// <response code="200">登录成功</response> | |
| 140 | + | |
| 141 | + /// <response code="400">参数缺失、验证码错误或账号密码错误</response> | |
| 142 | + | |
| 143 | + /// <response code="500">服务器错误</response> | |
| 144 | + | |
| 46 | 145 | [AllowAnonymous] |
| 146 | + | |
| 47 | 147 | [HttpPost("th-web-auth/login")] |
| 148 | + | |
| 48 | 149 | public virtual async Task<ThWebLoginOutputDto> LoginAsync(ThWebLoginInputVo input) |
| 150 | + | |
| 49 | 151 | { |
| 50 | - if (input.TenantId == Guid.Empty | |
| 51 | - || string.IsNullOrWhiteSpace(input.Password) | |
| 152 | + | |
| 153 | + if (string.IsNullOrWhiteSpace(input.Password) | |
| 154 | + | |
| 52 | 155 | || string.IsNullOrWhiteSpace(input.UserName)) |
| 156 | + | |
| 53 | 157 | { |
| 54 | - throw new UserFriendlyException("请输入租户、邮箱与密码!"); | |
| 158 | + | |
| 159 | + throw new UserFriendlyException("请输入租户、账号与密码!"); | |
| 160 | + | |
| 55 | 161 | } |
| 56 | 162 | |
| 163 | + | |
| 164 | + | |
| 57 | 165 | ValidationImageCaptcha(input.Uuid, input.Code); |
| 58 | 166 | |
| 167 | + | |
| 168 | + | |
| 59 | 169 | var tenantConfig = await TenantResolveHelper.ResolveTenantAsync( |
| 60 | - _tenantStore, CurrentTenant, input.TenantId); | |
| 170 | + | |
| 171 | + _tenantStore, CurrentTenant, input.TenantId, input.TenantName); | |
| 172 | + | |
| 173 | + var tenantId = tenantConfig.Id; | |
| 174 | + | |
| 175 | + | |
| 61 | 176 | |
| 62 | 177 | UserAggregateRoot user; |
| 178 | + | |
| 63 | 179 | string accessToken; |
| 180 | + | |
| 64 | 181 | string refreshToken; |
| 65 | - using (CurrentTenant.Change(input.TenantId, tenantConfig.Name)) | |
| 182 | + | |
| 183 | + using (CurrentTenant.Change(tenantId, tenantConfig.Name)) | |
| 184 | + | |
| 66 | 185 | { |
| 186 | + | |
| 67 | 187 | user = await FindActiveUserByEmailAsync(input.UserName.Trim()) |
| 188 | + | |
| 68 | 189 | ?? throw new UserFriendlyException("Sign-in failed: account not found."); |
| 69 | 190 | |
| 191 | + | |
| 192 | + | |
| 70 | 193 | if (!user.JudgePassword(input.Password)) |
| 194 | + | |
| 71 | 195 | { |
| 196 | + | |
| 72 | 197 | throw new UserFriendlyException(UserConst.Login_Error); |
| 198 | + | |
| 73 | 199 | } |
| 74 | 200 | |
| 201 | + | |
| 202 | + | |
| 75 | 203 | accessToken = await _accountManager.GetTokenByUserIdAsync(user.Id); |
| 204 | + | |
| 76 | 205 | refreshToken = _accountManager.CreateRefreshToken(user.Id); |
| 206 | + | |
| 77 | 207 | } |
| 78 | 208 | |
| 209 | + | |
| 210 | + | |
| 79 | 211 | return new ThWebLoginOutputDto |
| 212 | + | |
| 80 | 213 | { |
| 214 | + | |
| 81 | 215 | Token = accessToken, |
| 216 | + | |
| 82 | 217 | RefreshToken = refreshToken, |
| 83 | - TenantId = input.TenantId, | |
| 218 | + | |
| 219 | + TenantId = tenantId, | |
| 220 | + | |
| 84 | 221 | TenantName = tenantConfig.Name ?? string.Empty |
| 222 | + | |
| 85 | 223 | }; |
| 224 | + | |
| 86 | 225 | } |
| 87 | 226 | |
| 227 | + | |
| 228 | + | |
| 88 | 229 | private void ValidationImageCaptcha(string? uuid, string? code) |
| 230 | + | |
| 89 | 231 | { |
| 232 | + | |
| 90 | 233 | if (!_rbacOptions.EnableCaptcha) |
| 234 | + | |
| 91 | 235 | { |
| 236 | + | |
| 92 | 237 | return; |
| 238 | + | |
| 93 | 239 | } |
| 94 | 240 | |
| 241 | + | |
| 242 | + | |
| 95 | 243 | if (!_captcha.Validate(uuid, code)) |
| 244 | + | |
| 96 | 245 | { |
| 246 | + | |
| 97 | 247 | throw new UserFriendlyException("Invalid captcha."); |
| 248 | + | |
| 98 | 249 | } |
| 250 | + | |
| 99 | 251 | } |
| 100 | 252 | |
| 253 | + | |
| 254 | + | |
| 101 | 255 | private async Task<UserAggregateRoot?> FindActiveUserByEmailAsync(string email) |
| 256 | + | |
| 102 | 257 | { |
| 258 | + | |
| 103 | 259 | var normalized = email.Trim().ToLowerInvariant(); |
| 260 | + | |
| 104 | 261 | var users = await _userRepository._DbQueryable |
| 262 | + | |
| 105 | 263 | .Where(u => !u.IsDeleted && u.State) |
| 264 | + | |
| 106 | 265 | .Where(u => |
| 266 | + | |
| 107 | 267 | (u.Email != null && SqlFunc.ToLower(u.Email) == normalized) || |
| 268 | + | |
| 108 | 269 | SqlFunc.ToLower(u.UserName) == normalized) |
| 270 | + | |
| 109 | 271 | .ToListAsync(); |
| 272 | + | |
| 110 | 273 | return users.FirstOrDefault(u => |
| 274 | + | |
| 111 | 275 | u.Email != null && |
| 276 | + | |
| 112 | 277 | string.Equals(u.Email.Trim(), normalized, StringComparison.OrdinalIgnoreCase)) |
| 278 | + | |
| 113 | 279 | ?? users.FirstOrDefault(); |
| 280 | + | |
| 114 | 281 | } |
| 282 | + | |
| 115 | 283 | } |
| 284 | + | |
| 285 | + | ... | ... |
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/rbac/Yi.Framework.Rbac.Domain/Entities/ConfigAggregateRoot.cs
| ... | ... | @@ -32,7 +32,7 @@ namespace Yi.Framework.Rbac.Domain.Entities |
| 32 | 32 | /// <summary> |
| 33 | 33 | /// 配置类别 |
| 34 | 34 | ///</summary> |
| 35 | - [SugarColumn(ColumnName = "ConfigType")] | |
| 35 | + [SugarColumn(ColumnName = "ConfigType", IsNullable = true)] | |
| 36 | 36 | public string? ConfigType { get; set; } |
| 37 | 37 | |
| 38 | 38 | /// <summary> | ... | ... |
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/rbac/Yi.Framework.Rbac.SqlSugarCore/DataSeeds/ConfigDataSeed.cs
| ... | ... | @@ -38,6 +38,8 @@ namespace Yi.Framework.Rbac.SqlSugarCore.DataSeeds |
| 38 | 38 | ConfigName = "初始密码", |
| 39 | 39 | ConfigKey = "sys.user.initPassword", |
| 40 | 40 | ConfigValue = "123456", |
| 41 | + // CodeFirst 新库上 ConfigType 常为 NOT NULL,种子必须赋值 | |
| 42 | + ConfigType = "N", | |
| 41 | 43 | OrderNum = 1, |
| 42 | 44 | IsDeleted = false, |
| 43 | 45 | Remark = "初始密码" | ... | ... |
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/tenant-management/Yi.Framework.TenantManagement.Application/TenantService.cs
| 1 | 1 | using System.Reflection; |
| 2 | +using System.Text.RegularExpressions; | |
| 3 | +using Microsoft.AspNetCore.Http.Timeouts; | |
| 2 | 4 | using Microsoft.AspNetCore.Mvc; |
| 3 | 5 | using Microsoft.Extensions.DependencyInjection; |
| 6 | +using Microsoft.Extensions.Options; | |
| 4 | 7 | using SqlSugar; |
| 5 | 8 | using Volo.Abp; |
| 6 | 9 | using Volo.Abp.Application.Dtos; |
| 7 | 10 | using Volo.Abp.Data; |
| 8 | 11 | using Volo.Abp.Modularity; |
| 12 | +using Volo.Abp.MultiTenancy; | |
| 9 | 13 | using Volo.Abp.Uow; |
| 10 | 14 | using Yi.Framework.Ddd.Application; |
| 11 | 15 | using Yi.Framework.SqlSugarCore.Abstractions; |
| ... | ... | @@ -22,24 +26,38 @@ namespace Yi.Framework.TenantManagement.Application |
| 22 | 26 | YiCrudAppService<TenantAggregateRoot, TenantGetOutputDto, TenantGetListOutputDto, Guid, TenantGetListInput, |
| 23 | 27 | TenantCreateInput, TenantUpdateInput>, ITenantService |
| 24 | 28 | { |
| 25 | - private ISqlSugarRepository<TenantAggregateRoot, Guid> _repository; | |
| 26 | - private IDataSeeder _dataSeeder; | |
| 29 | + private readonly ISqlSugarRepository<TenantAggregateRoot, Guid> _repository; | |
| 30 | + private readonly IDataSeeder _dataSeeder; | |
| 31 | + private readonly DbConnOptions _dbConnOptions; | |
| 27 | 32 | |
| 28 | - public TenantService(ISqlSugarRepository<TenantAggregateRoot, Guid> repository, IDataSeeder dataSeeder) : | |
| 33 | + public TenantService( | |
| 34 | + ISqlSugarRepository<TenantAggregateRoot, Guid> repository, | |
| 35 | + IDataSeeder dataSeeder, | |
| 36 | + IOptions<DbConnOptions> dbConnOptions) : | |
| 29 | 37 | base(repository) |
| 30 | 38 | { |
| 31 | 39 | _repository = repository; |
| 32 | 40 | _dataSeeder = dataSeeder; |
| 41 | + _dbConnOptions = dbConnOptions.Value; | |
| 33 | 42 | } |
| 34 | 43 | |
| 35 | 44 | /// <summary> |
| 45 | + /// YiTenant 标记了 <see cref="DefaultTenantTableAttribute"/>,读写必须走主库(CurrentTenant=null → DbConnOptions.Url), | |
| 46 | + /// 不能随请求租户上下文落到 Default 租户的业务库。 | |
| 47 | + /// </summary> | |
| 48 | + private IDisposable UseHostTenantScope() => CurrentTenant.Change(null); | |
| 49 | + | |
| 50 | + /// <summary> | |
| 36 | 51 | /// 租户单查 |
| 37 | 52 | /// </summary> |
| 38 | 53 | /// <param name="id"></param> |
| 39 | 54 | /// <returns></returns> |
| 40 | - public override Task<TenantGetOutputDto> GetAsync(Guid id) | |
| 55 | + public override async Task<TenantGetOutputDto> GetAsync(Guid id) | |
| 41 | 56 | { |
| 42 | - return base.GetAsync(id); | |
| 57 | + using (UseHostTenantScope()) | |
| 58 | + { | |
| 59 | + return await base.GetAsync(id); | |
| 60 | + } | |
| 43 | 61 | } |
| 44 | 62 | |
| 45 | 63 | /// <summary> |
| ... | ... | @@ -49,14 +67,17 @@ namespace Yi.Framework.TenantManagement.Application |
| 49 | 67 | /// <returns></returns> |
| 50 | 68 | public override async Task<PagedResultDto<TenantGetListOutputDto>> GetListAsync(TenantGetListInput input) |
| 51 | 69 | { |
| 52 | - RefAsync<int> total = 0; | |
| 70 | + using (UseHostTenantScope()) | |
| 71 | + { | |
| 72 | + RefAsync<int> total = 0; | |
| 53 | 73 | |
| 54 | - var entities = await _repository._DbQueryable | |
| 55 | - .WhereIF(!string.IsNullOrEmpty(input.Name), x => x.Name.Contains(input.Name!)) | |
| 56 | - .WhereIF(input.StartTime is not null && input.EndTime is not null, | |
| 57 | - x => x.CreationTime >= input.StartTime && x.CreationTime <= input.EndTime) | |
| 58 | - .ToPageListAsync(input.SkipCount, input.MaxResultCount, total); | |
| 59 | - return new PagedResultDto<TenantGetListOutputDto>(total, await MapToGetListOutputDtosAsync(entities)); | |
| 74 | + var entities = await _repository._DbQueryable | |
| 75 | + .WhereIF(!string.IsNullOrEmpty(input.Name), x => x.Name.Contains(input.Name!)) | |
| 76 | + .WhereIF(input.StartTime is not null && input.EndTime is not null, | |
| 77 | + x => x.CreationTime >= input.StartTime && x.CreationTime <= input.EndTime) | |
| 78 | + .ToPageListAsync(input.SkipCount, input.MaxResultCount, total); | |
| 79 | + return new PagedResultDto<TenantGetListOutputDto>(total, await MapToGetListOutputDtosAsync(entities)); | |
| 80 | + } | |
| 60 | 81 | } |
| 61 | 82 | |
| 62 | 83 | /// <summary> |
| ... | ... | @@ -65,8 +86,11 @@ namespace Yi.Framework.TenantManagement.Application |
| 65 | 86 | /// <returns></returns> |
| 66 | 87 | public async Task<List<TenantSelectOutputDto>> GetSelectAsync() |
| 67 | 88 | { |
| 68 | - var entites = await _repository._DbQueryable.ToListAsync(); | |
| 69 | - return entites.Select(x => new TenantSelectOutputDto { Id = x.Id, Name = x.Name }).ToList(); | |
| 89 | + using (UseHostTenantScope()) | |
| 90 | + { | |
| 91 | + var entites = await _repository._DbQueryable.ToListAsync(); | |
| 92 | + return entites.Select(x => new TenantSelectOutputDto { Id = x.Id, Name = x.Name }).ToList(); | |
| 93 | + } | |
| 70 | 94 | } |
| 71 | 95 | |
| 72 | 96 | |
| ... | ... | @@ -77,12 +101,15 @@ namespace Yi.Framework.TenantManagement.Application |
| 77 | 101 | /// <returns></returns> |
| 78 | 102 | public override async Task<TenantGetOutputDto> CreateAsync(TenantCreateInput input) |
| 79 | 103 | { |
| 80 | - if (await _repository.IsAnyAsync(x => x.Name == input.Name)) | |
| 104 | + using (UseHostTenantScope()) | |
| 81 | 105 | { |
| 82 | - throw new UserFriendlyException("创建失败,当前租户已存在"); | |
| 83 | - } | |
| 106 | + if (await _repository.IsAnyAsync(x => x.Name == input.Name)) | |
| 107 | + { | |
| 108 | + throw new UserFriendlyException("创建失败,当前租户已存在"); | |
| 109 | + } | |
| 84 | 110 | |
| 85 | - return await base.CreateAsync(input); | |
| 111 | + return await base.CreateAsync(input); | |
| 112 | + } | |
| 86 | 113 | } |
| 87 | 114 | |
| 88 | 115 | /// <summary> |
| ... | ... | @@ -93,12 +120,15 @@ namespace Yi.Framework.TenantManagement.Application |
| 93 | 120 | /// <returns></returns> |
| 94 | 121 | public override async Task<TenantGetOutputDto> UpdateAsync(Guid id, TenantUpdateInput input) |
| 95 | 122 | { |
| 96 | - if (await _repository.IsAnyAsync(x => x.Name == input.Name && x.Id != id)) | |
| 123 | + using (UseHostTenantScope()) | |
| 97 | 124 | { |
| 98 | - throw new UserFriendlyException("更新后租户名已经存在"); | |
| 99 | - } | |
| 125 | + if (await _repository.IsAnyAsync(x => x.Name == input.Name && x.Id != id)) | |
| 126 | + { | |
| 127 | + throw new UserFriendlyException("更新后租户名已经存在"); | |
| 128 | + } | |
| 100 | 129 | |
| 101 | - return await base.UpdateAsync(id, input); | |
| 130 | + return await base.UpdateAsync(id, input); | |
| 131 | + } | |
| 102 | 132 | } |
| 103 | 133 | |
| 104 | 134 | |
| ... | ... | @@ -107,9 +137,12 @@ namespace Yi.Framework.TenantManagement.Application |
| 107 | 137 | /// </summary> |
| 108 | 138 | /// <param name="id"></param> |
| 109 | 139 | /// <returns></returns> |
| 110 | - public override Task DeleteAsync(IEnumerable<Guid> id) | |
| 140 | + public override async Task DeleteAsync(IEnumerable<Guid> id) | |
| 111 | 141 | { |
| 112 | - return base.DeleteAsync(id); | |
| 142 | + using (UseHostTenantScope()) | |
| 143 | + { | |
| 144 | + await base.DeleteAsync(id); | |
| 145 | + } | |
| 113 | 146 | } |
| 114 | 147 | |
| 115 | 148 | |
| ... | ... | @@ -119,44 +152,374 @@ namespace Yi.Framework.TenantManagement.Application |
| 119 | 152 | /// <param name="id"></param> |
| 120 | 153 | /// <returns></returns> |
| 121 | 154 | [HttpPut("tenant/init/{id}")] |
| 155 | + [RequestTimeout("ThTenantDatabaseInit")] | |
| 122 | 156 | public async Task InitAsync([FromRoute] Guid id) |
| 123 | 157 | { |
| 124 | - await CurrentUnitOfWork.SaveChangesAsync(); | |
| 158 | + TenantAggregateRoot tenant; | |
| 159 | + using (UseHostTenantScope()) | |
| 160 | + { | |
| 161 | + if (CurrentUnitOfWork != null) | |
| 162 | + { | |
| 163 | + await CurrentUnitOfWork.SaveChangesAsync(); | |
| 164 | + } | |
| 165 | + | |
| 166 | + tenant = await _repository.FindAsync(id); | |
| 167 | + if (tenant == null) | |
| 168 | + { | |
| 169 | + throw new UserFriendlyException("未找到租户信息"); | |
| 170 | + } | |
| 171 | + } | |
| 172 | + | |
| 173 | + // 用主库读到的连接串直接建库/表,不依赖 CurrentTenant.Change(id) 解析仓储连接 | |
| 174 | + await CodeFirstForTenantAsync(tenant, LazyServiceProvider); | |
| 175 | + | |
| 125 | 176 | using (CurrentTenant.Change(id)) |
| 126 | 177 | { |
| 127 | - await CodeFirst(this.LazyServiceProvider); | |
| 128 | - await _dataSeeder.SeedAsync(id); | |
| 178 | + await _dataSeeder.SeedAsync(id); | |
| 129 | 179 | } |
| 130 | 180 | } |
| 131 | 181 | |
| 132 | - private async Task CodeFirst(IServiceProvider service) | |
| 182 | + /// <summary> | |
| 183 | + /// 在租户业务库执行 CodeFirst(连接串来自主库 YiTenant 记录)。 | |
| 184 | + /// 步骤:无库名连接建库 → 新连接连目标库建表(建库后必须重连,同会话 USE 在部分 MySQL/RDS 会 Access denied)。 | |
| 185 | + /// </summary> | |
| 186 | + private async Task CodeFirstForTenantAsync(TenantAggregateRoot tenant, IServiceProvider service) | |
| 133 | 187 | { |
| 134 | 188 | var moduleContainer = service.GetRequiredService<IModuleContainer>(); |
| 135 | 189 | |
| 136 | - //没有数据库,不能创工作单元,创建库,先关闭 | |
| 137 | - using (var uow = UnitOfWorkManager.Begin(requiresNew: true, isTransactional: false)) | |
| 190 | + List<Type> types = new List<Type>(); | |
| 191 | + foreach (var module in moduleContainer.Modules) | |
| 138 | 192 | { |
| 139 | - ISqlSugarClient db = await _repository.GetDbContextAsync(); | |
| 140 | - //尝试创建数据库 | |
| 141 | - db.DbMaintenance.CreateDatabase(); | |
| 193 | + types.AddRange(module.Assembly.GetTypes() | |
| 194 | + .Where(x => x.GetCustomAttribute<IgnoreCodeFirstAttribute>() == null) | |
| 195 | + .Where(x => x.GetCustomAttribute<SugarTable>() != null) | |
| 196 | + .Where(x => x.GetCustomAttribute<DefaultTenantTableAttribute>() is null) | |
| 197 | + .Where(x => x.GetCustomAttribute<SplitTableAttribute>() is null)); | |
| 198 | + } | |
| 142 | 199 | |
| 143 | - List<Type> types = new List<Type>(); | |
| 144 | - foreach (var module in moduleContainer.Modules) | |
| 200 | + var databaseName = ExtractDatabaseName(tenant.TenantConnectionString); | |
| 201 | + if (string.IsNullOrWhiteSpace(databaseName) || !SafeDatabaseNameRegex.IsMatch(databaseName)) | |
| 202 | + { | |
| 203 | + throw new UserFriendlyException("租户连接串中的数据库名无效,无法建库"); | |
| 204 | + } | |
| 205 | + | |
| 206 | + // 建库连接候选(按优先级,互不相同才尝试下一条): | |
| 207 | + // 1) AdminConnectionString 高权限(可选) | |
| 208 | + // 2) 主库 Url(带 database=host,RDS 上多数账号必须先进入已授权库才能执行 CREATE) | |
| 209 | + // 3) 无 database= 的实例级连接(与部分 Navicat 用法一致) | |
| 210 | + var createCandidates = new List<(string Label, string ConnectionString)>(); | |
| 211 | + void AddCandidate(string label, string? conn) | |
| 212 | + { | |
| 213 | + if (string.IsNullOrWhiteSpace(conn)) | |
| 145 | 214 | { |
| 146 | - types.AddRange(module.Assembly.GetTypes() | |
| 147 | - .Where(x => x.GetCustomAttribute<IgnoreCodeFirstAttribute>() == null) | |
| 148 | - .Where(x => x.GetCustomAttribute<SugarTable>() != null) | |
| 149 | - .Where(x => x.GetCustomAttribute<DefaultTenantTableAttribute>() is null) | |
| 150 | - .Where(x => x.GetCustomAttribute<SplitTableAttribute>() is null)); | |
| 215 | + return; | |
| 151 | 216 | } |
| 152 | 217 | |
| 153 | - if (types.Count > 0) | |
| 218 | + if (createCandidates.Any(x => | |
| 219 | + string.Equals(x.ConnectionString, conn, StringComparison.OrdinalIgnoreCase))) | |
| 154 | 220 | { |
| 155 | - db.CodeFirst.InitTables(types.ToArray()); | |
| 221 | + return; | |
| 156 | 222 | } |
| 157 | 223 | |
| 158 | - await uow.CompleteAsync(); | |
| 224 | + createCandidates.Add((label, conn)); | |
| 159 | 225 | } |
| 226 | + | |
| 227 | + AddCandidate("AdminConnectionString", _dbConnOptions.AdminConnectionString); | |
| 228 | + AddCandidate("DbConnOptions.Url(主库)", _dbConnOptions.Url); | |
| 229 | + AddCandidate( | |
| 230 | + "实例级(无database)", | |
| 231 | + BuildServerLevelConnectionString( | |
| 232 | + !string.IsNullOrWhiteSpace(_dbConnOptions.Url) | |
| 233 | + ? _dbConnOptions.Url! | |
| 234 | + : tenant.TenantConnectionString)); | |
| 235 | + | |
| 236 | + if (createCandidates.Count == 0) | |
| 237 | + { | |
| 238 | + throw new UserFriendlyException("未配置可用的数据库连接串,无法创建租户库"); | |
| 239 | + } | |
| 240 | + | |
| 241 | + var externalServices = new ConfigureExternalServices | |
| 242 | + { | |
| 243 | + EntityNameService = (type, entity) => | |
| 244 | + { | |
| 245 | + if (_dbConnOptions.EnableUnderLine && !entity.DbTableName.Contains('_')) | |
| 246 | + { | |
| 247 | + entity.DbTableName = UtilMethods.ToUnderLine(entity.DbTableName); | |
| 248 | + } | |
| 249 | + }, | |
| 250 | + EntityService = (propertyInfo, columnInfo) => | |
| 251 | + { | |
| 252 | + // 与 SqlSugarDbContextFactory 一致:可空引用类型映射为可空列,避免 Seed 插入 null 失败 | |
| 253 | + if (new NullabilityInfoContext().Create(propertyInfo).WriteState | |
| 254 | + is NullabilityState.Nullable) | |
| 255 | + { | |
| 256 | + columnInfo.IsNullable = true; | |
| 257 | + } | |
| 258 | + | |
| 259 | + if (_dbConnOptions.EnableUnderLine && !columnInfo.IsIgnore | |
| 260 | + && !columnInfo.DbColumnName.Contains('_')) | |
| 261 | + { | |
| 262 | + columnInfo.DbColumnName = UtilMethods.ToUnderLine(columnInfo.DbColumnName); | |
| 263 | + } | |
| 264 | + } | |
| 265 | + }; | |
| 266 | + | |
| 267 | + // 1) CREATE DATABASE:依次尝试候选连接 | |
| 268 | + var createErrors = new List<string>(); | |
| 269 | + string? privilegedConnectionString = null; | |
| 270 | + foreach (var candidate in createCandidates) | |
| 271 | + { | |
| 272 | + try | |
| 273 | + { | |
| 274 | + ExecuteCreateDatabase(tenant.DbType, candidate.ConnectionString, databaseName); | |
| 275 | + privilegedConnectionString = candidate.ConnectionString; | |
| 276 | + break; | |
| 277 | + } | |
| 278 | + catch (Exception ex) | |
| 279 | + { | |
| 280 | + createErrors.Add($"{candidate.Label}: {GetRootMessage(ex)}"); | |
| 281 | + } | |
| 282 | + } | |
| 283 | + | |
| 284 | + if (privilegedConnectionString == null) | |
| 285 | + { | |
| 286 | + var userId = ExtractConnectionValue(tenant.TenantConnectionString, "uid") ?? "netteam"; | |
| 287 | + throw new UserFriendlyException( | |
| 288 | + $"创建租户库失败(库={databaseName})。尝试结果:{string.Join(" | ", createErrors)}。" + | |
| 289 | + $"说明:MySQL 报 Access denied to database 新建库名时,通常是账号没有 CREATE 权限(与能否连上主库无关)。" + | |
| 290 | + $"请在 appsettings 的 DbConnOptions.AdminConnectionString 配置高权限账号连接串后重试;或手动执行:" + | |
| 291 | + $"CREATE DATABASE IF NOT EXISTS `{databaseName}` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; " + | |
| 292 | + $"GRANT ALL PRIVILEGES ON `{databaseName}`.* TO '{userId}'@'%'; " + | |
| 293 | + $"再 PUT /api/app/tenant/init/{tenant.Id}"); | |
| 294 | + } | |
| 295 | + | |
| 296 | + // 2) 把业务账号(TenantConnectionString 的 uid,如 netteam)授权到新库 | |
| 297 | + // 建库常用高权限账号(Admin / javateam),否则业务账号无 CREATE TABLE 权限 | |
| 298 | + var grantWarnings = TryGrantTenantDatabaseAccess( | |
| 299 | + tenant.DbType, | |
| 300 | + privilegedConnectionString, | |
| 301 | + databaseName, | |
| 302 | + tenant.TenantConnectionString); | |
| 303 | + | |
| 304 | + // 3) 建表:优先业务连接串;失败则用建库成功的高权限连接串切到目标库再建表 | |
| 305 | + try | |
| 306 | + { | |
| 307 | + InitTenantTables( | |
| 308 | + tenant.Id, | |
| 309 | + tenant.DbType, | |
| 310 | + tenant.TenantConnectionString, | |
| 311 | + types, | |
| 312 | + externalServices); | |
| 313 | + } | |
| 314 | + catch (Exception tenantConnEx) | |
| 315 | + { | |
| 316 | + var adminTenantConn = ReplaceConnectionDatabase(privilegedConnectionString, databaseName); | |
| 317 | + try | |
| 318 | + { | |
| 319 | + InitTenantTables( | |
| 320 | + tenant.Id, | |
| 321 | + tenant.DbType, | |
| 322 | + adminTenantConn, | |
| 323 | + types, | |
| 324 | + externalServices); | |
| 325 | + } | |
| 326 | + catch (Exception adminConnEx) | |
| 327 | + { | |
| 328 | + var userId = ExtractConnectionValue(tenant.TenantConnectionString, "uid") ?? "netteam"; | |
| 329 | + throw new UserFriendlyException( | |
| 330 | + $"租户库 `{databaseName}` 已存在,但建表失败。" + | |
| 331 | + $"业务账号建表:{GetRootMessage(tenantConnEx)};" + | |
| 332 | + $"高权限建表:{GetRootMessage(adminConnEx)}。" + | |
| 333 | + (string.IsNullOrEmpty(grantWarnings) ? "" : $"授权提示:{grantWarnings}。") + | |
| 334 | + $"请手动执行 GRANT ALL PRIVILEGES ON `{databaseName}`.* TO '{userId}'@'%'; 后 " + | |
| 335 | + $"PUT /api/app/tenant/init/{tenant.Id}"); | |
| 336 | + } | |
| 337 | + } | |
| 338 | + | |
| 339 | + await Task.CompletedTask; | |
| 340 | + } | |
| 341 | + | |
| 342 | + private static readonly Regex SafeDatabaseNameRegex = | |
| 343 | + new(@"^[a-zA-Z0-9][a-zA-Z0-9_\-]{0,63}$", RegexOptions.Compiled); | |
| 344 | + | |
| 345 | + private static string GetRootMessage(Exception ex) | |
| 346 | + { | |
| 347 | + var current = ex; | |
| 348 | + while (current.InnerException != null) | |
| 349 | + { | |
| 350 | + current = current.InnerException; | |
| 351 | + } | |
| 352 | + | |
| 353 | + return current.Message; | |
| 354 | + } | |
| 355 | + | |
| 356 | + /// <summary> | |
| 357 | + /// 去掉 database=,使连接为「实例级」,便于执行 CREATE DATABASE(与 Navicat 无默认库一致)。 | |
| 358 | + /// </summary> | |
| 359 | + private static string BuildServerLevelConnectionString(string connectionString) | |
| 360 | + { | |
| 361 | + var segments = connectionString | |
| 362 | + .Split(';', StringSplitOptions.RemoveEmptyEntries) | |
| 363 | + .Select(x => x.Trim()) | |
| 364 | + .Where(x => !x.StartsWith("database=", StringComparison.OrdinalIgnoreCase) | |
| 365 | + && !x.StartsWith("initial catalog=", StringComparison.OrdinalIgnoreCase)) | |
| 366 | + .ToList(); | |
| 367 | + return string.Join(';', segments) + ";"; | |
| 368 | + } | |
| 369 | + | |
| 370 | + private static void ExecuteCreateDatabase(DbType dbType, string connectionString, string databaseName) | |
| 371 | + { | |
| 372 | + using var createDb = new SqlSugarClient(new ConnectionConfig | |
| 373 | + { | |
| 374 | + ConfigId = $"tenant-create-db-{databaseName}-{Guid.NewGuid():N}", | |
| 375 | + DbType = dbType, | |
| 376 | + ConnectionString = connectionString, | |
| 377 | + IsAutoCloseConnection = true | |
| 378 | + }); | |
| 379 | + | |
| 380 | + createDb.Ado.ExecuteCommand( | |
| 381 | + $"CREATE DATABASE IF NOT EXISTS `{databaseName}` " + | |
| 382 | + "DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"); | |
| 383 | + } | |
| 384 | + | |
| 385 | + /// <summary> | |
| 386 | + /// 授权业务账号访问新租户库;失败不抛(返回警告,后续可用高权限建表)。 | |
| 387 | + /// </summary> | |
| 388 | + private static string TryGrantTenantDatabaseAccess( | |
| 389 | + DbType dbType, | |
| 390 | + string privilegedConnectionString, | |
| 391 | + string databaseName, | |
| 392 | + string tenantConnectionString) | |
| 393 | + { | |
| 394 | + var appUserId = ExtractConnectionValue(tenantConnectionString, "uid"); | |
| 395 | + var privilegedUserId = ExtractConnectionValue(privilegedConnectionString, "uid"); | |
| 396 | + if (string.IsNullOrWhiteSpace(appUserId)) | |
| 397 | + { | |
| 398 | + return "租户连接串缺少 uid,跳过 GRANT"; | |
| 399 | + } | |
| 400 | + | |
| 401 | + // 建库账号与业务账号相同,通常无需再 GRANT | |
| 402 | + if (string.Equals(appUserId, privilegedUserId, StringComparison.OrdinalIgnoreCase)) | |
| 403 | + { | |
| 404 | + return string.Empty; | |
| 405 | + } | |
| 406 | + | |
| 407 | + try | |
| 408 | + { | |
| 409 | + using var grantDb = new SqlSugarClient(new ConnectionConfig | |
| 410 | + { | |
| 411 | + ConfigId = $"tenant-grant-{databaseName}-{Guid.NewGuid():N}", | |
| 412 | + DbType = dbType, | |
| 413 | + ConnectionString = privilegedConnectionString, | |
| 414 | + IsAutoCloseConnection = true | |
| 415 | + }); | |
| 416 | + | |
| 417 | + // 阿里云 RDS:对业务账号授权新库全部权限 | |
| 418 | + grantDb.Ado.ExecuteCommand( | |
| 419 | + $"GRANT ALL PRIVILEGES ON `{databaseName}`.* TO '{EscapeSqlLiteral(appUserId)}'@'%'"); | |
| 420 | + return string.Empty; | |
| 421 | + } | |
| 422 | + catch (Exception ex) | |
| 423 | + { | |
| 424 | + return GetRootMessage(ex); | |
| 425 | + } | |
| 426 | + } | |
| 427 | + | |
| 428 | + private static void InitTenantTables( | |
| 429 | + Guid tenantId, | |
| 430 | + DbType dbType, | |
| 431 | + string connectionString, | |
| 432 | + List<Type> types, | |
| 433 | + ConfigureExternalServices externalServices) | |
| 434 | + { | |
| 435 | + using var db = new SqlSugarClient(new ConnectionConfig | |
| 436 | + { | |
| 437 | + ConfigId = $"tenant-init-tables-{tenantId}-{Guid.NewGuid():N}", | |
| 438 | + DbType = dbType, | |
| 439 | + ConnectionString = connectionString, | |
| 440 | + IsAutoCloseConnection = true, | |
| 441 | + ConfigureExternalServices = externalServices | |
| 442 | + }); | |
| 443 | + | |
| 444 | + db.Ado.ExecuteCommand("SELECT 1"); | |
| 445 | + | |
| 446 | + // 历史误用精简 DbModel(如 RoleDbEntity)建出的残缺表,InitTables 不会补列,需先删再重建 | |
| 447 | + DropIncompleteRbacTablesIfNeeded(db); | |
| 448 | + | |
| 449 | + if (types.Count > 0) | |
| 450 | + { | |
| 451 | + db.CodeFirst.InitTables(types.ToArray()); | |
| 452 | + } | |
| 453 | + } | |
| 454 | + | |
| 455 | + /// <summary> | |
| 456 | + /// 若 Role 等表缺少 CreationTime,说明曾被精简映射建坏,删除后由完整实体重建。 | |
| 457 | + /// </summary> | |
| 458 | + private static void DropIncompleteRbacTablesIfNeeded(ISqlSugarClient db) | |
| 459 | + { | |
| 460 | + foreach (var tableName in new[] { "Role", "role", "RoleMenu", "rolemenu", "Menu", "menu" }) | |
| 461 | + { | |
| 462 | + if (!db.DbMaintenance.IsAnyTable(tableName, false)) | |
| 463 | + { | |
| 464 | + continue; | |
| 465 | + } | |
| 466 | + | |
| 467 | + var columns = db.DbMaintenance.GetColumnInfosByTableName(tableName, false); | |
| 468 | + var hasCreationTime = columns.Any(c => | |
| 469 | + string.Equals(c.DbColumnName, "CreationTime", StringComparison.OrdinalIgnoreCase)); | |
| 470 | + | |
| 471 | + // Role 精简模型只有 Id/IsDeleted/RoleCode/RoleName,缺 CreationTime | |
| 472 | + if (string.Equals(tableName, "Role", StringComparison.OrdinalIgnoreCase) && !hasCreationTime) | |
| 473 | + { | |
| 474 | + db.DbMaintenance.DropTable(tableName); | |
| 475 | + continue; | |
| 476 | + } | |
| 477 | + | |
| 478 | + // RoleMenu 精简模型无业务外键类型问题较少,但若列过少也重建 | |
| 479 | + if (string.Equals(tableName, "RoleMenu", StringComparison.OrdinalIgnoreCase) | |
| 480 | + && columns.Count < 3) | |
| 481 | + { | |
| 482 | + db.DbMaintenance.DropTable(tableName); | |
| 483 | + } | |
| 484 | + } | |
| 485 | + } | |
| 486 | + | |
| 487 | + private static string EscapeSqlLiteral(string value) | |
| 488 | + => value.Replace("'", "''", StringComparison.Ordinal); | |
| 489 | + | |
| 490 | + private static string? ExtractDatabaseName(string connectionString) | |
| 491 | + => ExtractConnectionValue(connectionString, "database"); | |
| 492 | + | |
| 493 | + private static string? ExtractConnectionValue(string connectionString, string key) | |
| 494 | + { | |
| 495 | + if (string.IsNullOrWhiteSpace(connectionString)) | |
| 496 | + { | |
| 497 | + return null; | |
| 498 | + } | |
| 499 | + | |
| 500 | + var prefix = key + "="; | |
| 501 | + foreach (var segment in connectionString.Split(';', StringSplitOptions.RemoveEmptyEntries)) | |
| 502 | + { | |
| 503 | + var part = segment.Trim(); | |
| 504 | + if (part.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) | |
| 505 | + { | |
| 506 | + return part[prefix.Length..].Trim(); | |
| 507 | + } | |
| 508 | + } | |
| 509 | + | |
| 510 | + return null; | |
| 511 | + } | |
| 512 | + | |
| 513 | + private static string ReplaceConnectionDatabase(string connectionString, string databaseName) | |
| 514 | + { | |
| 515 | + var segments = connectionString | |
| 516 | + .Split(';', StringSplitOptions.RemoveEmptyEntries) | |
| 517 | + .Select(x => x.Trim()) | |
| 518 | + .Where(x => !x.StartsWith("database=", StringComparison.OrdinalIgnoreCase) | |
| 519 | + && !x.StartsWith("initial catalog=", StringComparison.OrdinalIgnoreCase)) | |
| 520 | + .ToList(); | |
| 521 | + segments.Add($"database={databaseName}"); | |
| 522 | + return string.Join(';', segments) + ";"; | |
| 160 | 523 | } |
| 161 | 524 | } |
| 162 | -} | |
| 163 | 525 | \ No newline at end of file |
| 526 | +} | ... | ... |
泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/tenant-management/Yi.Framework.TenantManagement.Domain/SqlSugarAndConfigurationTenantStore.cs
| ... | ... | @@ -108,7 +108,12 @@ namespace Yi.Framework.TenantManagement.Domain |
| 108 | 108 | { |
| 109 | 109 | var tenantConfiguration = tenant != null ? MapToConfiguration(tenant) : null; |
| 110 | 110 | var cacheItem = new TenantCacheItem(tenantConfiguration); |
| 111 | - await Cache.SetAsync(cacheKey, cacheItem, considerUow: true); | |
| 111 | + // 未命中不写入缓存,避免同请求 UoW 内复用 null 结果(如 Create 尚未提交时 Init 查询) | |
| 112 | + if (tenant != null) | |
| 113 | + { | |
| 114 | + await Cache.SetAsync(cacheKey, cacheItem, considerUow: true); | |
| 115 | + } | |
| 116 | + | |
| 112 | 117 | return cacheItem; |
| 113 | 118 | } |
| 114 | 119 | ... | ... |
泰额版/Food Labeling Management Code/Yi.Abp.Net8/src/Yi.Abp.Web/YiAbpWebModule.cs
| ... | ... | @@ -8,6 +8,7 @@ using Hangfire.MemoryStorage; |
| 8 | 8 | using Hangfire.Redis.StackExchange; |
| 9 | 9 | using Microsoft.AspNetCore.Authentication.JwtBearer; |
| 10 | 10 | using Microsoft.AspNetCore.Cors; |
| 11 | +using Microsoft.AspNetCore.Http.Timeouts; | |
| 11 | 12 | using Microsoft.AspNetCore.Mvc; |
| 12 | 13 | using Microsoft.AspNetCore.StaticFiles; |
| 13 | 14 | using Microsoft.IdentityModel.Tokens; |
| ... | ... | @@ -227,6 +228,12 @@ namespace Yi.Abp.Web |
| 227 | 228 | } |
| 228 | 229 | }); |
| 229 | 230 | |
| 231 | + // 租户业务库同步初始化(PUT tenant/init、initialize-tenant-database)允许较长耗时 | |
| 232 | + service.AddRequestTimeouts(options => | |
| 233 | + { | |
| 234 | + options.AddPolicy("ThTenantDatabaseInit", TimeSpan.FromMinutes(10)); | |
| 235 | + }); | |
| 236 | + | |
| 230 | 237 | //速率限制 |
| 231 | 238 | //每60秒限制100个请求,滑块添加,分6段 |
| 232 | 239 | service.AddRateLimiter(_ => |
| ... | ... | @@ -355,6 +362,8 @@ namespace Yi.Abp.Web |
| 355 | 362 | |
| 356 | 363 | app.UseRouting(); |
| 357 | 364 | |
| 365 | + app.UseRequestTimeouts(); | |
| 366 | + | |
| 358 | 367 | //跨域 |
| 359 | 368 | app.UseCors(DefaultCorsPolicyName); |
| 360 | 369 | ... | ... |
泰额版/Food Labeling Management Code/Yi.Abp.Net8/src/Yi.Abp.Web/appsettings.json
| ... | ... | @@ -21,7 +21,7 @@ |
| 21 | 21 | //应用启动:SelfUrl 供 Program.cs UseUrls 绑定;用 0.0.0.0 避免写成固定局域网 IP 在本机无该网卡时启动失败(WinError 10049) |
| 22 | 22 | "App": { |
| 23 | 23 | "SelfUrl": "http://192.168.31.87:19002", |
| 24 | - "CorsOrigins": "http://localhost:19002;http://localhost:18000;http://localhost:5666;http://localhost:5173;http://localhost:3000;http://127.0.0.1:19002" | |
| 24 | + "CorsOrigins": "http://localhost:19002;http://localhost:18000;http://localhost:5666;http://localhost:5173;http://localhost:5174;http://localhost:3000;http://127.0.0.1:19002" | |
| 25 | 25 | }, |
| 26 | 26 | //配置 |
| 27 | 27 | "Settings": { |
| ... | ... | @@ -57,6 +57,9 @@ |
| 57 | 57 | "MaxImportRows": 5000, |
| 58 | 58 | "MaxUploadBytes": 10485760, |
| 59 | 59 | "MaxBulkUpdateItems": 500 |
| 60 | + }, | |
| 61 | + "TenantSelectCrypto": { | |
| 62 | + "SecretKey": "FoodLabelingThTenantSelect2026Key!" | |
| 60 | 63 | } |
| 61 | 64 | }, |
| 62 | 65 | |
| ... | ... | @@ -64,7 +67,9 @@ |
| 64 | 67 | "DbList": [ "Sqlite", "Mysql", "Sqlserver", "Oracle", "PostgreSQL" ], |
| 65 | 68 | |
| 66 | 69 | "DbConnOptions": { |
| 67 | - "Url": "server=rm-bp19ohrgc6111ynzh1o.mysql.rds.aliyuncs.com;port=3306;database=antis-foodlabeling-host;uid=netteam;pwd=netteam;CharSet=utf8mb4;", | |
| 70 | + "Url": "server=rm-bp19ohrgc6111ynzh1o.mysql.rds.aliyuncs.com;port=3306;database=antis-foodlabeling-host;uid=javateam;pwd=javateam2026;CharSet=utf8mb4;", | |
| 71 | + // 高权限:仅建库/授权;租户连接串仍用 FoodLabeling:TenantDatabase 的 netteam | |
| 72 | + "AdminConnectionString": "server=rm-bp19ohrgc6111ynzh1o.mysql.rds.aliyuncs.com;port=3306;database=antis-foodlabeling-host;uid=javateam;pwd=javateam2026;CharSet=utf8mb4;", | |
| 68 | 73 | "DbType": "MySql", |
| 69 | 74 | "EnabledReadWrite": false, |
| 70 | 75 | "EnabledCodeFirst": false, | ... | ... |
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/AllScopeBindingHelper.cs
| ... | ... | @@ -110,6 +110,14 @@ public static class AllScopeBindingHelper |
| 110 | 110 | bool hasArrayInPayload) |
| 111 | 111 | { |
| 112 | 112 | var ids = LabelEntityPartnerScopeHelper.NormalizePartnerIds(partnerIds, companyIds); |
| 113 | + | |
| 114 | + // 显式 SPECIFIED 时保留指定 Company 落库,不因「全选当前全部 Company」而归档为 ALL(与 Location 维度一致)。 | |
| 115 | + if (string.Equals(declaredType?.Trim(), ScopeSpecified, StringComparison.OrdinalIgnoreCase) | |
| 116 | + && ids.Count > 0) | |
| 117 | + { | |
| 118 | + return (ScopeSpecified, ids); | |
| 119 | + } | |
| 120 | + | |
| 113 | 121 | var allPartners = await ResolveAllPartnerIdsAsync(db); |
| 114 | 122 | var isFull = ids.Count > 0 && IsFullIdSelection(ids, allPartners); |
| 115 | 123 | var type = ResolveDimensionType(declaredType, ids, hasArrayInPayload, isFull); |
| ... | ... | @@ -173,6 +181,12 @@ public static class AllScopeBindingHelper |
| 173 | 181 | return true; |
| 174 | 182 | } |
| 175 | 183 | |
| 184 | + // 显式 SPECIFIED 时保留指定范围落库,不因「全选当前 Company 下门店」而归档为 ALL。 | |
| 185 | + if (string.Equals(declaredAvailabilityType?.Trim(), ScopeSpecified, StringComparison.OrdinalIgnoreCase)) | |
| 186 | + { | |
| 187 | + return false; | |
| 188 | + } | |
| 189 | + | |
| 176 | 190 | var merged = await LocationScopeBindingHelper.MergeToLocationIdsAsync( |
| 177 | 191 | db, |
| 178 | 192 | (IReadOnlyList<string>?)null, | ... | ... |
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/LabelEntityPartnerScopeHelper.cs
| ... | ... | @@ -259,10 +259,42 @@ public static class LabelEntityPartnerScopeHelper |
| 259 | 259 | var hasTable = HasPartnerTableForKind(schema, kind); |
| 260 | 260 | var hasColumn = HasPartnerColumnForKind(schema, kind); |
| 261 | 261 | |
| 262 | + // 主表 AppliedPartnerType 列已迁移但静态缓存未感知关联表时(常见于迁移后首访 GET),刷新后再读。 | |
| 263 | + if (!hasTable && hasColumn) | |
| 264 | + { | |
| 265 | + schema = await RefreshSchemaCacheAsync(db); | |
| 266 | + hasTable = HasPartnerTableForKind(schema, kind); | |
| 267 | + hasColumn = HasPartnerColumnForKind(schema, kind); | |
| 268 | + } | |
| 269 | + | |
| 262 | 270 | var partnerLinks = hasTable |
| 263 | 271 | ? await LoadPartnerLinksAsync(db, kind, ids) |
| 264 | 272 | : new List<(string EntityId, string PartnerId)>(); |
| 265 | 273 | |
| 274 | + if (partnerLinks.Count == 0 && hasColumn) | |
| 275 | + { | |
| 276 | + var hasSpecifiedWithoutLinks = false; | |
| 277 | + foreach (var entityId in ids) | |
| 278 | + { | |
| 279 | + var storedType = await GetAppliedPartnerTypeAsync(db, kind, entityId); | |
| 280 | + if (string.Equals(storedType, ScopeSpecified, StringComparison.OrdinalIgnoreCase)) | |
| 281 | + { | |
| 282 | + hasSpecifiedWithoutLinks = true; | |
| 283 | + break; | |
| 284 | + } | |
| 285 | + } | |
| 286 | + | |
| 287 | + if (hasSpecifiedWithoutLinks && !hasTable) | |
| 288 | + { | |
| 289 | + schema = await RefreshSchemaCacheAsync(db); | |
| 290 | + hasTable = HasPartnerTableForKind(schema, kind); | |
| 291 | + if (hasTable) | |
| 292 | + { | |
| 293 | + partnerLinks = await LoadPartnerLinksAsync(db, kind, ids); | |
| 294 | + } | |
| 295 | + } | |
| 296 | + } | |
| 297 | + | |
| 266 | 298 | var partnerIdSet = partnerLinks.Select(x => x.PartnerId).Distinct(StringComparer.Ordinal).ToList(); |
| 267 | 299 | var partnerNameById = await LoadPartnerNameMapAsync(db, partnerIdSet); |
| 268 | 300 | |
| ... | ... | @@ -439,31 +471,13 @@ public static class LabelEntityPartnerScopeHelper |
| 439 | 471 | } |
| 440 | 472 | |
| 441 | 473 | /// <summary> |
| 442 | - /// 由 Query partnerId 或可见门店范围解析列表 Company 筛选 Id;均未限时返回 <c>null</c>。 | |
| 474 | + /// 由 Query <c>partnerId</c> 解析列表 Company 筛选 Id;未传则返回 <c>null</c>(Region/Location 筛选由门店范围单独处理)。 | |
| 443 | 475 | /// </summary> |
| 444 | - public static async Task<List<string>?> ResolveListPartnerIdsAsync( | |
| 476 | + public static Task<List<string>?> ResolveListPartnerIdsAsync( | |
| 445 | 477 | ISqlSugarClient db, |
| 446 | 478 | string? partnerId, |
| 447 | - List<string>? scopedLocationIds) | |
| 448 | - { | |
| 449 | - var fromQuery = await ResolveScopedPartnerIdsForListAsync(db, partnerId); | |
| 450 | - if (fromQuery is not null) | |
| 451 | - { | |
| 452 | - return fromQuery; | |
| 453 | - } | |
| 454 | - | |
| 455 | - if (scopedLocationIds is null) | |
| 456 | - { | |
| 457 | - return null; | |
| 458 | - } | |
| 459 | - | |
| 460 | - if (scopedLocationIds.Count == 0) | |
| 461 | - { | |
| 462 | - return new List<string>(); | |
| 463 | - } | |
| 464 | - | |
| 465 | - return await LocationScopeBindingHelper.ResolvePartnerIdsFromLocationIdsAsync(db, scopedLocationIds); | |
| 466 | - } | |
| 479 | + List<string>? scopedLocationIds) => | |
| 480 | + ResolveScopedPartnerIdsForListAsync(db, partnerId); | |
| 467 | 481 | |
| 468 | 482 | /// <summary>单元测试或切换库后调用。</summary> |
| 469 | 483 | public static void ResetSchemaCacheForTests() => _cachedSchema = null; | ... | ... |
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/LocationScopeBindingHelper.cs
| ... | ... | @@ -215,37 +215,22 @@ public static class LocationScopeBindingHelper |
| 215 | 215 | return exists ? new List<string> { locId } : new List<string>(); |
| 216 | 216 | } |
| 217 | 217 | |
| 218 | - var gid = groupId?.Trim(); | |
| 218 | + var groupIds = ParseScopeIdsFromQuery(groupId); | |
| 219 | 219 | var pid = partnerId?.Trim(); |
| 220 | 220 | |
| 221 | - if (string.IsNullOrWhiteSpace(pid) && string.IsNullOrWhiteSpace(gid)) | |
| 221 | + if (string.IsNullOrWhiteSpace(pid) && groupIds.Count == 0) | |
| 222 | 222 | { |
| 223 | 223 | return null; |
| 224 | 224 | } |
| 225 | 225 | |
| 226 | - var q = db.Queryable<LocationAggregateRoot>().Where(x => !x.IsDeleted); | |
| 227 | - | |
| 228 | - if (!string.IsNullOrWhiteSpace(gid)) | |
| 226 | + if (groupIds.Count > 0) | |
| 229 | 227 | { |
| 230 | - var g = await db.Queryable<FlGroupDbEntity>() | |
| 231 | - .FirstAsync(x => !x.IsDeleted && x.Id == gid); | |
| 232 | - if (g is null) | |
| 233 | - { | |
| 234 | - return new List<string>(); | |
| 235 | - } | |
| 228 | + return await ResolveLocationIdsFromGroupIdsAsync(db, groupIds); | |
| 229 | + } | |
| 236 | 230 | |
| 237 | - var gName = g.GroupName?.Trim() ?? string.Empty; | |
| 238 | - var partner = await db.Queryable<FlPartnerDbEntity>() | |
| 239 | - .FirstAsync(x => !x.IsDeleted && x.Id == g.PartnerId); | |
| 240 | - if (partner is null) | |
| 241 | - { | |
| 242 | - return new List<string>(); | |
| 243 | - } | |
| 231 | + var q = db.Queryable<LocationAggregateRoot>().Where(x => !x.IsDeleted); | |
| 244 | 232 | |
| 245 | - var pName = partner.PartnerName?.Trim() ?? string.Empty; | |
| 246 | - q = q.Where(x => x.GroupName == gName && x.Partner == pName); | |
| 247 | - } | |
| 248 | - else if (!string.IsNullOrWhiteSpace(pid)) | |
| 233 | + if (!string.IsNullOrWhiteSpace(pid)) | |
| 249 | 234 | { |
| 250 | 235 | var partner = await db.Queryable<FlPartnerDbEntity>() |
| 251 | 236 | .FirstAsync(x => !x.IsDeleted && x.Id == pid); |
| ... | ... | @@ -282,13 +267,13 @@ public static class LocationScopeBindingHelper |
| 282 | 267 | return exists ? new List<string> { locId } : new List<string>(); |
| 283 | 268 | } |
| 284 | 269 | |
| 285 | - var gid = groupId?.Trim(); | |
| 286 | - if (string.IsNullOrWhiteSpace(gid)) | |
| 270 | + var groupIds = ParseScopeIdsFromQuery(groupId); | |
| 271 | + if (groupIds.Count == 0) | |
| 287 | 272 | { |
| 288 | 273 | return null; |
| 289 | 274 | } |
| 290 | 275 | |
| 291 | - return await ResolveLocationIdsFromGroupIdsAsync(db, new List<string> { gid }); | |
| 276 | + return await ResolveLocationIdsFromGroupIdsAsync(db, groupIds); | |
| 292 | 277 | } |
| 293 | 278 | |
| 294 | 279 | /// <summary> |
| ... | ... | @@ -640,6 +625,20 @@ public static class LocationScopeBindingHelper |
| 640 | 625 | } |
| 641 | 626 | |
| 642 | 627 | /// <summary> |
| 628 | + /// 解析 Query 中的 Id 参数(支持逗号分隔多值,如多个 Region GroupId)。 | |
| 629 | + /// </summary> | |
| 630 | + public static List<string> ParseScopeIdsFromQuery(string? raw) | |
| 631 | + { | |
| 632 | + if (string.IsNullOrWhiteSpace(raw)) | |
| 633 | + { | |
| 634 | + return new List<string>(); | |
| 635 | + } | |
| 636 | + | |
| 637 | + var parts = raw.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); | |
| 638 | + return NormalizeIds(parts); | |
| 639 | + } | |
| 640 | + | |
| 641 | + /// <summary> | |
| 643 | 642 | /// Company Admin 在其绑定 Company 下新建 Region 后,将该 Region 下已有门店追加写入 <c>userlocation</c>(不删除已有绑定)。 |
| 644 | 643 | /// </summary> |
| 645 | 644 | public static async Task TryAutoBindCompanyAdminToNewRegionAsync( | ... | ... |
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/DbModels/MenuDbEntity.cs
| 1 | 1 | using SqlSugar; |
| 2 | +using Yi.Framework.SqlSugarCore.Abstractions; | |
| 2 | 3 | |
| 3 | 4 | namespace FoodLabeling.Application.Services.DbModels; |
| 4 | 5 | |
| 5 | 6 | /// <summary> |
| 6 | 7 | /// menu 表映射(兼容数字/字符串类型的 Id、ParentId) |
| 8 | +/// 禁止参与 CodeFirst,完整表结构由 RBAC MenuAggregateRoot 创建 | |
| 7 | 9 | /// </summary> |
| 10 | +[IgnoreCodeFirst] | |
| 8 | 11 | [SugarTable("menu")] |
| 9 | 12 | public class MenuDbEntity |
| 10 | 13 | { | ... | ... |
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/DbModels/RoleDbEntity.cs
| 1 | 1 | using SqlSugar; |
| 2 | +using Yi.Framework.SqlSugarCore.Abstractions; | |
| 2 | 3 | |
| 3 | 4 | namespace FoodLabeling.Application.Services.DbModels; |
| 4 | 5 | |
| 5 | 6 | /// <summary> |
| 6 | 7 | /// Role 表映射(用于 SqlSugar 直查,避免走仓储 IDataPermission) |
| 8 | +/// 字段不全,禁止参与 CodeFirst,否则会建成缺列的 Role 表导致 Seed 失败 | |
| 7 | 9 | /// </summary> |
| 10 | +[IgnoreCodeFirst] | |
| 8 | 11 | [SugarTable("Role")] |
| 9 | 12 | public class RoleDbEntity |
| 10 | 13 | { | ... | ... |
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/DbModels/RoleMenuDbEntity.cs
| 1 | 1 | using SqlSugar; |
| 2 | +using Yi.Framework.SqlSugarCore.Abstractions; | |
| 2 | 3 | |
| 3 | 4 | namespace FoodLabeling.Application.Services.DbModels; |
| 4 | 5 | |
| 5 | 6 | /// <summary> |
| 6 | 7 | /// rolemenu 表映射(兼容字符串类型 RoleId/MenuId) |
| 8 | +/// 禁止参与 CodeFirst,完整表结构由 RBAC RoleMenuEntity 创建 | |
| 7 | 9 | /// </summary> |
| 10 | +[IgnoreCodeFirst] | |
| 8 | 11 | [SugarTable("rolemenu")] |
| 9 | 12 | public class RoleMenuDbEntity |
| 10 | 13 | { | ... | ... |
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/DbModels/UserLocationDbEntity.cs
| 1 | 1 | using SqlSugar; |
| 2 | +using Yi.Framework.SqlSugarCore.Abstractions; | |
| 2 | 3 | |
| 3 | 4 | namespace FoodLabeling.Application.Services.DbModels; |
| 4 | 5 | |
| 5 | 6 | /// <summary> |
| 6 | 7 | /// userlocation 表映射(成员-门店关联) |
| 8 | +/// 禁止参与 CodeFirst,避免与领域实体建表冲突 | |
| 7 | 9 | /// </summary> |
| 10 | +[IgnoreCodeFirst] | |
| 8 | 11 | [SugarTable("userlocation")] |
| 9 | 12 | public class UserLocationDbEntity |
| 10 | 13 | { | ... | ... |
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelCategoryAppService.cs
| ... | ... | @@ -275,6 +275,7 @@ public class LabelCategoryAppService : ApplicationService, ILabelCategoryAppServ |
| 275 | 275 | State = x.State, |
| 276 | 276 | ButtonAppearance = x.ButtonAppearance, |
| 277 | 277 | AvailabilityType = x.AvailabilityType, |
| 278 | + AppliedPartnerType = x.AppliedPartnerType, | |
| 278 | 279 | OrderNum = x.OrderNum |
| 279 | 280 | }; |
| 280 | 281 | } | ... | ... |
美国版/Food Labeling Management Code/Yi.Abp.Net8/src/Yi.Abp.Web/appsettings.json
| ... | ... | @@ -20,8 +20,8 @@ |
| 20 | 20 | }, |
| 21 | 21 | //应用启动:SelfUrl 供 Program.cs UseUrls 绑定;用 0.0.0.0 避免写成固定局域网 IP 在本机无该网卡时启动失败(WinError 10049) |
| 22 | 22 | "App": { |
| 23 | - "SelfUrl": "http://192.168.31.87:19001", | |
| 24 | - "CorsOrigins": "http://localhost:19001;http://localhost:18000;http://localhost:5666;http://localhost:5174;http://localhost:3000" | |
| 23 | + "SelfUrl": "http://localhost:19001", | |
| 24 | + "CorsOrigins": "http://localhost:19001;http://localhost:18000;http://localhost:5666;http://localhost:5174;http://localhost:5173;http://localhost:3000" | |
| 25 | 25 | }, |
| 26 | 26 | //配置 |
| 27 | 27 | "Settings": { | ... | ... |
项目相关文档/2026-07-16代码优化.md
0 → 100644
| 1 | +# 2026-07-16 泰额版代码优化 | |
| 2 | + | |
| 3 | +本文档说明 **泰额版后端** 当日对 `tenant-select` 出参、默认管理员凭据加密及 Web 登录入参的改造。仅涉及泰额版 `Yi.Abp.Net8`,前端需同步对接。 | |
| 4 | + | |
| 5 | +--- | |
| 6 | + | |
| 7 | +## 一、变更概述 | |
| 8 | + | |
| 9 | +| 项 | 说明 | | |
| 10 | +|----|------| | |
| 11 | +| 接口 | `GET /api/app/th-multi-tenancy/tenant-select` | | |
| 12 | +| 目的 | 登录页展示租户列表时不再暴露租户 Id、数据库连接串;改为返回创建时间与可解密的默认管理员凭据 | | |
| 13 | +| 登录 | `POST /api/app/th-web-auth/login` 支持 `tenantName` 替代 `tenantId` | | |
| 14 | +| 配置 | 新增 `FoodLabeling:TenantSelectCrypto:SecretKey` | | |
| 15 | + | |
| 16 | +--- | |
| 17 | + | |
| 18 | +## 二、tenant-select 出参变更 | |
| 19 | + | |
| 20 | +### 2.1 新旧字段对比 | |
| 21 | + | |
| 22 | +| 旧字段 | 新字段 | 说明 | | |
| 23 | +|--------|--------|------| | |
| 24 | +| `id` | — | **已移除**,不再返回租户 Guid | | |
| 25 | +| `name` | `name` | 保留,租户名称 | | |
| 26 | +| — | `creationTime` | **新增**,租户创建时间(主库 `yitenant`) | | |
| 27 | +| — | `loginAccount` | **新增**,默认管理员账号,固定为 `admin`(与 `UserDataSeed` 一致) | | |
| 28 | +| — | `password` | **新增**,AES-CBC 加密后的 Base64 密文(**非**库内不可逆哈希) | | |
| 29 | +| — | `passwordSalt` | **新增**,AES IV 的 Base64,前端解密时使用 | | |
| 30 | +| `tenantConnectionString` / 连接串相关 | — | **从未在此接口返回**;仍不暴露 | | |
| 31 | + | |
| 32 | +### 2.2 出参示例 | |
| 33 | + | |
| 34 | +```json | |
| 35 | +[ | |
| 36 | + { | |
| 37 | + "name": "Default", | |
| 38 | + "creationTime": "2026-01-15T10:30:00", | |
| 39 | + "loginAccount": "admin", | |
| 40 | + "password": "xK3mP9vL2nQ8wR1sT4uV7yZ0aB5cD6eF8gH9iJ0kL1m=", | |
| 41 | + "passwordSalt": "AbCdEfGhIjKlMnOpQrStUvWxYz0123==" | |
| 42 | + } | |
| 43 | +] | |
| 44 | +``` | |
| 45 | + | |
| 46 | +> 每条记录的 `password` / `passwordSalt` 因随机 IV 而不同;明文来源均为 `RbacOptions.AdminPassword`(当前默认 `123456`)。 | |
| 47 | + | |
| 48 | +--- | |
| 49 | + | |
| 50 | +## 三、密码加盐加密与前端解密 | |
| 51 | + | |
| 52 | +### 3.1 算法约定 | |
| 53 | + | |
| 54 | +| 项 | 值 | | |
| 55 | +|----|-----| | |
| 56 | +| 算法 | AES-256-CBC | | |
| 57 | +| 填充 | PKCS7 | | |
| 58 | +| Key | `SHA256(UTF8(SecretKey))` → 32 字节 | | |
| 59 | +| IV | 每次加密随机 16 字节,Base64 写入 `passwordSalt` | | |
| 60 | +| 密文 | Base64 写入 `password` | | |
| 61 | +| 明文 | `RbacOptions.AdminPassword`(appsettings,与种子管理员一致) | | |
| 62 | + | |
| 63 | +### 3.2 后端配置 | |
| 64 | + | |
| 65 | +`appsettings.json`: | |
| 66 | + | |
| 67 | +```json | |
| 68 | +"FoodLabeling": { | |
| 69 | + "TenantSelectCrypto": { | |
| 70 | + "SecretKey": "FoodLabelingThTenantSelect2026Key!" | |
| 71 | + } | |
| 72 | +} | |
| 73 | +``` | |
| 74 | + | |
| 75 | +- `SecretKey` 为前后端约定的字符串,**不要求**本身为 32 字节;后端用 SHA256 派生 AES-256 密钥。 | |
| 76 | +- 生产环境请更换为足够长度的随机字符串,并与前端构建配置保持一致。 | |
| 77 | + | |
| 78 | +### 3.3 前端解密(CryptoJS 示例) | |
| 79 | + | |
| 80 | +```javascript | |
| 81 | +import CryptoJS from 'crypto-js'; | |
| 82 | + | |
| 83 | +const SECRET_KEY = 'FoodLabelingThTenantSelect2026Key!'; // 与后端 TenantSelectCrypto:SecretKey 一致 | |
| 84 | + | |
| 85 | +function decryptTenantPassword(passwordBase64, passwordSaltBase64) { | |
| 86 | + const key = CryptoJS.SHA256(CryptoJS.enc.Utf8.parse(SECRET_KEY)); | |
| 87 | + const iv = CryptoJS.enc.Base64.parse(passwordSaltBase64); | |
| 88 | + const cipher = CryptoJS.enc.Base64.parse(passwordBase64); | |
| 89 | + | |
| 90 | + const decrypted = CryptoJS.AES.decrypt( | |
| 91 | + { ciphertext: cipher }, | |
| 92 | + key, | |
| 93 | + { iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }, | |
| 94 | + ); | |
| 95 | + | |
| 96 | + return decrypted.toString(CryptoJS.enc.Utf8); | |
| 97 | +} | |
| 98 | +``` | |
| 99 | + | |
| 100 | +### 3.4 前端解密(Web Crypto 伪代码) | |
| 101 | + | |
| 102 | +```javascript | |
| 103 | +async function decryptTenantPassword(passwordBase64, passwordSaltBase64) { | |
| 104 | + const secretKey = 'FoodLabelingThTenantSelect2026Key!'; | |
| 105 | + const keyMaterial = await crypto.subtle.importKey( | |
| 106 | + 'raw', | |
| 107 | + await crypto.subtle.digest('SHA-256', new TextEncoder().encode(secretKey)), | |
| 108 | + { name: 'AES-CBC' }, | |
| 109 | + false, | |
| 110 | + ['decrypt'], | |
| 111 | + ); | |
| 112 | + const iv = Uint8Array.from(atob(passwordSaltBase64), (c) => c.charCodeAt(0)); | |
| 113 | + const cipher = Uint8Array.from(atob(passwordBase64), (c) => c.charCodeAt(0)); | |
| 114 | + const plain = await crypto.subtle.decrypt({ name: 'AES-CBC', iv }, keyMaterial, cipher); | |
| 115 | + return new TextDecoder().decode(plain); | |
| 116 | +} | |
| 117 | +``` | |
| 118 | + | |
| 119 | +### 3.5 安全说明 | |
| 120 | + | |
| 121 | +- 接口为 **匿名可访问**,密文仅降低明文密码在传输/展示中的直接暴露风险,**不能**替代 HTTPS 与生产环境改密策略。 | |
| 122 | +- 解密后的密码仅用于登录表单预填或一键登录;请勿持久化明文密码。 | |
| 123 | + | |
| 124 | +--- | |
| 125 | + | |
| 126 | +## 四、Web 登录:tenantName 替代 tenantId | |
| 127 | + | |
| 128 | +`tenant-select` 不再返回 `id` 后,Web 登录须使用 **租户名称**。 | |
| 129 | + | |
| 130 | +### 4.1 入参变更 | |
| 131 | + | |
| 132 | +| 字段 | 必填 | 说明 | | |
| 133 | +|------|------|------| | |
| 134 | +| `tenantId` | 否 | 与 `tenantName` 二选一 | | |
| 135 | +| `tenantName` | 否 | 与 `tenantId` 二选一,推荐 | | |
| 136 | +| `userName` | 是 | 账号或邮箱;`admin` 或 `admin@example.com` 均可 | | |
| 137 | +| `password` | 是 | 明文密码 | | |
| 138 | + | |
| 139 | +二者均为空时返回:`请指定租户 Id 或租户名称`。 | |
| 140 | + | |
| 141 | +### 4.2 登录示例(curl) | |
| 142 | + | |
| 143 | +```bash | |
| 144 | +curl -X POST "http://127.0.0.1:19002/api/app/th-web-auth/login" \ | |
| 145 | + -H "Content-Type: application/json" \ | |
| 146 | + -d "{\"tenantName\":\"Default\",\"userName\":\"admin\",\"password\":\"123456\"}" | |
| 147 | +``` | |
| 148 | + | |
| 149 | +### 4.3 出参(不变) | |
| 150 | + | |
| 151 | +```json | |
| 152 | +{ | |
| 153 | + "token": "eyJhbGciOiJIUzI1NiIs...", | |
| 154 | + "refreshToken": "...", | |
| 155 | + "tenantId": "11111111-1111-1111-1111-111111111111", | |
| 156 | + "tenantName": "Default" | |
| 157 | +} | |
| 158 | +``` | |
| 159 | + | |
| 160 | +Token 内仍写入真实 `TenantId` Guid;后续业务 API 行为不变。 | |
| 161 | + | |
| 162 | +--- | |
| 163 | + | |
| 164 | +## 五、泰额 App 登录说明 | |
| 165 | + | |
| 166 | +`POST /api/app/th-app-auth/login` **本次未改**,仍要求入参 `tenantId`(Guid)。 | |
| 167 | + | |
| 168 | +若 App 端也需要去掉 tenantId,需单独改造 `ThAppLoginInputVo` 与 `ThAppAuthAppService`,并与移动端联调。 | |
| 169 | + | |
| 170 | +--- | |
| 171 | + | |
| 172 | +## 六、相关接口(当日其它优化,可选) | |
| 173 | + | |
| 174 | +- **开通租户** `POST /api/app/th-tenant-provisioning/provision`:创建租户后可在后台异步初始化业务库(`DatabaseInitializing` / `InitializeTenantDatabase`)。 | |
| 175 | +- **同步初始化** `POST /api/app/th-tenant-provisioning/initialize-tenant-database/{tenantId}`:补跑租户库 CodeFirst + Seed。 | |
| 176 | + | |
| 177 | +与本次 `tenant-select` 改造无直接冲突;平台管理员仍通过 provision 创建租户,登录页通过 `tenant-select` + `tenantName` 登录。 | |
| 178 | + | |
| 179 | +--- | |
| 180 | + | |
| 181 | +## 七、改动文件列表(后端) | |
| 182 | + | |
| 183 | +| 文件 | 变更 | | |
| 184 | +|------|------| | |
| 185 | +| `FoodLabeling.Th.Application.Contracts/Dtos/MultiTenancy/ThTenantSelectDto.cs` | 出参字段调整 | | |
| 186 | +| `FoodLabeling.Th.Application.Contracts/Options/FoodLabelingThTenantSelectCryptoOptions.cs` | 新增加密配置 | | |
| 187 | +| `FoodLabeling.Th.Application/MultiTenancy/TenantSelectCredentialCipher.cs` | AES-CBC 加密 | | |
| 188 | +| `FoodLabeling.Th.Application/MultiTenancy/ThTenantSelectConsts.cs` | 默认 admin 账号常量 | | |
| 189 | +| `FoodLabeling.Th.Application/MultiTenancy/TenantResolveHelper.cs` | 支持 tenantName 解析 | | |
| 190 | +| `FoodLabeling.Th.Application/Services/ThMultiTenancyAppService.cs` | tenant-select 映射与加密 | | |
| 191 | +| `FoodLabeling.Th.Application.Contracts/Dtos/Auth/ThWebLoginInputVo.cs` | TenantId 可选 + TenantName | | |
| 192 | +| `FoodLabeling.Th.Application/Services/ThWebAuthAppService.cs` | 按名称登录 | | |
| 193 | +| `FoodLabeling.Th.Application/FoodLabelingThApplicationModule.cs` | 注册加密配置 | | |
| 194 | +| `src/Yi.Abp.Web/appsettings.json` | TenantSelectCrypto 节点 | | |
| 195 | + | |
| 196 | +--- | |
| 197 | + | |
| 198 | +## 八、前端对接 checklist | |
| 199 | + | |
| 200 | +- [ ] 更新 `ThTenantSelectDto` 类型,移除 `id`,增加 `creationTime` / `loginAccount` / `password` / `passwordSalt` | |
| 201 | +- [ ] 配置与后端一致的 `SecretKey`,解密 `password` 后填入登录表单(若需) | |
| 202 | +- [ ] 登录请求改传 `tenantName: selected.name`,不再依赖 `tenantId` | |
| 203 | +- [ ] 登录成功后仍保存响应中的 `tenantId` 供业务 API / `__tenant` 头使用 | ... | ... |