diff --git a/Admin.NET/Admin.NET.Core/Entity/SysApiInfo.cs b/Admin.NET/Admin.NET.Core/Entity/SysApiInfo.cs new file mode 100644 index 00000000..572b99ee --- /dev/null +++ b/Admin.NET/Admin.NET.Core/Entity/SysApiInfo.cs @@ -0,0 +1,63 @@ +// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。 +// +// 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。 +// +// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任! + +namespace Admin.NET.Core; + +/// +/// 系统接口信息表 +/// +[SysTable] +[SugarTable(null, "系统接口信息表")] +public partial class SysApiInfo : EntityBaseId +{ + /// + /// 组名 + /// + [SugarColumn(ColumnDescription = "组名", Length = 64)] + public string? GroupName { get; set; } + + /// + /// 路由名 + /// + [SugarColumn(ColumnDescription = "路由名", Length = 64)] + public string? Name { get; set; } + + /// + /// 描述 + /// + [SugarColumn(ColumnDescription = "描述", Length = 64)] + public string? Desc { get; set; } + + /// + /// 路由 + /// + [SugarColumn(ColumnDescription = "路由", Length = 64)] + public string Route { get; set; } + + /// + /// 控制器名称 + /// + [SugarColumn(ColumnDescription = "控制器名称", Length = 64)] + public string Action { get; set; } + + /// + /// 请求方式 + /// + [SugarColumn(ColumnDescription = "请求方式", Length = 16)] + public string HttpMethod { get; set; } + + /// + /// 是否移动端接口 + /// + [SugarColumn(ColumnDescription = "是否移动端接口")] + public bool IsAppApi { get; set; } + + /// + /// 排序 + /// + [SugarColumn(ColumnDescription = "排序")] + public int Order { get; set; } = 100; +} \ No newline at end of file diff --git a/Admin.NET/Admin.NET.Core/Entity/VSysPermissions.cs b/Admin.NET/Admin.NET.Core/Entity/VSysPermissions.cs new file mode 100644 index 00000000..8367082d --- /dev/null +++ b/Admin.NET/Admin.NET.Core/Entity/VSysPermissions.cs @@ -0,0 +1,58 @@ +// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。 +// +// 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。 +// +// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任! + +namespace Admin.NET.Core; + +/// +/// 系统权限标识视图 +/// +[SugarTable(null, "系统权限标识视图"), IgnoreTable] +public class VSysPermissions : ISqlSugarView +{ + /// + /// 来自菜单标识 + /// + [SugarColumn(ColumnDescription = "来自菜单标识")] + public long MenuId { get; set; } + + /// + /// 状态 + /// + [SugarColumn(ColumnDescription = "状态")] + public StatusEnum Status { get; set; } + + /// + /// 权限标识 + /// + [SugarColumn(ColumnDescription = "权限标识", IsPrimaryKey = true)] + public string Permission { get; set; } + + /// + /// 视图语句 + /// + public string GetQueryableSqlString(SqlSugarScopeProvider db) + { + return db.Union( + db.Queryable() + .Where(u => u.Type == MenuTypeEnum.Btn && u.Status == StatusEnum.Enable && !string.IsNullOrWhiteSpace(u.Permission)) + .Select(u => new VSysPermissions + { + MenuId = u.Id, + Status = u.Status, + Permission = u.Permission + }), + db.Queryable() + .Where(u => !string.IsNullOrWhiteSpace(u.Route) && SqlFunc.Subqueryable().Where(z => z.Permission == u.Route).NotAny()) + .Select(u => new VSysPermissions + { + MenuId = 0, + Status = StatusEnum.Enable, + Permission = u.Route, + }).Distinct()) + .OrderBy(u => u.Permission) + .ToMappedSqlString(); + } +} \ No newline at end of file diff --git a/Admin.NET/Admin.NET.Core/Entity/VSysUserOrg.cs b/Admin.NET/Admin.NET.Core/Entity/VSysUserOrg.cs new file mode 100644 index 00000000..57da8107 --- /dev/null +++ b/Admin.NET/Admin.NET.Core/Entity/VSysUserOrg.cs @@ -0,0 +1,82 @@ +// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。 +// +// 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。 +// +// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任! + +namespace Admin.NET.Core; + +/// +/// 系统用户机构视图 +/// +[SugarTable(null, "系统用户机构视图"), IgnoreTable] +public class VSysUserOrg : ISqlSugarView +{ + /// + /// 用户Id + /// + [SugarColumn(ColumnDescription = "用户Id")] + public long UserId { get; set; } + + /// + /// 机构Id + /// + [SugarColumn(ColumnDescription = "机构Id")] + public long OrgId { get; set; } + + /// + /// 视图语句 + /// + public string GetQueryableSqlString(SqlSugarScopeProvider db) + { + return db.Union( + // 获取用户表中的机构Id + db.Queryable().IgnoreTenant() + .Select(u => new VSysUserOrg + { + UserId = u.Id, + OrgId = u.OrgId + }), + // 获取用户创建的机构Id + db.Queryable().IgnoreTenant() + .Where(u => u.CreateUserId != null) + .Select(u => new VSysUserOrg + { + UserId = u.CreateUserId.Value, + OrgId = u.Id + }), + // 获取用户扩展机构Id + db.Queryable() + .Select(u => new VSysUserOrg + { + UserId = u.UserId, + OrgId = u.OrgId + }), + // 获取用户角色关联的机构Id + db.Queryable() + .InnerJoin((u, a) => u.RoleId == a.RoleId) + .Select((u, a) => new VSysUserOrg + { + UserId = a.UserId, + OrgId = u.OrgId + }), + // 获取包含全部数据权限的机构Id + db.Queryable().IgnoreTenant() + .FullJoin((u, a) => a.SysRole.DataScope == DataScopeEnum.All) + .Select((u, a) => new VSysUserOrg + { + UserId = a.UserId, + OrgId = u.Id + }), + // 超管获取全部机构Id + db.Queryable().IgnoreTenant() + .FullJoin((u, a) => a.AccountType == AccountTypeEnum.SuperAdmin) + .Select((u, a) => new VSysUserOrg + { + UserId = a.Id, + OrgId = u.Id + })) + .Where(u => u.OrgId != null && u.OrgId != 0) + .ToMappedSqlString(); + } +} \ No newline at end of file diff --git a/Admin.NET/Admin.NET.Core/Enum/ErrorCodeEnum.cs b/Admin.NET/Admin.NET.Core/Enum/ErrorCodeEnum.cs index 66de8ed2..c41bef3a 100644 --- a/Admin.NET/Admin.NET.Core/Enum/ErrorCodeEnum.cs +++ b/Admin.NET/Admin.NET.Core/Enum/ErrorCodeEnum.cs @@ -326,9 +326,9 @@ public enum ErrorCodeEnum D3001, /// - /// 字典类型下面有字典值禁止删除 + /// 字典编码已存在 /// - [ErrorCodeItemMetadata("字典类型下面有字典值禁止删除")] + [ErrorCodeItemMetadata("字典编码已存在")] D3002, /// diff --git a/Admin.NET/Admin.NET.Core/Job/StartHostedService.cs b/Admin.NET/Admin.NET.Core/Job/StartHostedService.cs index 99e334c0..87ffc73e 100644 --- a/Admin.NET/Admin.NET.Core/Job/StartHostedService.cs +++ b/Admin.NET/Admin.NET.Core/Job/StartHostedService.cs @@ -41,6 +41,13 @@ public class StartHostedService(IServiceScopeFactory serviceScopeFactory) : IHos Console.WriteLine(message); Log.Information(message); + // 持久化系统接口数据 + var sysAuthService = serviceScope.ServiceProvider.GetRequiredService(); + await sysAuthService.ResetSysApiInfo(); + message = $"【启动任务】持久化系统接口数据 {DateTime.Now}"; + Console.WriteLine(message); + Log.Information(message); + Console.ForegroundColor = originColor; }, cancellationToken); } diff --git a/Admin.NET/Admin.NET.Core/Logging/DatabaseLoggingWriter.cs b/Admin.NET/Admin.NET.Core/Logging/DatabaseLoggingWriter.cs index 8a30b7b6..8409fe67 100644 --- a/Admin.NET/Admin.NET.Core/Logging/DatabaseLoggingWriter.cs +++ b/Admin.NET/Admin.NET.Core/Logging/DatabaseLoggingWriter.cs @@ -188,7 +188,7 @@ public class DatabaseLoggingWriter : IDatabaseLoggingWriter, IDisposable /// private LoggingUserInfo GetUserInfo(LoggingMonitorDto loggingMonitor) { - var userManger = LazyHelper.GetService(); + var userManger = LazyHelper.GetService().Value; LoggingUserInfo result = new(); if (loggingMonitor.AuthorizationClaims != null) { diff --git a/Admin.NET/Admin.NET.Core/Logging/ElasticSearchLoggingWriter.cs b/Admin.NET/Admin.NET.Core/Logging/ElasticSearchLoggingWriter.cs index dc2f943c..d496f9c5 100644 --- a/Admin.NET/Admin.NET.Core/Logging/ElasticSearchLoggingWriter.cs +++ b/Admin.NET/Admin.NET.Core/Logging/ElasticSearchLoggingWriter.cs @@ -42,7 +42,7 @@ public class ElasticSearchLoggingWriter : IDatabaseLoggingWriter, IDisposable return; // 获取当前操作者 - var userManager = LazyHelper.GetService(); + var userManager = LazyHelper.GetService().Value; string account = "", realName = "", userId = "", tenantId = ""; if (loggingMonitor.authorizationClaims != null) { diff --git a/Admin.NET/Admin.NET.Core/Logging/HttpLoggingHandler.cs b/Admin.NET/Admin.NET.Core/Logging/HttpLoggingHandler.cs index 1c7f7b7d..3407a823 100644 --- a/Admin.NET/Admin.NET.Core/Logging/HttpLoggingHandler.cs +++ b/Admin.NET/Admin.NET.Core/Logging/HttpLoggingHandler.cs @@ -38,7 +38,7 @@ public class HttpLoggingHandler : DelegatingHandler, ITransient if (!enabledLog || attr?.IgnoreLog == true) return await base.SendAsync(request, cancellationToken); var stopWatch = Stopwatch.StartNew(); - var userManger = LazyHelper.GetService(); + var userManger = LazyHelper.GetService().Value; var urlList = request.RequestUri?.LocalPath.Split("/") ?? []; var sysLogHttp = new SysLogHttp { diff --git a/Admin.NET/Admin.NET.Core/Service/Auth/SysAuthService.cs b/Admin.NET/Admin.NET.Core/Service/Auth/SysAuthService.cs index 5e969cc7..17134f31 100644 --- a/Admin.NET/Admin.NET.Core/Service/Auth/SysAuthService.cs +++ b/Admin.NET/Admin.NET.Core/Service/Auth/SysAuthService.cs @@ -6,6 +6,8 @@ using Furion.SpecificationDocument; using Lazy.Captcha.Core; +using Microsoft.AspNetCore.Mvc.ApiExplorer; +using Microsoft.AspNetCore.Mvc.Controllers; namespace Admin.NET.Core.Service; @@ -20,7 +22,9 @@ public class SysAuthService : IDynamicApiController, ITransient private readonly SqlSugarRepository _sysUserRep; private readonly SysConfigService _sysConfigService; private readonly SysCacheService _sysCacheService; + private readonly IHttpContextAccessor _httpContextAccessor; + private readonly IApiDescriptionGroupCollectionProvider _apiProvider; private readonly ICaptcha _captcha; private readonly IEventPublisher _eventPublisher; @@ -28,12 +32,14 @@ public class SysAuthService : IDynamicApiController, ITransient SqlSugarRepository sysUserRep, SysConfigService sysConfigService, SysCacheService sysCacheService, + IApiDescriptionGroupCollectionProvider apiProvider, IHttpContextAccessor httpContextAccessor, ICaptcha captcha, IEventPublisher eventPublisher) { _userManager = userManager; _sysUserRep = sysUserRep; + _apiProvider = apiProvider; _sysConfigService = sysConfigService; _sysCacheService = sysCacheService; _httpContextAccessor = httpContextAccessor; @@ -288,14 +294,28 @@ public class SysAuthService : IDynamicApiController, ITransient user.SysPos ??= await db.Queryable().FirstAsync(u => u.Id == user.PosId); user.SysOrg ??= await db.Queryable().FirstAsync(u => u.Id == user.OrgId); - var permissions = await LazyHelper.GetService().GetUserApiList(user.Id); - var unauthorizedPermissions = await LazyHelper.GetService().GetUnAuthApiList(user.Id); - var orgIds = await LazyHelper.GetService().GetUserOrgIdList(user.Id, user.OrgId); - var roleIds = await db.Queryable().Where(u => u.UserId == user.Id).Select(u => u.RoleId).ToListAsync(); - var postIds = await db.Queryable().Where(u => u.UserId == user.Id).Select(u => u.PosId).ToListAsync() ?? []; + var orgIds = await db.Queryable().Where(u => u.UserId == user.Id).Select(u => u.OrgId).ToListAsync(); + var roleIds = await db.Queryable().InnerJoinIF(user.AccountType != AccountTypeEnum.SuperAdmin, (u, a) => a.RoleId == u.Id && a.UserId == user.Id).Select((u, a) => u.Id).ToListAsync(); + var posIds = await db.Queryable().InnerJoinIF(user.AccountType != AccountTypeEnum.SuperAdmin, (u, a) => a.PosId == u.Id && a.UserId == user.Id).Select((u, a) => u.Id).ToListAsync(); + posIds = posIds.Concat([user.PosId]).Where(u => u != 0).ToList(); + var maxDataScope = await db.Queryable().Where(u => roleIds.Contains(u.Id)).MinAsync(u => u.DataScope); if (maxDataScope == 0) maxDataScope = DataScopeEnum.Self; - postIds.Add(user.PosId); + + var permissions = user.AccountType != AccountTypeEnum.SuperAdmin ? await db.Queryable() + .InnerJoin((u, a) => roleIds.Contains(a.RoleId) && u.MenuId == a.MenuId) + .InnerJoin((u, a, b) => u.Permission != b.Route) + .Select(u => u.Permission) + .ToListAsync() + : await db.Queryable().Select(u => u.Permission).ToListAsync(); + + var unauthorizedPermissions = user.AccountType != AccountTypeEnum.SuperAdmin ? await db.Union( + db.Queryable().Where(u => roleIds.Contains(u.RoleId)).Select(u => u.Route), + db.Queryable().Where(u => u.MenuId != 0 && SqlFunc.Subqueryable() + .Where(z => roleIds.Contains(z.RoleId) && z.MenuId == u.MenuId).NotAny()) + .Select(u => u.Permission) + ).ToListAsync() + : []; // 缓存用户Session _userManager.SetSession(new() @@ -317,11 +337,11 @@ public class SysAuthService : IDynamicApiController, ITransient LoginMode = loginMode, TokenVersion = user.TokenVersion, OrgIds = orgIds, - PosIds = postIds, + PosIds = posIds, RoleIds = roleIds, Permissions = permissions, UnauthorizedPermissions = unauthorizedPermissions, - AppPermissions = loginMode == LoginModeEnum.APP ? LazyHelper.GetService().GetAppApiList() : null, + AppPermissions = loginMode == LoginModeEnum.APP ? LazyHelper.GetService().Value.GetAppApiList() : null, MaxDataScope = user.AccountType == AccountTypeEnum.SuperAdmin ? DataScopeEnum.All : maxDataScope, ExtProps = App.GetServices().SelectMany(u => u.GetInitExtProps(user)).ToDictionary(u => u.Key, u => u.Value) }); @@ -485,4 +505,59 @@ public class SysAuthService : IDynamicApiController, ITransient var user = await _sysUserRep.AsQueryable().IgnoreTenant().Includes(u => u.SysOrg).FirstAsync(u => u.Id == userId); await SetUserSession(user, CommonHelper.IsMobile(_httpContextAccessor.HttpContext?.Request.Headers.UserAgent ?? "") ? LoginModeEnum.APP : LoginModeEnum.PC); } + + /// + /// 重置系统接口信息 + /// + [NonAction] + public async Task ResetSysApiInfo() + { + var id = SqlSugarConst.DefaultTenantId + 10000000000; + var apiList = new List(); + var apiDescriptionGroups = _apiProvider.ApiDescriptionGroups.Items; + foreach (ApiDescriptionGroup group in apiDescriptionGroups) + { + foreach (var action in group.Items) + { + // 控制器信息 + if (action.ActionDescriptor is not ControllerActionDescriptor actionDescriptor) continue; + var apiDescription = actionDescriptor.ControllerTypeInfo.GetCustomAttribute(true); + + // 路由 + var route = action.RelativePath!.Contains('{') ? action.RelativePath[..(action.RelativePath.IndexOf('{') - 1)] : action.RelativePath; // 去掉路由参数 + route = route[(route.IndexOf('/') + 1)..]; // 去掉路由前缀 + + // 获取分组名称和接口名称 + string groupName = null, displayText = null; + foreach (var attr in action.ActionDescriptor.EndpointMetadata) + { + switch (attr) + { + case ApiDescriptionSettingsAttribute settings: + if (!string.IsNullOrWhiteSpace(settings.GroupName)) groupName = settings.GroupName; + break; + case DisplayNameAttribute displayName: + if (!string.IsNullOrWhiteSpace(displayName.DisplayName)) displayText = displayName.DisplayName; + break; + } + } + + apiList.Add(new SysApiInfo + { + Id = id++, + Route = route, + HttpMethod = action.HttpMethod, + Order = apiDescription?.Order ?? 0, + Action = actionDescriptor.ActionName, + Name = actionDescriptor.ControllerName, + GroupName = groupName ?? group.GroupName, + IsAppApi = actionDescriptor.ControllerTypeInfo.GetCustomAttribute(true) != null, + Desc = displayText ?? (string.IsNullOrWhiteSpace(apiDescription?.Description) ? actionDescriptor.ControllerName : apiDescription?.Description), + }); + } + } + + await _sysUserRep.Context.Deleteable().ExecuteCommandAsync(); + await _sysUserRep.Context.Insertable(apiList).ExecuteCommandAsync(); + } } \ No newline at end of file diff --git a/Admin.NET/Admin.NET.Core/Service/Cache/SysCacheService.cs b/Admin.NET/Admin.NET.Core/Service/Cache/SysCacheService.cs index e6165f1b..8d619ed1 100644 --- a/Admin.NET/Admin.NET.Core/Service/Cache/SysCacheService.cs +++ b/Admin.NET/Admin.NET.Core/Service/Cache/SysCacheService.cs @@ -431,7 +431,8 @@ public class SysCacheService : IDynamicApiController, ISingleton public void Clear() { // 超管用户操作,清空所有缓存 - if (LazyHelper.GetService().SuperAdmin) + var userManager = App.GetService(); + if (userManager.SuperAdmin) { _cacheProvider.Cache.Clear(); Cache.Default.Clear(); diff --git a/Admin.NET/Admin.NET.Core/Service/Dict/SysDictDataService.cs b/Admin.NET/Admin.NET.Core/Service/Dict/SysDictDataService.cs index 170f7e3d..49d318ec 100644 --- a/Admin.NET/Admin.NET.Core/Service/Dict/SysDictDataService.cs +++ b/Admin.NET/Admin.NET.Core/Service/Dict/SysDictDataService.cs @@ -61,7 +61,10 @@ public class SysDictDataService : IDynamicApiController, ITransient [DisplayName("增加字典值")] public async Task AddDictData(AddDictDataInput input) { - var isExist = await _sysDictDataRep.IsAnyAsync(u => u.Value == input.Value && u.DictTypeId == input.DictTypeId); + var isExist = await _sysDictDataRep.IsAnyAsync(u => u.Code != null && u.Code == input.Code && u.DictTypeId == input.DictTypeId); + if (isExist) throw Oops.Oh(ErrorCodeEnum.D3002); + + isExist = await _sysDictDataRep.IsAnyAsync(u => u.Value != null && u.Value == input.Value && u.DictTypeId == input.DictTypeId); if (isExist) throw Oops.Oh(ErrorCodeEnum.D3003); var dictType = await _sysDictDataRep.Change().GetByIdAsync(input.DictTypeId); @@ -86,7 +89,10 @@ public class SysDictDataService : IDynamicApiController, ITransient var isExist = await _sysDictDataRep.IsAnyAsync(u => u.Id == input.Id); if (!isExist) throw Oops.Oh(ErrorCodeEnum.D3004); - isExist = await _sysDictDataRep.IsAnyAsync(u => u.Value == input.Value && u.DictTypeId == input.DictTypeId && u.Id != input.Id); + isExist = await _sysDictDataRep.IsAnyAsync(u => u.Code != null && u.Code == input.Code && u.DictTypeId == input.DictTypeId && u.Id != input.Id); + if (isExist) throw Oops.Oh(ErrorCodeEnum.D3002); + + isExist = await _sysDictDataRep.IsAnyAsync(u => u.Value != null && u.Value == input.Value && u.DictTypeId == input.DictTypeId && u.Id != input.Id); if (isExist) throw Oops.Oh(ErrorCodeEnum.D3003); var dictType = await _sysDictDataRep.Change().GetByIdAsync(input.DictTypeId); diff --git a/Admin.NET/Admin.NET.Core/Service/User/UserManager.cs b/Admin.NET/Admin.NET.Core/Service/User/UserManager.cs index e764237e..a0fd26c9 100644 --- a/Admin.NET/Admin.NET.Core/Service/User/UserManager.cs +++ b/Admin.NET/Admin.NET.Core/Service/User/UserManager.cs @@ -211,7 +211,7 @@ public class UserManager( if (long.TryParse(userId.ToString(), out long tempId)) userId = tempId; else return null; } - LazyHelper.GetService().RefreshSession(userId).GetAwaiter().GetResult(); + LazyHelper.GetService().Value.RefreshSession(userId).GetAwaiter().GetResult(); } return sysCacheService.Get(CacheConst.KeyUserSession + userId); } diff --git a/Admin.NET/Admin.NET.Core/SqlSugar/SqlSugarExtension.cs b/Admin.NET/Admin.NET.Core/SqlSugar/SqlSugarExtension.cs index 3d07e76e..a735409c 100644 --- a/Admin.NET/Admin.NET.Core/SqlSugar/SqlSugarExtension.cs +++ b/Admin.NET/Admin.NET.Core/SqlSugar/SqlSugarExtension.cs @@ -584,7 +584,7 @@ public static class SqlSugarExtension // 使用线程安全的延迟初始化服务实例获取文本缩写 var abbrValue = LazyHelper.GetService() - .GetNameAbbr(new() { Text = value, All = attribute.SaveFullAbbr }) + .Value.GetNameAbbr(new() { Text = value, All = attribute.SaveFullAbbr }) .GetAwaiter() .GetResult(); entityInfo.SetValue(abbrValue); @@ -634,7 +634,7 @@ public static class SqlSugarExtension // 使用线程安全的延迟初始化服务实例获取流水号 var serial = LazyHelper.GetService() - .NextSeqNo(attribute.Type, attribute.IsGlobal) + .Value.NextSeqNo(attribute.Type, attribute.IsGlobal) .GetAwaiter() .GetResult(); entityInfo.SetValue(serial); diff --git a/Admin.NET/Admin.NET.Core/SqlSugar/SqlSugarFilter.cs b/Admin.NET/Admin.NET.Core/SqlSugar/SqlSugarFilter.cs index f038614e..86896c1e 100644 --- a/Admin.NET/Admin.NET.Core/SqlSugar/SqlSugarFilter.cs +++ b/Admin.NET/Admin.NET.Core/SqlSugar/SqlSugarFilter.cs @@ -59,7 +59,8 @@ public static class SqlSugarFilter if (string.IsNullOrWhiteSpace(userId)) return; // 获取用户session - var session = LazyHelper.GetService().GetSessionOrRefresh(userId); + var userManager = LazyHelper.GetService().Value; + var session = userManager.GetSessionOrRefresh(userId); if (session == null) return; // 配置用户机构集合缓存 @@ -113,7 +114,8 @@ public static class SqlSugarFilter if (string.IsNullOrWhiteSpace(userId)) return maxDataScope; // 获取用户session - var session = LazyHelper.GetService().GetSessionOrRefresh(userId); + var userManager = LazyHelper.GetService().Value; + var session = userManager.GetSessionOrRefresh(userId); if (session == null) return (int)DataScopeEnum.Self; // 获取用户最大数据范围---仅本人数据 diff --git a/Admin.NET/Admin.NET.Core/SqlSugar/SqlSugarRepository.cs b/Admin.NET/Admin.NET.Core/SqlSugar/SqlSugarRepository.cs index 8eb2525b..b3a12977 100644 --- a/Admin.NET/Admin.NET.Core/SqlSugar/SqlSugarRepository.cs +++ b/Admin.NET/Admin.NET.Core/SqlSugar/SqlSugarRepository.cs @@ -37,7 +37,8 @@ public class SqlSugarRepository : SimpleClient, ISqlSugarRepository whe return; // 若未贴任何表特性或当前未登录或是默认租户Id,则返回默认库连接 - var tenantId = LazyHelper.GetService().TenantId?.ToString(); + var userManager = LazyHelper.GetService().Value; + var tenantId = userManager.TenantId?.ToString(); if (string.IsNullOrWhiteSpace(tenantId) || tenantId == SqlSugarConst.MainConfigId) return; // 根据租户Id切换库连接, 为空则返回默认库连接 diff --git a/Admin.NET/Admin.NET.Core/SqlSugar/SqlSugarSetup.cs b/Admin.NET/Admin.NET.Core/SqlSugar/SqlSugarSetup.cs index 133bd038..b1ed6f2a 100644 --- a/Admin.NET/Admin.NET.Core/SqlSugar/SqlSugarSetup.cs +++ b/Admin.NET/Admin.NET.Core/SqlSugar/SqlSugarSetup.cs @@ -215,7 +215,7 @@ public static class SqlSugarSetup Log.Warning(log); }; - var userManager = LazyHelper.GetService(); + var userManager = LazyHelper.GetService().Value; // 数据审计 dbProvider.Aop.DataExecuting = (oldValue, entityInfo) => { diff --git a/Admin.NET/Admin.NET.Core/Utils/LazyHelper.cs b/Admin.NET/Admin.NET.Core/Utils/LazyHelper.cs index d6fb725a..c317f6f5 100644 --- a/Admin.NET/Admin.NET.Core/Utils/LazyHelper.cs +++ b/Admin.NET/Admin.NET.Core/Utils/LazyHelper.cs @@ -6,18 +6,28 @@ namespace Admin.NET.Core; +/// +/// 懒加载帮助类 +/// public class LazyHelper { - private static readonly Dictionary> _cache = new(); + private static readonly ConcurrentDictionary Cache = new(); /// /// 获取服务 /// /// /// - public static T GetService() where T : class + public static Lazy GetService() where T : class { - if (_cache.TryGetValue(typeof(T), out var lazy)) return (T)lazy.Value; - return (T)(_cache[typeof(T)] = new Lazy(() => App.GetService())).Value; + try + { + return Cache.GetOrAdd(typeof(T), _ => new Lazy(() => App.GetService())); + } + catch (Exception) + { + Cache.Remove(typeof(T), out _); + return null; + } } } \ No newline at end of file diff --git a/Admin.NET/Admin.NET.Web.Core/Handlers/JwtHandler.cs b/Admin.NET/Admin.NET.Web.Core/Handlers/JwtHandler.cs index 47f50c3b..6a51e947 100644 --- a/Admin.NET/Admin.NET.Web.Core/Handlers/JwtHandler.cs +++ b/Admin.NET/Admin.NET.Web.Core/Handlers/JwtHandler.cs @@ -91,7 +91,8 @@ namespace Admin.NET.Web.Core } // 验证租户有效期 - var tenantId = LazyHelper.GetService().TenantId?.ToString(); + var userManager = LazyHelper.GetService().Value; + var tenantId = userManager.TenantId?.ToString(); if (!string.IsNullOrWhiteSpace(tenantId)) { var tenant = sysCacheService.Get>(CacheConst.KeyTenant)?.FirstOrDefault(u => u.Id == long.Parse(tenantId)); @@ -117,7 +118,7 @@ namespace Admin.NET.Web.Core /// private static async Task CheckAuthorizeAsync(DefaultHttpContext httpContext) { - var userManager = LazyHelper.GetService(); + var userManager = LazyHelper.GetService().Value; // 排除超管权限判断 if (userManager?.AccountType == AccountTypeEnum.SuperAdmin) return true; diff --git a/Admin.NET/Plugins/Admin.NET.Plugin.ReZero/Service/SuperApiAop.cs b/Admin.NET/Plugins/Admin.NET.Plugin.ReZero/Service/SuperApiAop.cs index f3ddb0eb..29071b63 100644 --- a/Admin.NET/Plugins/Admin.NET.Plugin.ReZero/Service/SuperApiAop.cs +++ b/Admin.NET/Plugins/Admin.NET.Plugin.ReZero/Service/SuperApiAop.cs @@ -61,7 +61,7 @@ public class SuperApiAop : DefaultSuperApiAop var paths = api?.Url?.Split('/'); var actionName = paths?[^1]; - var userManager = LazyHelper.GetService(); + var userManager = LazyHelper.GetService().Value; var apiInfo = new { requestUrl = api?.Url, diff --git a/Web/src/views/system/dict/component/editDictData.vue b/Web/src/views/system/dict/component/editDictData.vue index b1ff18fc..2f5b1f18 100644 --- a/Web/src/views/system/dict/component/editDictData.vue +++ b/Web/src/views/system/dict/component/editDictData.vue @@ -20,7 +20,7 @@ - + @@ -57,10 +57,10 @@ - - - - 格式化JSON + + + + 格式化JSON @@ -156,4 +156,4 @@ const formatJSON = () => { // 导出对象 defineExpose({ openDialog }); - + \ No newline at end of file