平安校园
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SysRoleService.cs 25 KiB

4 月之前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. 
  2. //
  3. namespace SafeCampus.System;
  4. /// <inheritdoc cref="ISysRoleService"/>
  5. //[Injection(Proxy = typeof(GlobalDispatchProxy))]
  6. public class SysRoleService : DbRepository<SysRole>, ISysRoleService
  7. {
  8. private readonly ILogger<SysRoleService> _logger;
  9. private readonly ISimpleCacheService _simpleCacheService;
  10. private readonly IRelationService _relationService;
  11. private readonly ISysOrgService _sysOrgService;
  12. private readonly IResourceService _resourceService;
  13. private readonly IEventPublisher _eventPublisher;
  14. public SysRoleService(ILogger<SysRoleService> logger, ISimpleCacheService simpleCacheService, IRelationService relationService,
  15. ISysOrgService sysOrgService, IResourceService resourceService, IEventPublisher eventPublisher)
  16. {
  17. _logger = logger;
  18. _simpleCacheService = simpleCacheService;
  19. _relationService = relationService;
  20. _sysOrgService = sysOrgService;
  21. _resourceService = resourceService;
  22. _eventPublisher = eventPublisher;
  23. }
  24. #region 查询
  25. /// <summary>
  26. /// 获取所有
  27. /// </summary>
  28. /// <returns></returns>
  29. public override async Task<List<SysRole>> GetListAsync()
  30. {
  31. //先从Redis拿
  32. var sysRoles = _simpleCacheService.Get<List<SysRole>>(SystemConst.CACHE_SYS_ROLE);
  33. if (sysRoles == null)
  34. {
  35. //redis没有就去数据库拿
  36. sysRoles = await base.GetListAsync();
  37. if (sysRoles.Count > 0)
  38. {
  39. //插入Redis
  40. _simpleCacheService.Set(SystemConst.CACHE_SYS_ROLE, sysRoles);
  41. }
  42. }
  43. return sysRoles;
  44. }
  45. /// <inheritdoc/>
  46. public async Task<List<SysRole>> GetRoleListByUserId(long userId)
  47. {
  48. var cods = new List<SysRole>();//角色代码集合
  49. var roleList = await _relationService.GetRelationListByObjectIdAndCategory(userId, CateGoryConst.RELATION_SYS_USER_HAS_ROLE);//根据用户ID获取角色ID
  50. var roleIdList = roleList.Select(x => x.TargetId.ToLong()).ToList();//角色ID列表
  51. if (roleIdList.Count > 0)
  52. {
  53. cods = await GetListAsync(it => roleIdList.Contains(it.Id));
  54. }
  55. return cods;
  56. }
  57. /// <inheritdoc/>
  58. public async Task<SqlSugarPagedList<SysRole>> Page(RolePageInput input)
  59. {
  60. var orgIds = await _sysOrgService.GetOrgChildIds(input.OrgId);//获取下级机构
  61. var query = Context.Queryable<SysRole>()
  62. .WhereIF(input.OrgId > 0, it => orgIds.Contains(it.OrgId.Value))//根据组织
  63. .WhereIF(input.OrgIds != null, it => input.OrgIds.Contains(it.OrgId.Value))//数据权限
  64. .WhereIF(!string.IsNullOrEmpty(input.Category), it => it.Category == input.Category)//根据分类
  65. .WhereIF(!string.IsNullOrEmpty(input.SearchKey), it => it.Name.Contains(input.SearchKey))//根据关键字查询
  66. .OrderByIF(!string.IsNullOrEmpty(input.SortField), $"{input.SortField} {input.SortOrder}").OrderBy(it => it.SortCode);//排序
  67. var pageInfo = await query.ToPagedListAsync(input.PageNum, input.PageSize);//分页
  68. return pageInfo;
  69. }
  70. /// <inheritdoc/>
  71. public async Task<List<RoleTreeOutput>> Tree(RoleTreeInput input)
  72. {
  73. var result = new List<RoleTreeOutput>();//返回结果
  74. var sysOrgList = await _sysOrgService.GetListAsync(false);//获取所有机构
  75. var sysRoles = await GetListAsync();//获取所有角色
  76. if (input.OrgIds != null)//根据数据范围查
  77. {
  78. sysOrgList = sysOrgList.Where(it => input.OrgIds.Contains(it.Id)).ToList();//在指定组织列表查询
  79. sysRoles = sysRoles.Where(it => input.OrgIds.Contains(it.OrgId.GetValueOrDefault())).ToList();//在指定职位列表查询
  80. }
  81. var topOrgList = sysOrgList.Where(it => it.ParentId == 0).ToList();//获取顶级机构
  82. var globalRole = sysRoles.Where(it => it.Category == CateGoryConst.ROLE_GLOBAL).ToList();//获取全局角色
  83. if (globalRole.Count > 0)
  84. {
  85. result.Add(new RoleTreeOutput()
  86. {
  87. Id = CommonUtils.GetSingleId(),
  88. Name = "全局角色",
  89. Children = globalRole.Select(it => new RoleTreeOutput
  90. {
  91. Id = it.Id,
  92. Name = it.Name,
  93. IsRole = true
  94. }).ToList()
  95. });//添加全局角色
  96. }
  97. //遍历顶级机构
  98. foreach (var org in topOrgList)
  99. {
  100. var childIds = await _sysOrgService.GetOrgChildIds(org.Id, true, sysOrgList);//获取机构下的所有子级ID
  101. var childRoles = sysRoles.Where(it => it.OrgId != null && childIds.Contains(it.OrgId.Value)).ToList();//获取机构下的所有角色
  102. if (childRoles.Count == 0)
  103. continue;
  104. var roleTreeOutput = new RoleTreeOutput
  105. {
  106. Id = org.Id,
  107. Name = org.Name,
  108. IsRole = false
  109. };//实例化角色树
  110. childRoles.ForEach(it =>
  111. {
  112. roleTreeOutput.Children.Add(new RoleTreeOutput()
  113. {
  114. Id = it.Id,
  115. Name = it.Name,
  116. IsRole = true
  117. });
  118. });
  119. result.Add(roleTreeOutput);
  120. }
  121. return result;
  122. }
  123. /// <inheritdoc />
  124. public async Task<RoleOwnResourceOutput> OwnResource(BaseIdInput input, string category)
  125. {
  126. var roleOwnResource = new RoleOwnResourceOutput { Id = input.Id };//定义结果集
  127. var grantInfoList = new List<RelationRoleResource>();//已授权信息集合
  128. //获取关系列表
  129. var relations = await _relationService.GetRelationListByObjectIdAndCategory(input.Id, category);
  130. //遍历关系表
  131. relations.ForEach(it =>
  132. {
  133. //将扩展信息转为实体
  134. var relationRole = it.ExtJson.ToJsonEntity<RelationRoleResource>();
  135. grantInfoList.Add(relationRole);//添加到已授权信息
  136. });
  137. roleOwnResource.GrantInfoList = grantInfoList;//赋值已授权信息
  138. return roleOwnResource;
  139. }
  140. /// <inheritdoc />
  141. public async Task<RoleOwnPermissionOutput> OwnPermission(BaseIdInput input)
  142. {
  143. var roleOwnPermission = new RoleOwnPermissionOutput { Id = input.Id };//定义结果集
  144. var grantInfoList = new List<RelationRolePermission>();//已授权信息集合
  145. //获取关系列表
  146. var relations = await _relationService.GetRelationListByObjectIdAndCategory(input.Id, CateGoryConst.RELATION_SYS_ROLE_HAS_PERMISSION);
  147. //遍历关系表
  148. relations.ForEach(it =>
  149. {
  150. //将扩展信息转为实体
  151. var relationPermission = it.ExtJson.ToJsonEntity<RelationRolePermission>();
  152. grantInfoList.Add(relationPermission);//添加到已授权信息
  153. });
  154. roleOwnPermission.GrantInfoList = grantInfoList;//赋值已授权信息
  155. return roleOwnPermission;
  156. }
  157. /// <inheritdoc />
  158. public async Task<List<UserSelectorOutPut>> OwnUser(BaseIdInput input)
  159. {
  160. //获取关系列表
  161. var relations = await _relationService.GetRelationListByTargetIdAndCategory(input.Id.ToString(), CateGoryConst.RELATION_SYS_USER_HAS_ROLE);
  162. var userIds = relations.Select(it => it.ObjectId).ToList();
  163. var userList = await Context.Queryable<SysUser>().Where(it => userIds.Contains(it.Id)).Select<UserSelectorOutPut>().ToListAsync();
  164. return userList;
  165. }
  166. /// <inheritdoc />
  167. public async Task<SqlSugarPagedList<RoleSelectorOutPut>> RoleSelector(RoleSelectorInput input)
  168. {
  169. var orgIds = await _sysOrgService.GetOrgChildIds(input.OrgId);//获取下级组织
  170. //如果机构ID列表不为空
  171. if (input.OrgIds != null)
  172. {
  173. orgIds = orgIds.Where(it => input.OrgIds.Contains(it)).ToList();//包含在机构ID列表中的组织ID
  174. }
  175. var result = await Context.Queryable<SysRole>()
  176. .WhereIF(input.OrgId == 0, it => it.Category == CateGoryConst.ROLE_GLOBAL)//不传机构ID就是全局角色
  177. .WhereIF(orgIds.Count > 0, it => orgIds.Contains(it.OrgId.Value))//组织ID
  178. .WhereIF(!string.IsNullOrEmpty(input.Name), it => it.Name.Contains(input.Name))//根据关键字查询
  179. .Select<RoleSelectorOutPut>()
  180. .ToPagedListAsync(input.PageNum, input.PageSize);
  181. return result;
  182. }
  183. /// <inheritdoc />
  184. public async Task<List<string>> RolePermissionTreeSelector(BaseIdInput input)
  185. {
  186. var permissionTreeSelectors = new List<string>();//授权树结果集
  187. //获取单页信息
  188. var spa = await _resourceService.GetListByCategory(CateGoryConst.RESOURCE_SPA);
  189. var spaIds = spa.Select(it => it.Id).ToList();
  190. if (spaIds.Any())
  191. {
  192. //获取权限授权树
  193. var permissions = _resourceService.PermissionTreeSelector(spa.Select(it => it.Path).ToList());
  194. if (permissions.Count > 0)
  195. permissionTreeSelectors.AddRange(permissions.Select(it => it.PermissionName).ToList());//返回授权树权限名称列表
  196. }
  197. //获取角色资源关系
  198. var relationsRes = await _relationService.GetRelationByCategory(CateGoryConst.RELATION_SYS_ROLE_HAS_RESOURCE);
  199. var menuIds = relationsRes.Where(it => it.ObjectId == input.Id).Select(it => it.TargetId.ToLong()).ToList();
  200. if (menuIds.Any())
  201. {
  202. //获取菜单信息
  203. var menus = await _resourceService.GetResourcesByIds(menuIds, CateGoryConst.RESOURCE_MENU);
  204. //获取权限授权树
  205. var permissions = _resourceService.PermissionTreeSelector(menus.Select(it => it.Path).ToList());
  206. if (permissions.Count > 0)
  207. permissionTreeSelectors.AddRange(permissions.Select(it => it.PermissionName).ToList());//返回授权树权限名称列表
  208. }
  209. return permissionTreeSelectors;
  210. }
  211. /// <inheritdoc />
  212. public async Task<List<SysRole>> GetRoleListByIdList(IdListInput input)
  213. {
  214. var roles = await GetListAsync();
  215. var roleList = roles.Where(it => input.IdList.Contains(it.Id)).ToList();// 获取指定ID的岗位列表
  216. return roleList;
  217. }
  218. /// <inheritdoc />
  219. public async Task<SysRole> Detail(BaseIdInput input)
  220. {
  221. var roles = await GetListAsync();
  222. var role = roles.Where(it => it.Id == input.Id).FirstOrDefault();
  223. return role;
  224. }
  225. #endregion
  226. #region 新增
  227. /// <inheritdoc />
  228. public async Task Add(RoleAddInput input)
  229. {
  230. await CheckInput(input);//检查参数
  231. var sysRole = input.Adapt<SysRole>();//实体转换
  232. if (await InsertAsync(sysRole))//插入数据
  233. await RefreshCache();//刷新缓存
  234. }
  235. #endregion
  236. #region 编辑
  237. /// <inheritdoc />
  238. public async Task Edit(RoleEditInput input)
  239. {
  240. //判断是否超管
  241. if (input.Code == SysRoleConst.SUPER_ADMIN)
  242. throw Oops.Bah("不可编辑超管角色");
  243. await CheckInput(input);//检查参数
  244. var role = await GetFirstAsync(it => it.Id == input.Id);//获取角色
  245. if (role != null)
  246. {
  247. var permissions = new List<SysRelation>();
  248. //如果改了默认数据权限
  249. if (role.DefaultDataScope.ScopeCategory != input.DefaultDataScope.ScopeCategory)
  250. {
  251. //获取角色授权列表
  252. var relations = await _relationService.GetRelationByCategory(CateGoryConst.RELATION_SYS_ROLE_HAS_PERMISSION);
  253. //找到当前角色的
  254. permissions = relations.Where(it => it.ObjectId == input.Id).ToList();
  255. permissions.ForEach(it =>
  256. {
  257. var rolePermission = it.ExtJson.ToJsonEntity<RelationRolePermission>();//扩展信息转实体
  258. //如果表里的数据范围是默认数据范围才更新,已经自定义了的数据范围不更新
  259. if (rolePermission.ScopeCategory == role.DefaultDataScope.ScopeCategory
  260. && Enumerable.SequenceEqual(rolePermission.ScopeDefineOrgIdList, role.DefaultDataScope.ScopeDefineOrgIdList))
  261. {
  262. //重新赋值数据范围
  263. rolePermission.ScopeCategory = input.DefaultDataScope.ScopeCategory;
  264. rolePermission.ScopeDefineOrgIdList = input.DefaultDataScope.ScopeDefineOrgIdList;
  265. it.ExtJson = rolePermission.ToJson();
  266. }
  267. });
  268. }
  269. var sysRole = input.Adapt<SysRole>();//实体转换
  270. //事务
  271. var result = await Tenant.UseTranAsync(async () =>
  272. {
  273. await UpdateAsync(sysRole);//更新角色
  274. if (permissions.Any())//如果有授权权限就更新
  275. await Context.Updateable(permissions).ExecuteCommandAsync();
  276. });
  277. if (result.IsSuccess)//如果成功了
  278. {
  279. await RefreshCache();//刷新缓存
  280. if (permissions.Any())//如果有授权
  281. await _relationService.RefreshCache(CateGoryConst.RELATION_SYS_ROLE_HAS_PERMISSION);//关系表刷新SYS_ROLE_HAS_PERMISSION缓存
  282. await _eventPublisher.PublishAsync(EventSubscriberConst.CLEAR_USER_CACHE, new List<long> { input.Id });//清除角色下用户缓存
  283. }
  284. else
  285. {
  286. //写日志
  287. _logger.LogError(result.ErrorMessage, result.ErrorException);
  288. throw Oops.Oh(ErrorCodeEnum.A0002);
  289. }
  290. }
  291. }
  292. /// <inheritdoc />
  293. public async Task GrantResource(GrantResourceInput input)
  294. {
  295. var allMenus = await _resourceService.GetListByCategory(SysResourceConst.MENU);//获取所有菜单
  296. var spas = await _resourceService.GetListByCategory(SysResourceConst.SPA);
  297. var menuIds = input.GrantInfoList.Select(it => it.MenuId).ToList();//菜单ID
  298. var extJsons = input.GrantInfoList.Select(it => it.ToJson()).ToList();//拓展信息
  299. var relationRoles = new List<SysRelation>();//要添加的角色资源和授权关系表
  300. var sysRole = (await GetListAsync()).Where(it => it.Id == input.Id).FirstOrDefault();//获取角色
  301. if (sysRole != null)
  302. {
  303. #region 角色模块处理
  304. var menusList = allMenus.Where(it => menuIds.Contains(it.Id)).ToList();//获取菜单信息
  305. //获取我的模块信息Id列表
  306. var moduleIds = menusList.Select(it => it.Module.Value).Distinct().ToList();
  307. moduleIds.ForEach(it =>
  308. {
  309. //将角色资源添加到列表
  310. relationRoles.Add(new SysRelation
  311. {
  312. ObjectId = sysRole.Id,
  313. TargetId = it.ToString(),
  314. Category = CateGoryConst.RELATION_SYS_ROLE_HAS_MODULE
  315. });
  316. });
  317. #endregion 角色模块处理
  318. #region 角色资源处理
  319. //遍历菜单列表
  320. for (var i = 0; i < menuIds.Count; i++)
  321. {
  322. //将角色资源添加到列表
  323. relationRoles.Add(new SysRelation
  324. {
  325. ObjectId = sysRole.Id,
  326. TargetId = menuIds[i].ToString(),
  327. Category = CateGoryConst.RELATION_SYS_ROLE_HAS_RESOURCE,
  328. ExtJson = extJsons?[i]
  329. });
  330. }
  331. #endregion 角色资源处理
  332. #region 角色权限处理.
  333. var relationRolePer = new List<SysRelation>();//要添加的角色有哪些权限列表
  334. var defaultDataScope = sysRole.DefaultDataScope;//获取默认数据范围
  335. //获取菜单信息
  336. var menus = allMenus.Where(it => menuIds.Contains(it.Id)).ToList();
  337. menus.AddRange(spas);//单页id添加到列表
  338. if (menus.Count > 0)
  339. {
  340. //获取权限授权树
  341. var permissions = _resourceService.PermissionTreeSelector(menus.Select(it => it.Path).ToList());
  342. permissions.ForEach(it =>
  343. {
  344. //新建角色权限关系
  345. relationRolePer.Add(new SysRelation
  346. {
  347. ObjectId = sysRole.Id,
  348. TargetId = it.ApiRoute,
  349. Category = CateGoryConst.RELATION_SYS_ROLE_HAS_PERMISSION,
  350. ExtJson = new RelationRolePermission
  351. {
  352. ApiUrl = it.ApiRoute,
  353. ScopeCategory = defaultDataScope.ScopeCategory,
  354. ScopeDefineOrgIdList = defaultDataScope.ScopeDefineOrgIdList
  355. }.ToJson()
  356. });
  357. });
  358. }
  359. relationRoles.AddRange(relationRolePer);//合并列表
  360. #endregion 角色权限处理.
  361. #region 保存数据库
  362. //事务
  363. var result = await Tenant.UseTranAsync(async () =>
  364. {
  365. var relationRep = ChangeRepository<DbRepository<SysRelation>>();//切换仓储
  366. //如果不是代码生成,就删除老的
  367. if (!input.IsCodeGen)
  368. await relationRep.DeleteAsync(it => it.ObjectId == sysRole.Id && (it.Category == CateGoryConst.RELATION_SYS_ROLE_HAS_PERMISSION
  369. || it.Category == CateGoryConst.RELATION_SYS_ROLE_HAS_RESOURCE
  370. || it.Category == CateGoryConst.RELATION_SYS_ROLE_HAS_MODULE));
  371. await relationRep.InsertRangeAsync(relationRoles);//添加新的
  372. });
  373. if (result.IsSuccess)//如果成功了
  374. {
  375. await _relationService.RefreshCache(CateGoryConst.RELATION_SYS_ROLE_HAS_RESOURCE);//刷新关系缓存
  376. await _relationService.RefreshCache(CateGoryConst.RELATION_SYS_ROLE_HAS_PERMISSION);//刷新关系缓存
  377. await _eventPublisher.PublishAsync(EventSubscriberConst.CLEAR_USER_CACHE, new List<long> { input.Id });//发送事件清除角色下用户缓存
  378. }
  379. else
  380. {
  381. //写日志
  382. _logger.LogError(result.ErrorMessage, result.ErrorException);
  383. throw Oops.Oh(ErrorCodeEnum.A0003);
  384. }
  385. #endregion 保存数据库
  386. }
  387. }
  388. /// <inheritdoc />
  389. public async Task GrantPermission(GrantPermissionInput input)
  390. {
  391. var sysRole = (await GetListAsync()).Where(it => it.Id == input.Id).FirstOrDefault();//获取角色
  392. if (sysRole != null)
  393. {
  394. var apiUrls = input.GrantInfoList.Select(it => it.ApiUrl).ToList();//apiUrl列表
  395. var extJsons = input.GrantInfoList.Select(it => it.ToJson()).ToList();//拓展信息
  396. await _relationService.SaveRelationBatch(CateGoryConst.RELATION_SYS_ROLE_HAS_PERMISSION, input.Id, apiUrls, extJsons,
  397. true);//添加到数据库
  398. await _eventPublisher.PublishAsync(EventSubscriberConst.CLEAR_USER_CACHE, new List<long> { input.Id });//清除角色下用户缓存
  399. }
  400. }
  401. /// <inheritdoc />
  402. public async Task GrantUser(GrantUserInput input)
  403. {
  404. var sysRelations = new List<SysRelation>();//关系列表
  405. //遍历用户ID
  406. input.GrantInfoList.ForEach(it =>
  407. {
  408. sysRelations.Add(new SysRelation
  409. {
  410. ObjectId = it,
  411. TargetId = input.Id.ToString(),
  412. Category = CateGoryConst.RELATION_SYS_USER_HAS_ROLE
  413. });
  414. });
  415. //事务
  416. var result = await Tenant.UseTranAsync(async () =>
  417. {
  418. var relationRep = ChangeRepository<DbRepository<SysRelation>>();//切换仓储
  419. var targetId = input.Id.ToString();//目标ID转string
  420. await relationRep.DeleteAsync(it => it.TargetId == targetId && it.Category == CateGoryConst.RELATION_SYS_USER_HAS_ROLE);//删除老的
  421. await relationRep.InsertRangeAsync(sysRelations);//添加新的
  422. });
  423. if (result.IsSuccess)//如果成功了
  424. {
  425. await _relationService.RefreshCache(CateGoryConst.RELATION_SYS_USER_HAS_ROLE);//刷新关系表SYS_USER_HAS_ROLE缓存
  426. await _eventPublisher.PublishAsync(EventSubscriberConst.CLEAR_USER_CACHE, new List<long> { input.Id });//清除角色下用户缓存
  427. }
  428. else
  429. {
  430. //写日志
  431. _logger.LogError(result.ErrorMessage, result.ErrorException);
  432. throw Oops.Oh(ErrorCodeEnum.A0003);
  433. }
  434. }
  435. #endregion
  436. #region 删除
  437. /// <inheritdoc />
  438. public async Task Delete(BaseIdListInput input)
  439. {
  440. //获取所有ID
  441. var ids = input.Ids;
  442. if (ids.Count > 0)
  443. {
  444. var sysRoles = await GetListAsync();//获取所有角色
  445. var hasSuperAdmin = sysRoles.Any(it => it.Code == SysRoleConst.SUPER_ADMIN && ids.Contains(it.Id));//判断是否有超级管理员
  446. if (hasSuperAdmin) throw Oops.Bah("不可删除系统内置超管角色");
  447. //数据库是string所以这里转下
  448. var targetIds = ids.Select(it => it.ToString()).ToList();
  449. //定义删除的关系
  450. var delRelations = new List<string>
  451. {
  452. CateGoryConst.RELATION_SYS_ROLE_HAS_RESOURCE,
  453. CateGoryConst.RELATION_SYS_ROLE_HAS_PERMISSION,
  454. CateGoryConst.RELATION_SYS_ROLE_HAS_MODULE
  455. };
  456. //事务
  457. var result = await Tenant.UseTranAsync(async () =>
  458. {
  459. await DeleteByIdsAsync(ids.Cast<object>().ToArray());//删除按钮
  460. var relationRep = ChangeRepository<DbRepository<SysRelation>>();//切换仓储
  461. //删除关系表角色与资源关系,角色与权限关系
  462. await relationRep.DeleteAsync(it => ids.Contains(it.ObjectId) && delRelations.Contains(it.Category));
  463. //删除关系表角色与用户关系
  464. await relationRep.DeleteAsync(it => targetIds.Contains(it.TargetId) && it.Category == CateGoryConst.RELATION_SYS_USER_HAS_ROLE);
  465. });
  466. if (result.IsSuccess)//如果成功了
  467. {
  468. await RefreshCache();//刷新缓存
  469. await _relationService.RefreshCache(CateGoryConst.RELATION_SYS_USER_HAS_ROLE);//关系表刷新SYS_USER_HAS_ROLE缓存
  470. await _relationService.RefreshCache(CateGoryConst.RELATION_SYS_ROLE_HAS_RESOURCE);//关系表刷新Relation_SYS_ROLE_HAS_RESOURCE缓存
  471. await _relationService.RefreshCache(CateGoryConst.RELATION_SYS_ROLE_HAS_PERMISSION);//关系表刷新Relation_SYS_ROLE_HAS_PERMISSION缓存
  472. await _relationService.RefreshCache(CateGoryConst.RELATION_SYS_ROLE_HAS_MODULE);//关系表刷新RELATION_SYS_ROLE_HAS_MODULE缓存
  473. await _eventPublisher.PublishAsync(EventSubscriberConst.CLEAR_USER_CACHE, ids);//清除角色下用户缓存
  474. }
  475. else
  476. {
  477. //写日志
  478. _logger.LogError(result.ErrorMessage, result.ErrorException);
  479. throw Oops.Oh(ErrorCodeEnum.A0002);
  480. }
  481. }
  482. }
  483. /// <inheritdoc />
  484. public async Task RefreshCache()
  485. {
  486. _simpleCacheService.Remove(SystemConst.CACHE_SYS_ROLE);//删除KEY
  487. await GetListAsync();//重新缓存
  488. }
  489. #endregion
  490. #region 方法
  491. /// <summary>
  492. /// 检查输入参数
  493. /// </summary>
  494. /// <param name="sysRole"></param>
  495. private async Task CheckInput(SysRole sysRole)
  496. {
  497. //判断分类
  498. if (sysRole.Category != CateGoryConst.ROLE_GLOBAL && sysRole.Category != CateGoryConst.ROLE_ORG)
  499. throw Oops.Bah($"角色所属分类错误:{sysRole.Category}");
  500. //如果是机构角色orgId不能为空
  501. if (sysRole is { Category: CateGoryConst.ROLE_ORG, OrgId: null })
  502. throw Oops.Bah("orgId不能为空");
  503. if (sysRole.Category == CateGoryConst.ROLE_GLOBAL)//如果是全局
  504. sysRole.OrgId = null;//机构id设null
  505. var sysRoles = await GetListAsync();//获取所有
  506. var repeatName = sysRoles.Any(it => it.OrgId == sysRole.OrgId && it.Name == sysRole.Name && it.Id != sysRole.Id);//是否有重复角色名称
  507. if (repeatName)//如果有
  508. {
  509. if (sysRole.OrgId == null)
  510. throw Oops.Bah($"存在重复的全局角色:{sysRole.Name}");
  511. throw Oops.Bah($"同组织下存在重复的角色:{sysRole.Name}");
  512. }
  513. //如果code没填
  514. if (string.IsNullOrEmpty(sysRole.Code))
  515. {
  516. sysRole.Code = RandomHelper.CreateRandomString(10);//赋值Code
  517. }
  518. else
  519. {
  520. //判断是否有相同的Code
  521. if (sysRoles.Any(it => it.Code == sysRole.Code && it.Id != sysRole.Id))
  522. throw Oops.Bah($"存在重复的编码:{sysRole.Code}");
  523. }
  524. }
  525. #endregion 方法
  526. }