RolesAppService.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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.Runtime.Caching;
  10. using Abp.Runtime.Session;
  11. using Abp.UI;
  12. using Castle.Core.Internal;
  13. using ShwasherSys.Authorization.Permissions;
  14. using ShwasherSys.Authorization.Roles;
  15. using ShwasherSys.Authorization.Users;
  16. using ShwasherSys.BaseSysInfo.Roles.Dto;
  17. using ShwasherSys.BaseSysInfo.States;
  18. using ShwasherSys.Lambda;
  19. using IwbZero.AppServiceBase;
  20. using IwbZero.Auditing;
  21. using IwbZero.Authorization.Permissions;
  22. using IwbZero.Caching;
  23. using IwbZero.IdentityFramework;
  24. namespace ShwasherSys.BaseSysInfo.Roles
  25. {
  26. [AbpAuthorize(PermissionNames.PagesSystemRoles), AuditLog("系统角色", "角色")]
  27. public class RolesAppService : ShwasherAsyncCrudAppService<SysRole, RoleDto, int, PagedRequestDto, RoleCreateDto, RoleUpdateDto>, IRolesAppService
  28. {
  29. private readonly RoleManager _roleManager;
  30. private readonly UserManager _userManager;
  31. private readonly IRepository<SysUser, long> _userRepository;
  32. private readonly IRepository<SysUserRole, long> _userRoleRepository;
  33. private readonly IStatesAppService _stateAppService;
  34. protected override string GetPermissionName { get; set; } = PermissionNames.PagesSystemRolesCreate;
  35. protected override string GetAllPermissionName { get; set; } = PermissionNames.PagesSystemRolesCreate;
  36. protected override string CreatePermissionName { get; set; } = PermissionNames.PagesSystemRolesCreate;
  37. protected override string UpdatePermissionName { get; set; } = PermissionNames.PagesSystemRolesUpdate;
  38. protected override string DeletePermissionName { get; set; } = PermissionNames.PagesSystemRolesDelete;
  39. public RolesAppService(
  40. IRepository<SysRole, int> repository,
  41. RoleManager roleManager,
  42. UserManager userManager,
  43. IStatesAppService stateAppService,
  44. IRepository<SysUser, long> userRepository,
  45. IRepository<SysUserRole, long> userRoleRepository,
  46. ICacheManager cacheManager)
  47. : base(repository)
  48. {
  49. _roleManager = roleManager;
  50. _userManager = userManager;
  51. _stateAppService = stateAppService;
  52. _userRepository = userRepository;
  53. _userRoleRepository = userRoleRepository;
  54. CacheManager = cacheManager;
  55. LocalizationSourceName = ShwasherConsts.LocalizationSourceName;
  56. }
  57. [DisableAuditing]
  58. public List<SelectListItem> GetRoleTypeSelect()
  59. {
  60. var slist = new List<SelectListItem>();
  61. var list = _stateAppService.GetStateList("SysRole", "RoleType");
  62. foreach (var l in list)
  63. {
  64. if (int.TryParse(l.CodeValue, out var roleType))
  65. {
  66. if (roleType <= AbpSession.UserType && AbpSession?.UserName.ToLower() != "admin")
  67. {
  68. continue;
  69. }
  70. slist.Add(new SelectListItem { Text = l.DisplayValue, Value = l.CodeValue });
  71. }
  72. }
  73. return slist;
  74. }
  75. [DisableAuditing]
  76. public async Task<RoleDto> GetRoleByIdAsync(int roleId)
  77. {
  78. var role = await _roleManager.GetRoleByIdAsync(roleId);
  79. return MapToEntityDto(role);
  80. }
  81. [DisableAuditing]
  82. public async Task<PagedResultDto<RoleDtoModel>> GetAllRole(PagedRequestDto input)
  83. {
  84. CheckGetAllPermission();
  85. var query = CreateFilteredQuery(input);
  86. if (AbpSession?.UserName?.ToLower() != "admin")
  87. query = query.Where(a => a.Name.ToLower() != "admin" && a.RoleType > AbpSession.UserType);
  88. if (input.SearchList != null && input.SearchList.Count > 0)
  89. {
  90. List<LambdaObject> objList = new List<LambdaObject>();
  91. foreach (var o in input.SearchList)
  92. {
  93. if (o.KeyWords.IsNullOrEmpty())
  94. continue;
  95. object keyWords = o.KeyWords;
  96. objList.Add(new LambdaObject
  97. {
  98. FieldType = (LambdaFieldType)o.FieldType,
  99. FieldName = o.KeyField,
  100. FieldValue = keyWords,
  101. ExpType = (LambdaExpType)o.ExpType
  102. });
  103. }
  104. var exp = objList.GetExp<SysRole>();
  105. query = query.Where(exp);
  106. }
  107. var totalCount = await AsyncQueryableExecuter.CountAsync(query);
  108. query = ApplySorting(query, input);
  109. query = ApplyPaging(query, input);
  110. var entities = await AsyncQueryableExecuter.ToListAsync(query);
  111. var dtos = new PagedResultDto<RoleDtoModel>(
  112. totalCount,
  113. entities.Select(a => new RoleDtoModel()
  114. {
  115. Id = a.Id,
  116. Name = a.Name,
  117. RoleDisplayName = a.RoleDisplayName,
  118. RoleType = a.RoleType,
  119. RoleTypeName = _stateAppService.GetDisplayValue("SysRole", "RoleType", a.RoleType + ""),
  120. Description = a.Description,
  121. IsStatic = a.IsStatic,
  122. LastModificationTime = a.LastModificationTime,
  123. LastModifierUserName = a.LastModifierUser?.UserName ?? ""
  124. }).ToList()
  125. );
  126. return dtos;
  127. }
  128. public override async Task<RoleDto> Create(RoleCreateDto input)
  129. {
  130. var role = ObjectMapper.Map<SysRole>(input);
  131. CheckCreatePermission();
  132. //var result= await _roleManager.CheckDuplicateRoleNameAsync(input.Id, input.Name, input.RoleDisplayName);
  133. //if (!result.Succeeded)
  134. //{
  135. // CheckErrors(result);
  136. //}
  137. CheckErrors(await _roleManager.CreateAsync(role));
  138. await CurrentUnitOfWork.SaveChangesAsync();
  139. return new RoleDto();
  140. }
  141. public override async Task<RoleDto> Update(RoleUpdateDto input)
  142. {
  143. if (input.RoleType <= AbpSession.UserType && AbpSession?.UserName.ToLower() != "admin")
  144. {
  145. CheckErrors(IwbIdentityResult.Failed("没有此角色类型的权限,请检查后再操作!"));
  146. }
  147. CheckUpdatePermission();
  148. var role = await _roleManager.GetRoleByIdAsync(input.Id);
  149. MapToEntity(input, role);
  150. CheckErrors(await _roleManager.UpdateAsync(role));
  151. //var result= await _roleManager.CheckDuplicateRoleNameAsync(input.Id, input.Name, input.RoleDisplayName);
  152. //if (!result.Succeeded)
  153. //{
  154. // CheckErrors(result);
  155. //}
  156. //var entity = await GetEntityByIdAsync(input.Id);
  157. //MapToEntity(input, entity);
  158. //await CurrentUnitOfWork.SaveChangesAsync();
  159. return new RoleDto();
  160. }
  161. public override async Task Delete(EntityDto<int> input)
  162. {
  163. CheckDeletePermission();
  164. var role = await _roleManager.FindByIdAsync(input.Id);
  165. if (role.IsStatic)
  166. {
  167. throw new UserFriendlyException("CannotDeleteAStaticRole");
  168. }
  169. var users = await GetUsersInRoleAsync(role.Name);
  170. foreach (var user in users)
  171. {
  172. CheckErrors(await _userManager.RemoveFromRoleAsync(user, role.Name));
  173. }
  174. CheckErrors(await _roleManager.DeleteAsync(role));
  175. }
  176. [AbpAuthorize(PermissionNames.PagesSystemRolesAuth), AuditLog("角色权限配置")]
  177. public async Task Auth(AuthDto input)
  178. {
  179. var role = await _roleManager.GetRoleByIdAsync(input.Id);
  180. if (AbpSession?.UserType == 1 && AbpSession?.UserName.ToLower() != "admin")
  181. {
  182. CheckErrors(IwbIdentityResult.Failed("超级管理员权限不能修改"));
  183. }
  184. var grantedPermissions = new List<Permission>();
  185. if (input.PermissionNames != null && input.PermissionNames.Any())
  186. {
  187. grantedPermissions = PermissionManager
  188. .GetAllPermissions()
  189. .Where(p => input.PermissionNames.Contains(p.Name))
  190. .ToList();
  191. }
  192. await _roleManager.SetGrantedPermissionsAsync(role, grantedPermissions);
  193. CacheManager.GetCache(IwbRolePermissionCacheItem.CacheStoreName).Remove(input.Id + "@" + (AbpSession.GetTenantId()));
  194. }
  195. private Task<List<long>> GetUsersInRoleAsync(string roleName)
  196. {
  197. var users = (from user in _userRepository.GetAll()
  198. join userRole in _userRoleRepository.GetAll() on user.Id equals userRole.UserId
  199. join role in Repository.GetAll() on userRole.RoleId equals role.Id
  200. where role.Name == roleName
  201. select user.Id).Distinct().ToList();
  202. return Task.FromResult(users);
  203. }
  204. [DisableAuditing]
  205. public async Task<bool> IsGrantedAsync(int roleId, string permissionNmae)
  206. {
  207. return await _roleManager.IsGrantedAsync(roleId, permissionNmae);
  208. }
  209. [DisableAuditing]
  210. public Task<ListResultDto<PermissionDto>> GetAllPermissions()
  211. {
  212. var permissions = PermissionManager.GetAllPermissions();
  213. return Task.FromResult(new ListResultDto<PermissionDto>(
  214. ObjectMapper.Map<List<PermissionDto>>(permissions)
  215. ));
  216. }
  217. //protected override IQueryable<SysRole> CreateFilteredQuery(PagedRequestDto input)
  218. //{
  219. // return Repository.GetAllIncluding(x => x.Permissions);
  220. //}
  221. //protected override Task<SysRole> GetEntityByIdAsync(int id)
  222. //{
  223. // var role = Repository.GetAllIncluding(x => x.Permissions).FirstOrDefault(x => x.Id == id);
  224. // return Task.FromResult(role);
  225. //}
  226. protected override IQueryable<SysRole> ApplySorting(IQueryable<SysRole> query, PagedRequestDto input)
  227. {
  228. return query.OrderBy(r => r.RoleDisplayName);
  229. }
  230. }
  231. }