From b27ea85fedce991905d0a5ffb9c6f85951f0a50b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=8D=E5=81=9A=E7=A0=81=E5=86=9C?= <599854767@qq.com> Date: Sun, 26 Dec 2021 18:26:38 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Controllers/System/SysLoginController.cs | 11 +- .../Controllers/System/SysRoleController.cs | 9 +- ZR.Admin.WebApi/Extensions/DbExtension.cs | 118 ++++++++++++++++++ ZR.Admin.WebApi/Framework/AsyncFactory.cs | 1 - ZR.Admin.WebApi/Framework/JwtUtil.cs | 2 +- ZR.Admin.WebApi/Startup.cs | 63 +--------- ZR.Model/System/LoginUser.cs | 22 +++- ZR.Service/System/IService/ISysRoleService.cs | 6 + ZR.Service/System/SysRoleService.cs | 24 +++- 9 files changed, 179 insertions(+), 77 deletions(-) create mode 100644 ZR.Admin.WebApi/Extensions/DbExtension.cs diff --git a/ZR.Admin.WebApi/Controllers/System/SysLoginController.cs b/ZR.Admin.WebApi/Controllers/System/SysLoginController.cs index 1e07704..491430d 100644 --- a/ZR.Admin.WebApi/Controllers/System/SysLoginController.cs +++ b/ZR.Admin.WebApi/Controllers/System/SysLoginController.cs @@ -32,7 +32,7 @@ namespace ZR.Admin.WebApi.Controllers.System private readonly ISysPermissionService permissionService; private readonly SecurityCodeHelper SecurityCodeHelper; private readonly ISysConfigService sysConfigService; - + private readonly ISysRoleService roleService; public SysLoginController( IHttpContextAccessor contextAccessor, ISysMenuService sysMenuService, @@ -40,6 +40,7 @@ namespace ZR.Admin.WebApi.Controllers.System ISysLoginService sysLoginService, ISysPermissionService permissionService, ISysConfigService configService, + ISysRoleService sysRoleService, SecurityCodeHelper captcha) { httpContextAccessor = contextAccessor; @@ -49,6 +50,7 @@ namespace ZR.Admin.WebApi.Controllers.System this.sysLoginService = sysLoginService; this.permissionService = permissionService; this.sysConfigService = configService; + roleService = sysRoleService; } @@ -67,17 +69,18 @@ namespace ZR.Admin.WebApi.Controllers.System SysConfig sysConfig = sysConfigService.GetSysConfigByKey("sys.account.captchaOnOff"); if (sysConfig?.ConfigValue != "off" && CacheHelper.Get(loginBody.Uuid) is string str && !str.ToLower().Equals(loginBody.Code.ToLower())) { - throw new CustomException(ResultCode.CAPTCHA_ERROR, "验证码错误"); + return CustomError(ResultCode.CAPTCHA_ERROR, "验证码错误"); } var user = sysLoginService.Login(loginBody, AsyncFactory.RecordLogInfo(httpContextAccessor.HttpContext, "0", "login")); #region 存入cookie Action校验权限使用 //角色集合 eg: admin,yunying,common - List roles = permissionService.GetRolePermission(user); + //List roles = permissionService.GetRolePermission(user); + List roles = roleService.SelectRolePermissionByUserId(user.UserId); //权限集合 eg *:*:*,system:user:list List permissions = permissionService.GetMenuPermission(user); #endregion - LoginUser loginUser = new LoginUser(user.UserId, user.UserName, roles, permissions); + LoginUser loginUser = new LoginUser(user, roles, permissions); return SUCCESS(JwtUtil.GenerateJwtToken(HttpContext.AddClaims(loginUser))); } diff --git a/ZR.Admin.WebApi/Controllers/System/SysRoleController.cs b/ZR.Admin.WebApi/Controllers/System/SysRoleController.cs index 8859cc3..896e7b6 100644 --- a/ZR.Admin.WebApi/Controllers/System/SysRoleController.cs +++ b/ZR.Admin.WebApi/Controllers/System/SysRoleController.cs @@ -129,13 +129,8 @@ namespace ZR.Admin.WebApi.Controllers.System sysRoleDto.Create_by = HttpContext.GetName(); sysRoleService.CheckRoleAllowed(sysRoleDto); - - bool result = sysRoleService.UseTran2(() => - { - //删除角色菜单 - sysRoleService.DeleteRoleMenuByRoleId(sysRoleDto.RoleId); - sysRoleService.InsertRoleMenu(sysRoleDto); - }); + + bool result = sysRoleService.AuthDataScope(sysRoleDto); return SUCCESS(result); } diff --git a/ZR.Admin.WebApi/Extensions/DbExtension.cs b/ZR.Admin.WebApi/Extensions/DbExtension.cs new file mode 100644 index 0000000..2ca298d --- /dev/null +++ b/ZR.Admin.WebApi/Extensions/DbExtension.cs @@ -0,0 +1,118 @@ +using Infrastructure; +using Microsoft.Extensions.Configuration; +using SqlSugar; +using SqlSugar.IOC; +using System; +using System.Collections.Generic; +using System.Linq; +using ZR.Admin.WebApi.Framework; +using ZR.Model.System; + +namespace ZR.Admin.WebApi.Extensions +{ + public static class DbExtension + { + private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger(); + public static void AddDb(IConfiguration Configuration) + { + string connStr = Configuration.GetConnectionString(OptionsSetting.ConnAdmin); + string connStrBus = Configuration.GetConnectionString(OptionsSetting.ConnBus); + string dbKey = Configuration[OptionsSetting.DbKey]; + int dbType = Convert.ToInt32(Configuration[OptionsSetting.ConnDbType]); + int dbType_bus = Convert.ToInt32(Configuration[OptionsSetting.ConnBusDbType]); + + SugarIocServices.AddSqlSugar(new List() { + new IocConfig() { + ConfigId = "0", + ConnectionString = connStr, + DbType = (IocDbType)dbType, + IsAutoCloseConnection = true//自动释放 + }, new IocConfig() { + ConfigId = "1", + ConnectionString = connStrBus, + DbType = (IocDbType)dbType_bus, + IsAutoCloseConnection = true//自动释放 + } + }); + //每次Sql执行前事件 + var db0 = DbScoped.SugarScope.GetConnection(0); + db0.Aop.OnLogExecuting = (sql, pars) => + { + var param = DbScoped.SugarScope.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)); + + FilterData(db0); + + logger.Info($"Sql语句:{sql},{param}"); + }; + //出错打印日志 + db0.Aop.OnError = (e) => + { + logger.Error(e, $"执行SQL出错:{e.Message}"); + }; + //SQL执行完 + db0.Aop.OnLogExecuted = (sql, pars) => + { + //执行完了可以输出SQL执行时间 (OnLogExecutedDelegate) + }; + //Db1 + DbScoped.SugarScope.GetConnection(1).Aop.OnLogExecuting = (sql, pars) => + { + var param = DbScoped.SugarScope.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)); + //Console.WriteLine("【SQL语句Bus】" + sql.ToLower() + "\r\n" + param); + logger.Info($"Sql语句:{sql}, {param}"); + }; + //Db1错误日志 + DbScoped.SugarScope.GetConnection(1).Aop.OnError = (e) => + { + logger.Error($"执行Sql语句失败:{e.Sql},原因:{e.Message}"); + }; + + } + + private static void FilterData(SqlSugarProvider db0) + { + var u = App.User; + if (u != null && u.Identity.IsAuthenticated) + { + //获取当前用户的信息 + var user = JwtUtil.GetLoginUser(App.HttpContext); + if (user != null) + { + //非管理员过滤数据权限 + if (!user.RoleIds.Any(f => f.Equals("admin"))) + { + //TODO 实现范围过滤 + foreach (var role in user.Roles) + { + string dataScope = role.DataScope; + if ("1".Equals(dataScope)) + { + break; + } + else if ("2".Equals(dataScope)) + { + var roleDepts = db0.Queryable() + .Where(f => f.RoleId == role.RoleId).Select(f => f.DeptId).ToList(); + var filter1 = new TableFilterItem(it => roleDepts.Contains(it.DeptId)); + } + else if ("3".Equals(dataScope)) + { + var filter1 = new TableFilterItem(it => it.DeptId == user.DeptId); + } + else if ("4".Equals(dataScope)) + { + + } + else if ("5".Equals(dataScope)) + { + var filter1 = new TableFilterItem(it => it.UserId == user.UserId); + } + } + } + } + } + //TODO 在此实现数据过滤 + //DbScoped.SugarScope.GetConnection(0).QueryFilter.Add(new TableFilterItem(it => it.DeptId == 333)); //为Order表置全局条件 + } + } +} diff --git a/ZR.Admin.WebApi/Framework/AsyncFactory.cs b/ZR.Admin.WebApi/Framework/AsyncFactory.cs index 07c10c1..c1aae1a 100644 --- a/ZR.Admin.WebApi/Framework/AsyncFactory.cs +++ b/ZR.Admin.WebApi/Framework/AsyncFactory.cs @@ -30,6 +30,5 @@ namespace ZR.Admin.WebApi.Framework return sysLogininfor; } - } } diff --git a/ZR.Admin.WebApi/Framework/JwtUtil.cs b/ZR.Admin.WebApi/Framework/JwtUtil.cs index 83c8e46..9708e4c 100644 --- a/ZR.Admin.WebApi/Framework/JwtUtil.cs +++ b/ZR.Admin.WebApi/Framework/JwtUtil.cs @@ -121,7 +121,7 @@ namespace ZR.Admin.WebApi.Framework /// /// /// - private static LoginUser ValidateJwtToken(IEnumerable jwtToken) + public static LoginUser ValidateJwtToken(IEnumerable jwtToken) { try { diff --git a/ZR.Admin.WebApi/Startup.cs b/ZR.Admin.WebApi/Startup.cs index 6db363f..a32423e 100644 --- a/ZR.Admin.WebApi/Startup.cs +++ b/ZR.Admin.WebApi/Startup.cs @@ -9,12 +9,8 @@ using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; -using SqlSugar.IOC; using System; -using System.Collections.Generic; using System.IO; -using System.Linq; -using Microsoft.OpenApi.Models; using ZR.Admin.WebApi.Extensions; using ZR.Admin.WebApi.Filters; using ZR.Admin.WebApi.Framework; @@ -24,13 +20,11 @@ namespace ZR.Admin.WebApi { public class Startup { - public Startup(IConfiguration configuration, IWebHostEnvironment hostEnvironment) + public Startup(IConfiguration configuration) { Configuration = configuration; - CurrentEnvironment = hostEnvironment; } private NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger(); - private IWebHostEnvironment CurrentEnvironment { get; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { @@ -72,7 +66,7 @@ namespace ZR.Admin.WebApi o.TokenValidationParameters = JwtUtil.ValidParameters(); }); - InjectServices(services); + InjectServices(services, Configuration); services.AddMvc(options => { @@ -94,7 +88,6 @@ namespace ZR.Admin.WebApi { app.UseDeveloperExceptionPage(); } - app.UseSwagger(); //ʹԶζȥbody app.Use((context, next) => @@ -135,59 +128,15 @@ namespace ZR.Admin.WebApi /// עServices /// /// - private void InjectServices(IServiceCollection services) + /// + private void InjectServices(IServiceCollection services, IConfiguration configuration) { services.AddAppService(); //ƻ services.AddTaskSchedulers(); - - string connStr = Configuration.GetConnectionString(OptionsSetting.ConnAdmin); - string connStrBus = Configuration.GetConnectionString(OptionsSetting.ConnBus); - string dbKey = Configuration[OptionsSetting.DbKey]; - int dbType = Convert.ToInt32(Configuration[OptionsSetting.ConnDbType]); - int dbType_bus = Convert.ToInt32(Configuration[OptionsSetting.ConnBusDbType]); - - SugarIocServices.AddSqlSugar(new List() { - new IocConfig() { - ConfigId = "0", - ConnectionString = connStr, - DbType = (IocDbType)dbType, - IsAutoCloseConnection = true//Զͷ - }, new IocConfig() { - ConfigId = "1", - ConnectionString = connStrBus, - DbType = (IocDbType)dbType_bus, - IsAutoCloseConnection = true//Զͷ - } - }); - - //ʽ ӡSQL - DbScoped.SugarScope.GetConnection(0).Aop.OnLogExecuting = (sql, pars) => - { - var param = DbScoped.SugarScope.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)); - //Console.WriteLine("SQL䡿" + sql.ToLower() + "\r\n" + param); - logger.Info($"Sql䣺{sql}{param}"); - }; - //ӡ־ - DbScoped.SugarScope.GetConnection(0).Aop.OnError = (e) => - { - Console.WriteLine($"[ִSql]{e.Message}SQL={e.Sql}"); - Console.WriteLine(); - }; - - //ʽ ӡSQL - DbScoped.SugarScope.GetConnection(1).Aop.OnLogExecuting = (sql, pars) => - { - var param = DbScoped.SugarScope.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)); - //Console.WriteLine("SQLBus" + sql.ToLower() + "\r\n" + param); - logger.Info($"Sql䣺{sql}, {param}"); - }; - //Bus Db־ - DbScoped.SugarScope.GetConnection(1).Aop.OnError = (e) => - { - logger.Error($"ִSqlʧܣ{e.Sql}ԭ{e.Message}"); - }; + //ʼdb + DbExtension.AddDb(configuration); } } } diff --git a/ZR.Model/System/LoginUser.cs b/ZR.Model/System/LoginUser.cs index 2bb2ab8..3be5bba 100644 --- a/ZR.Model/System/LoginUser.cs +++ b/ZR.Model/System/LoginUser.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Text; namespace ZR.Model.System @@ -10,6 +11,7 @@ namespace ZR.Model.System public class LoginUser { public long UserId { get; set; } + public long DeptId { get; set; } public string UserName { get; set; } public string NickName { get; set; } /// @@ -17,18 +19,17 @@ namespace ZR.Model.System /// public List RoleIds { get; set; } /// + /// 角色集合 + /// + public List Roles { get; set; } + /// /// 权限集合 /// - public List Permissions{ get; set; } + public List Permissions { get; set; } public LoginUser() { } - public LoginUser(long userId, string userName) - { - UserId = userId; - UserName = userName; - } public LoginUser(long userId, string userName, List roleIds, List permissions) { UserId = userId; @@ -36,5 +37,14 @@ namespace ZR.Model.System RoleIds = roleIds; Permissions = permissions; } + public LoginUser(SysUser user, List roles, List permissions) + { + UserId = user.UserId; + UserName = user.UserName; + DeptId = user.DeptId; + Roles = roles; + RoleIds = roles.Select(f => f.RoleKey).ToList(); + Permissions = permissions; + } } } diff --git a/ZR.Service/System/IService/ISysRoleService.cs b/ZR.Service/System/IService/ISysRoleService.cs index b343c0f..e2517b8 100644 --- a/ZR.Service/System/IService/ISysRoleService.cs +++ b/ZR.Service/System/IService/ISysRoleService.cs @@ -76,6 +76,12 @@ namespace ZR.Service.System.IService /// public int DeleteRoleMenuByRoleId(long roleId); + /// + /// 授权数据范围 + /// + /// + /// + bool AuthDataScope(SysRole role); #region Service diff --git a/ZR.Service/System/SysRoleService.cs b/ZR.Service/System/SysRoleService.cs index 026b55d..02ce07c 100644 --- a/ZR.Service/System/SysRoleService.cs +++ b/ZR.Service/System/SysRoleService.cs @@ -148,11 +148,33 @@ namespace ZR.Service return SysRoleRepository.DeleteRoleMenuByRoleId(roleId); } + /// + /// 修改数据权限信息 + /// + /// + /// + public bool AuthDataScope(SysRole sysRoleDto) + { + return UseTran2(() => + { + int result = Update(sysRoleDto, it => new + { + it.DataScope + }, f => f.RoleId == sysRoleDto.RoleId); + + //if (result > 0 && sysRoleDto.DataScope == "2") + //{ + //删除角色菜单 + DeleteRoleMenuByRoleId(sysRoleDto.RoleId); + InsertRoleMenu(sysRoleDto); + //} + }); + } #region Service /// - /// 新增角色菜单信息 + /// 批量新增角色菜单信息 /// /// ///