| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253 |
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using System.Web.Mvc;
- using Abp.Application.Services.Dto;
- using Abp.Auditing;
- using Abp.Authorization;
- using Abp.Domain.Repositories;
- using Abp.MultiTenancy;
- using Abp.Runtime.Caching;
- using WePlatform.Authorization;
- using WePlatform.Authorization.Roles;
- using WePlatform.Authorization.Users;
- using WePlatform.BaseInfo;
- using WePlatform.BaseSystem.Roles.Dto;
- using WePlatform.BaseSystem.Users.Dto;
- using WePlatform.Configuration;
- using IwbZero.AppServiceBase;
- using IwbZero.Auditing;
- using IwbZero.Authorization.Base.Users;
- namespace WePlatform.BaseSystem.Roles
- {
- [AbpAuthorize(PermissionNames.PagesSystemMgRoleMg), AuditLog("系统角色", "角色")]
- public class RolesAppService : IwbAsyncCrudAppService<Role, RoleDto, int, IwbPagedRequestDto, RoleCreateDto, RoleUpdateDto>, IRolesAppService
- {
- private RoleManager RoleManager { get; }
- private IRepository<User, long> UserRepository { get; }
- private IRepository<UserRole, long> UserRoleRepository { get; }
- private IRepository<SysFunction> FunRepository { get; }
- public RolesAppService(
- IRepository<Role, int> repository,
- RoleManager roleManager,
- UserManager userManager,
- IRepository<User, long> userRepository,
- IRepository<UserRole, long> userRoleRepository,
- ICacheManager cacheManager, IRepository<SysFunction> funRepository)
- : base(repository)
- {
- RoleManager = roleManager;
- UserManager = userManager;
- UserRepository = userRepository;
- UserRoleRepository = userRoleRepository;
- FunRepository = funRepository;
- CacheManager = cacheManager;
- }
- [DisableAuditing]
- public async Task<List<SelectListItem>> GetRoleTypeSelect()
- {
- var sList = new List<SelectListItem>();
- var list = await StatesManager.GetStateListAsync("SysRole", "RoleType");
- foreach (var l in list)
- {
- if (int.TryParse(l.CodeValue, out var roleType))
- {
- if (roleType <= AbpSession.UserType && AbpSession?.UserName.ToLower() != "admin")
- {
- continue;
- }
- sList.Add(new SelectListItem { Text = l.DisplayValue, Value = l.CodeValue });
- }
- }
- return sList;
- }
- #region CURD
- [DisableAuditing]
- public async Task<RoleDto> GetRoleByIdAsync(int roleId)
- {
- var role = await RoleManager.GetRoleByIdAsync(roleId);
- return MapToEntityDto(role);
- }
- [DisableAuditing]
- [AbpAuthorize(PermissionNames.PagesSystemMgRoleMgQuery)]
- public override async Task<PagedResultDto<RoleDto>> GetAll(IwbPagedRequestDto input)
- {
- var query = CreateFilteredQuery(input);
- if (AbpSession.UserName != UserBase.AdminUserName && !(IwbConsts.MultiTenancyEnabled && AbpSession.MultiTenancySide.HasFlag(MultiTenancySides.Host)))
- query = query.Where(a => a.Name != UserBase.AdminUserName &&
- (a.RoleType > AbpSession.UserType) &&
- (AbpSession.AccountType == AccountTypeDefinition.System || a.AccountType == AbpSession.AccountType));
- var totalCount = await AsyncQueryableExecuter.CountAsync(query);
- query = ApplySorting(query, input);
- query = ApplyPaging(query, input);
- var entities = await AsyncQueryableExecuter.ToListAsync(query);
- return new PagedResultDto<RoleDto>(totalCount, entities.Select(MapToEntityDto).ToList());
- }
- [AbpAuthorize(PermissionNames.PagesSystemMgRoleMgCreate)]
- public override async Task Create(RoleCreateDto input)
- {
- if (input.RoleType <= AbpSession.UserType && AbpSession.UserName != UserBase.AdminUserName && AbpSession.UserName != UserBase.SystemUserName)
- {
- ThrowError(IwbLanguageMessage.NoPermissionUpdateRoleType);
- }
- var role = ObjectMapper.Map<Role>(input);
- role.SetNormalizedName();
- CheckErrors(await RoleManager.CreateAsync(role));
- await CurrentUnitOfWork.SaveChangesAsync();
- }
- [AbpAuthorize(PermissionNames.PagesSystemMgRoleMgUpdate)]
- public override async Task Update(RoleUpdateDto input)
- {
- if (input.RoleType <= AbpSession.UserType && AbpSession.UserName != UserBase.AdminUserName && AbpSession.UserName != UserBase.SystemUserName)
- {
- ThrowError(IwbLanguageMessage.NoPermissionUpdateRoleType);
- }
- var role = await RoleManager.GetRoleByIdAsync(input.Id);
- MapToEntity(input, role);
- CheckErrors(await RoleManager.UpdateAsync(role));
- }
- [AbpAuthorize(PermissionNames.PagesSystemMgRoleMgDelete)]
- public override async Task Delete(EntityDto<int> input)
- {
- var role = await RoleManager.FindByIdAsync(input.Id);
- if (role.IsStatic) ThrowError(IwbLanguageMessage.CanNotDeleteRole);
- var users = await GetUsersInRoleAsync(role.NormalizedName);
- foreach (var user in users)
- {
- CheckErrors(await UserManager.RemoveFromRoleAsync(user, role.NormalizedName));
- }
- CheckErrors(await RoleManager.DeleteAsync(role));
- }
- #endregion
- #region Auth
- [AbpAuthorize(PermissionNames.PagesSystemMgRoleMgAuth), AuditLog("角色权限配置")]
- public async Task Auth(AuthDto input)
- {
- var role = await RoleManager.GetRoleByIdAsync(input.Id);
- var grantedPermissions = new List<Permission>();
- if (input.PermissionNames != null && input.PermissionNames.Any())
- {
- grantedPermissions = PermissionManager
- .GetAllPermissions()
- .Where(p => input.PermissionNames.Contains(p.Name))
- .ToList();
- }
- await RoleManager.SetGrantedPermissionsAsync(role, grantedPermissions);
- }
- /// <summary>
- /// 角色权限
- /// </summary>
- /// <param name="roleId"></param>
- /// <returns></returns>
- [AbpAuthorize(PermissionNames.PagesSystemMgRoleMgAuth), DisableAuditing]
- public async Task<PermissionAuthDto> GetPermissions(int roleId)
- {
- var permissions = (await GetAllPermissions()).Items;
- List<PermissionDto> currentPerms = new List<PermissionDto>();
- if (AbpSession.UserName == UserBase.AdminUserName)
- {
- currentPerms.AddRange(permissions);
- }
- else
- {
- foreach (var perm in permissions)
- {
- if (await PermissionChecker.IsGrantedAsync(perm.Name))
- currentPerms.Add(perm);
- }
- }
- var permission = permissions.FirstOrDefault(a => a.Name == PermissionNames.Pages);
- var model = new PermissionAuthDto();
- if (permission != null)
- {
- var fun = await CacheManager.GetCache(IwbCacheNames.FunctionCache)
- .GetAsync(permission.Name, () => FunRepository.FirstOrDefaultAsync(a => a.PermissionName == permission.Name));
- model.Name = permission.Name;
- model.IsAuth = await RoleManager.IsGrantedAsync(roleId, permission.Name);
- model.PermDisplayName = fun.FunctionName;
- model.Sort = fun.Sort;
- model.Icon = fun.Icon;
- model.IsOpen = fun.Depth < 2;
- model.Children = await GetPermissionTree(permission.Name, currentPerms, roleId);
- }
- return model;
- }
- /// <summary>
- /// 获取角色权限树
- /// </summary>
- /// <param name="parentName"></param>
- /// <param name="permissions"></param>
- /// <param name="userId"></param>
- /// <returns></returns>
- private async Task<List<PermissionAuthDto>> GetPermissionTree(string parentName, List<PermissionDto> permissions, int userId)
- {
- var parentPerms = permissions.Where(a => a.Parent?.Name == parentName).OrderBy(a => a.Sort).ToList();
- var list = new List<PermissionAuthDto>();
- if (parentPerms.Any())
- {
- foreach (var p in parentPerms)
- {
- var fun = await CacheManager.GetCache(IwbCacheNames.FunctionCache)
- .GetAsync(p.Name, () => FunRepository.FirstOrDefaultAsync(a => a.PermissionName == p.Name));
- var model = new PermissionAuthDto
- {
- Name = p.Name,
- IsAuth = await RoleManager.IsGrantedAsync(userId, p.Name),
- PermDisplayName = fun.FunctionName,
- Sort = fun.Sort,
- Icon = fun.Icon,
- IsOpen = fun.Depth < 2,
- Children = await GetPermissionTree(p.Name, permissions, userId)
- };
- list.Add(model);
- }
- }
- return list;
- }
- [DisableAuditing]
- private Task<ListResultDto<PermissionDto>> GetAllPermissions()
- {
- var permissions = PermissionManager.GetAllPermissions();
- return Task.FromResult(new ListResultDto<PermissionDto>(
- ObjectMapper.Map<List<PermissionDto>>(permissions)
- ));
- }
- #endregion
- public Task<List<long>> GetUsersInRoleAsync(string roleName)
- {
- var users = (from user in UserRepository.GetAll()
- join userRole in UserRoleRepository.GetAll() on user.Id equals userRole.UserId
- join role in Repository.GetAll() on userRole.RoleId equals role.Id
- where role.Name == roleName
- select user.Id).Distinct().ToList();
- return Task.FromResult(users);
- }
- protected override IQueryable<Role> ApplySorting(IQueryable<Role> query, IwbPagedRequestDto input)
- {
- return query.OrderBy(r => r.DisplayName);
- }
- }
- }
|