RolesAppService.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System.Threading.Tasks;
  4. using System.Web.Mvc;
  5. using Abp.Application.Services.Dto;
  6. using Abp.Auditing;
  7. using Abp.Authorization;
  8. using Abp.Domain.Repositories;
  9. using Abp.MultiTenancy;
  10. using Abp.Runtime.Caching;
  11. using WePlatform.Authorization;
  12. using WePlatform.Authorization.Roles;
  13. using WePlatform.Authorization.Users;
  14. using WePlatform.BaseInfo;
  15. using WePlatform.BaseSystem.Roles.Dto;
  16. using WePlatform.BaseSystem.Users.Dto;
  17. using WePlatform.Configuration;
  18. using IwbZero.AppServiceBase;
  19. using IwbZero.Auditing;
  20. using IwbZero.Authorization.Base.Users;
  21. namespace WePlatform.BaseSystem.Roles
  22. {
  23. [AbpAuthorize(PermissionNames.PagesSystemMgRoleMg), AuditLog("系统角色", "角色")]
  24. public class RolesAppService : IwbAsyncCrudAppService<Role, RoleDto, int, IwbPagedRequestDto, RoleCreateDto, RoleUpdateDto>, IRolesAppService
  25. {
  26. private RoleManager RoleManager { get; }
  27. private IRepository<User, long> UserRepository { get; }
  28. private IRepository<UserRole, long> UserRoleRepository { get; }
  29. private IRepository<SysFunction> FunRepository { get; }
  30. public RolesAppService(
  31. IRepository<Role, int> repository,
  32. RoleManager roleManager,
  33. UserManager userManager,
  34. IRepository<User, long> userRepository,
  35. IRepository<UserRole, long> userRoleRepository,
  36. ICacheManager cacheManager, IRepository<SysFunction> funRepository)
  37. : base(repository)
  38. {
  39. RoleManager = roleManager;
  40. UserManager = userManager;
  41. UserRepository = userRepository;
  42. UserRoleRepository = userRoleRepository;
  43. FunRepository = funRepository;
  44. CacheManager = cacheManager;
  45. }
  46. [DisableAuditing]
  47. public async Task<List<SelectListItem>> GetRoleTypeSelect()
  48. {
  49. var sList = new List<SelectListItem>();
  50. var list = await StatesManager.GetStateListAsync("SysRole", "RoleType");
  51. foreach (var l in list)
  52. {
  53. if (int.TryParse(l.CodeValue, out var roleType))
  54. {
  55. if (roleType <= AbpSession.UserType && AbpSession?.UserName.ToLower() != "admin")
  56. {
  57. continue;
  58. }
  59. sList.Add(new SelectListItem { Text = l.DisplayValue, Value = l.CodeValue });
  60. }
  61. }
  62. return sList;
  63. }
  64. #region CURD
  65. [DisableAuditing]
  66. public async Task<RoleDto> GetRoleByIdAsync(int roleId)
  67. {
  68. var role = await RoleManager.GetRoleByIdAsync(roleId);
  69. return MapToEntityDto(role);
  70. }
  71. [DisableAuditing]
  72. [AbpAuthorize(PermissionNames.PagesSystemMgRoleMgQuery)]
  73. public override async Task<PagedResultDto<RoleDto>> GetAll(IwbPagedRequestDto input)
  74. {
  75. var query = CreateFilteredQuery(input);
  76. if (AbpSession.UserName != UserBase.AdminUserName && !(IwbConsts.MultiTenancyEnabled && AbpSession.MultiTenancySide.HasFlag(MultiTenancySides.Host)))
  77. query = query.Where(a => a.Name != UserBase.AdminUserName &&
  78. (a.RoleType > AbpSession.UserType) &&
  79. (AbpSession.AccountType == AccountTypeDefinition.System || a.AccountType == AbpSession.AccountType));
  80. var totalCount = await AsyncQueryableExecuter.CountAsync(query);
  81. query = ApplySorting(query, input);
  82. query = ApplyPaging(query, input);
  83. var entities = await AsyncQueryableExecuter.ToListAsync(query);
  84. return new PagedResultDto<RoleDto>(totalCount, entities.Select(MapToEntityDto).ToList());
  85. }
  86. [AbpAuthorize(PermissionNames.PagesSystemMgRoleMgCreate)]
  87. public override async Task Create(RoleCreateDto input)
  88. {
  89. if (input.RoleType <= AbpSession.UserType && AbpSession.UserName != UserBase.AdminUserName && AbpSession.UserName != UserBase.SystemUserName)
  90. {
  91. ThrowError(IwbLanguageMessage.NoPermissionUpdateRoleType);
  92. }
  93. var role = ObjectMapper.Map<Role>(input);
  94. role.SetNormalizedName();
  95. CheckErrors(await RoleManager.CreateAsync(role));
  96. await CurrentUnitOfWork.SaveChangesAsync();
  97. }
  98. [AbpAuthorize(PermissionNames.PagesSystemMgRoleMgUpdate)]
  99. public override async Task Update(RoleUpdateDto input)
  100. {
  101. if (input.RoleType <= AbpSession.UserType && AbpSession.UserName != UserBase.AdminUserName && AbpSession.UserName != UserBase.SystemUserName)
  102. {
  103. ThrowError(IwbLanguageMessage.NoPermissionUpdateRoleType);
  104. }
  105. var role = await RoleManager.GetRoleByIdAsync(input.Id);
  106. MapToEntity(input, role);
  107. CheckErrors(await RoleManager.UpdateAsync(role));
  108. }
  109. [AbpAuthorize(PermissionNames.PagesSystemMgRoleMgDelete)]
  110. public override async Task Delete(EntityDto<int> input)
  111. {
  112. var role = await RoleManager.FindByIdAsync(input.Id);
  113. if (role.IsStatic) ThrowError(IwbLanguageMessage.CanNotDeleteRole);
  114. var users = await GetUsersInRoleAsync(role.NormalizedName);
  115. foreach (var user in users)
  116. {
  117. CheckErrors(await UserManager.RemoveFromRoleAsync(user, role.NormalizedName));
  118. }
  119. CheckErrors(await RoleManager.DeleteAsync(role));
  120. }
  121. #endregion
  122. #region Auth
  123. [AbpAuthorize(PermissionNames.PagesSystemMgRoleMgAuth), AuditLog("角色权限配置")]
  124. public async Task Auth(AuthDto input)
  125. {
  126. var role = await RoleManager.GetRoleByIdAsync(input.Id);
  127. var grantedPermissions = new List<Permission>();
  128. if (input.PermissionNames != null && input.PermissionNames.Any())
  129. {
  130. grantedPermissions = PermissionManager
  131. .GetAllPermissions()
  132. .Where(p => input.PermissionNames.Contains(p.Name))
  133. .ToList();
  134. }
  135. await RoleManager.SetGrantedPermissionsAsync(role, grantedPermissions);
  136. }
  137. /// <summary>
  138. /// 角色权限
  139. /// </summary>
  140. /// <param name="roleId"></param>
  141. /// <returns></returns>
  142. [AbpAuthorize(PermissionNames.PagesSystemMgRoleMgAuth), DisableAuditing]
  143. public async Task<PermissionAuthDto> GetPermissions(int roleId)
  144. {
  145. var permissions = (await GetAllPermissions()).Items;
  146. List<PermissionDto> currentPerms = new List<PermissionDto>();
  147. if (AbpSession.UserName == UserBase.AdminUserName)
  148. {
  149. currentPerms.AddRange(permissions);
  150. }
  151. else
  152. {
  153. foreach (var perm in permissions)
  154. {
  155. if (await PermissionChecker.IsGrantedAsync(perm.Name))
  156. currentPerms.Add(perm);
  157. }
  158. }
  159. var permission = permissions.FirstOrDefault(a => a.Name == PermissionNames.Pages);
  160. var model = new PermissionAuthDto();
  161. if (permission != null)
  162. {
  163. var fun = await CacheManager.GetCache(IwbCacheNames.FunctionCache)
  164. .GetAsync(permission.Name, () => FunRepository.FirstOrDefaultAsync(a => a.PermissionName == permission.Name));
  165. model.Name = permission.Name;
  166. model.IsAuth = await RoleManager.IsGrantedAsync(roleId, permission.Name);
  167. model.PermDisplayName = fun.FunctionName;
  168. model.Sort = fun.Sort;
  169. model.Icon = fun.Icon;
  170. model.IsOpen = fun.Depth < 2;
  171. model.Children = await GetPermissionTree(permission.Name, currentPerms, roleId);
  172. }
  173. return model;
  174. }
  175. /// <summary>
  176. /// 获取角色权限树
  177. /// </summary>
  178. /// <param name="parentName"></param>
  179. /// <param name="permissions"></param>
  180. /// <param name="userId"></param>
  181. /// <returns></returns>
  182. private async Task<List<PermissionAuthDto>> GetPermissionTree(string parentName, List<PermissionDto> permissions, int userId)
  183. {
  184. var parentPerms = permissions.Where(a => a.Parent?.Name == parentName).OrderBy(a => a.Sort).ToList();
  185. var list = new List<PermissionAuthDto>();
  186. if (parentPerms.Any())
  187. {
  188. foreach (var p in parentPerms)
  189. {
  190. var fun = await CacheManager.GetCache(IwbCacheNames.FunctionCache)
  191. .GetAsync(p.Name, () => FunRepository.FirstOrDefaultAsync(a => a.PermissionName == p.Name));
  192. var model = new PermissionAuthDto
  193. {
  194. Name = p.Name,
  195. IsAuth = await RoleManager.IsGrantedAsync(userId, p.Name),
  196. PermDisplayName = fun.FunctionName,
  197. Sort = fun.Sort,
  198. Icon = fun.Icon,
  199. IsOpen = fun.Depth < 2,
  200. Children = await GetPermissionTree(p.Name, permissions, userId)
  201. };
  202. list.Add(model);
  203. }
  204. }
  205. return list;
  206. }
  207. [DisableAuditing]
  208. private Task<ListResultDto<PermissionDto>> GetAllPermissions()
  209. {
  210. var permissions = PermissionManager.GetAllPermissions();
  211. return Task.FromResult(new ListResultDto<PermissionDto>(
  212. ObjectMapper.Map<List<PermissionDto>>(permissions)
  213. ));
  214. }
  215. #endregion
  216. public Task<List<long>> GetUsersInRoleAsync(string roleName)
  217. {
  218. var users = (from user in UserRepository.GetAll()
  219. join userRole in UserRoleRepository.GetAll() on user.Id equals userRole.UserId
  220. join role in Repository.GetAll() on userRole.RoleId equals role.Id
  221. where role.Name == roleName
  222. select user.Id).Distinct().ToList();
  223. return Task.FromResult(users);
  224. }
  225. protected override IQueryable<Role> ApplySorting(IQueryable<Role> query, IwbPagedRequestDto input)
  226. {
  227. return query.OrderBy(r => r.DisplayName);
  228. }
  229. }
  230. }