平安校园
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.
 
 
 
 
 
 

586 lines
25 KiB

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