using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web.Mvc; using System.Web.WebPages; using Abp.Application.Services.Dto; using Abp.Auditing; using Abp.Authorization; using Abp.Domain.Repositories; using Abp.Localization; using Abp.MultiTenancy; using Abp.Runtime.Caching; using Abp.Runtime.Session; using WePlatform.Authorization; using WePlatform.Authorization.Users; using WePlatform.BaseInfo; using WePlatform.BaseSystem.Roles.Dto; using WePlatform.BaseSystem.Users.Dto; using WePlatform.CommonManager.States; using WePlatform.Configuration; using IwbZero; using IwbZero.AppServiceBase; using IwbZero.Auditing; using IwbZero.Authorization.Base; using IwbZero.Authorization.Base.Users; using Microsoft.AspNet.Identity; namespace WePlatform.BaseSystem.Users { [AbpAuthorize, AuditLog("系统用户", "用户")] public class UsersAppService : IwbAsyncCrudAppService, IUsersAppService { private IRepository FunRepository { get; } private LogInManager LogInManager { get; } public UsersAppService( IRepository repository, UserManager userManager, ICacheManager cacheManager, LogInManager logInManager, IRepository funRepository) : base(repository) { UserManager = userManager; LogInManager = logInManager; FunRepository = funRepository; CacheManager = cacheManager; } protected override string KeyExistMessage => string.Format(L(IwbLanguageMessage.KeyExistMessageFormatter), L("user")); protected override string KeyNotExistMessage => string.Format(L(IwbLanguageMessage.KeyNotExistMessageFormatter), L("user")); #region Select [DisableAuditing] public List GetUserTypeSelect() { var sList = new List(); var list = StatesManager.GetStateList("UserRole", "UserRoleType"); foreach (var l in list) { if (int.TryParse(l.CodeValue, out var userType)) { if (userType <= AbpSession.UserType && AbpSession.UserName != UserBase.AdminUserName) { continue; } sList.Add(new SelectListItem { Text = l.DisplayValue, Value = l.CodeValue }); } } return sList; } #endregion #region Roles [DisableAuditing] public async Task GetUserRoles(long userId) { var roleList = await UserManager.GetRolesAsync(userId); string[] roles = roleList.ToArray(); return roles; } //[DisableAuditing] //public async Task> GetRoles() //{ // var accountType = AbpSession.AccountType; // var roles = await RoleRepository.GetAllListAsync(a => // (AbpSession.UserName == UserBase.AdminUserName || a.RoleType > AbpSession.UserType) && // (accountType == 1 || a.AccountType == accountType)); // return new ListResultDto(ObjectMapper.Map>(roles)); //} //[DisableAuditing] //public List GetRoleSelects() //{ // var accountType = AbpSession.AccountType; // var sList = new List(); // var list = RoleRepository.GetAllList(a => // (AbpSession.UserName == UserBase.AdminUserName || a.RoleType > AbpSession.UserType) && // (accountType == AccountTypeDefinition.System || a.AccountType == accountType)); // foreach (var l in list) // { // sList.Add(new SelectListItem { Text = l.DisplayName, Value = l.Name }); // } // return sList; //} #endregion #region Password [AbpAuthorize, AuditLog("修改密码")] public async Task ChangePassword(ChangePasswordDto input) { if (AbpSession.UserId == null) { ThrowError(IwbLanguageMessage.UserSessionTimeout); } var user = await UserManager.GetUserByIdAsync(AbpSession.UserId ?? 0); var loginAsync = await LogInManager.LoginAsync(user.UserName, input.CurrentPassword, shouldLockout: false); if (loginAsync.Result != IwbLoginResultType.Success) { ThrowError(IwbLanguageMessage.PasswordError); } //if (!new Regex(AccountAppService.PasswordRegex).IsMatch(input.NewPassword)) //{ // throw new UserFriendlyException("Passwords must be at least 8 characters, contain a lowercase, uppercase, and number."); //} user.Password = new PasswordHasher().HashPassword(input.NewPassword); await Repository.UpdateAsync(user); return true; } [AbpAuthorize(PermissionNames.PagesSystemMgUserMgResetPassword), AuditLog("重置密码")] public async Task ResetPassword(EntityDto input) { var user = await UserManager.GetUserByIdAsync(input.Id); if (user == null) { CheckErrors(NotExistMessage); return; } if (user.UserType <= AbpSession.UserType && AbpSession.UserName != UserBase.AdminUserName && AbpSession.UserName != UserBase.SystemUserName) { ThrowError(IwbLanguageMessage.NoPermissionUpdateUser); } var password = await SettingManager.GetSettingValueAsync(IwbSettingNames.UserDefaultPassword); user.Password = new PasswordHasher().HashPassword(password); await Repository.UpdateAsync(user); } [AbpAuthorize(PermissionNames.PagesSystemMgUserMgResetLock), AuditLog("解除登陆锁定")] public async Task ResetLock(EntityDto input) { var user = await UserManager.GetUserByIdAsync(input.Id); if (user == null) { CheckErrors(NotExistMessage); return; } if (user.UserType <= AbpSession.UserType && AbpSession.UserName != UserBase.AdminUserName && AbpSession.UserName != UserBase.SystemUserName) { ThrowError(IwbLanguageMessage.NoPermissionUpdateUser); } await UserManager.UnLockUserLogin(user); } #endregion #region Auth [AbpAuthorize(PermissionNames.PagesSystemMgUserMgAuth), AuditLog("用户权限配置")] public async Task Auth(AuthDto input) { var user = await UserManager.GetUserByIdAsync(input.Id); if (user.UserName == UserBase.AdminUserName) { ThrowError(IwbLanguageMessage.CanNotUpdateAdminPermission); } var grantedPermissions = new List(); if (input.PermissionNames != null && input.PermissionNames.Any()) { grantedPermissions = PermissionManager .GetAllPermissions() .Where(p => input.PermissionNames.Contains(p.Name)) .ToList(); } await UserManager.SetGrantedPermissionsAsync(user, grantedPermissions); } /// /// 用户权限 /// /// /// [DisableAuditing] [AbpAuthorize(PermissionNames.PagesSystemMgUserMgAuth)] public async Task GetPermissions(long userId) { var permissions = (await GetAllPermissions()).Items; List currentPerms = new List(); 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 UserManager.IsGrantedAsync(userId, permission.Name, true); model.PermDisplayName = fun.FunctionName; model.Sort = fun.Sort; model.Icon = fun.Icon; model.IsOpen = fun.Depth < 2; model.Children = await GetPermissionTree(permission.Name, currentPerms, userId); } return model; } /// /// 获取用户权限树 /// /// /// /// /// private async Task> GetPermissionTree(string parentName, List permissions, long userId) { var parentPerms = permissions.Where(a => a.Parent?.Name == parentName).OrderBy(a => a.Sort).ToList(); var list = new List(); 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 UserManager.IsGrantedAsync(userId, p.Name, true), 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> GetAllPermissions() { var permissions = PermissionManager.GetAllPermissions(); return Task.FromResult(new ListResultDto( ObjectMapper.Map>(permissions) )); } #endregion #region CURD #region GET #region Get public async Task GetUser(EntityDto input) { var user = await GetEntityById(input.Id); var userRoles = await UserManager.GetRolesAsync(user.Id); var dto = MapToEntityDto(user); dto.Roles = userRoles.Select(ur => ur).ToArray(); return dto; } #endregion #endregion [DisableAuditing] [AbpAuthorize(PermissionNames.PagesSystemMgUserMgQuery)] public override async Task> GetAll(IwbPagedRequestDto input) { IQueryable query = CreateFilteredQuery(input); // ReSharper disable once RedundantLogicalConditionalExpressionOperand if (AbpSession.UserName != UserBase.AdminUserName && !(IwbConsts.MultiTenancyEnabled && AbpSession.MultiTenancySide.HasFlag(MultiTenancySides.Host))) query = query.Where(a => a.UserName != UserBase.AdminUserName && (a.UserType > 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(totalCount, entities.Select(MapToEntityDto).ToList()); } protected override IQueryable ApplySorting(IQueryable query, IwbPagedRequestDto input) { query = base.ApplySorting(query, input); //return query.OrderBy(r => r.UserType).ThenBy(a=>a.UserName); return query; } [AbpAuthorize(PermissionNames.PagesSystemMgUserMgCreate)] public override async Task Create(UserCreateDto input) { if (input.UserType <= AbpSession.UserType && AbpSession.UserName != UserBase.AdminUserName && AbpSession.UserName != UserBase.SystemUserName) { ThrowError(IwbLanguageMessage.NoPermissionUpdateUserType); } var user = ObjectMapper.Map(input); user.UserName = await BindAccount(input.AccountType, input.AccountNo); user.TenantId = AbpSession.TenantId; user.IsEmailConfirmed = true; var password = await SettingManager.GetSettingValueAsync(IwbSettingNames.UserDefaultPassword); CheckErrors(await UserManager.CreateAsync(user, password)); if (!input.RoleNames.IsEmpty()) { var roles = input.RoleNames.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (roles.Any()) { CheckErrors(await UserManager.SetRoles(user, roles)); } } await CurrentUnitOfWork.SaveChangesAsync(); } [AbpAuthorize(PermissionNames.PagesSystemMgUserMgUpdate)] public override async Task Update(UserUpdateDto input) { if (AbpSession.UserName != UserBase.AdminUserName && AbpSession.UserName != UserBase.SystemUserName) { var oldUser = await GetEntityById(input.Id); if (oldUser?.UserType <= AbpSession.UserType) ThrowError(IwbLanguageMessage.NoPermissionUpdateUser); if (input.UserType <= AbpSession.UserType) ThrowError(IwbLanguageMessage.NoPermissionUpdateUserType); } var user = await UserManager.GetUserByIdAsync(input.Id); if (input.AccountType != user.AccountType) ThrowError(IwbLanguageMessage.CanNotUpdateAccountType); /*修改绑定账号。。。 */ MapToEntity(input, user); CheckErrors(await UserManager.UpdateAsync(user)); if (!input.RoleNames.IsEmpty()) CheckErrors(await UserManager.SetRoles(user, input.RoleNames.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries))); CacheManager.GetCache(IwbZeroConsts.SystemUserCache) .Set(input.Id + "", Repository.FirstOrDefault(input.Id)); } [AbpAuthorize(PermissionNames.PagesSystemMgUserMgDelete)] public override async Task Delete(EntityDto input) { var user = await UserManager.GetUserByIdAsync(input.Id); if (user.UserName == UserBase.AdminUserName || user.UserName == UserBase.SystemUserName || user.UserType <= AbpSession.UserType) ThrowError(IwbLanguageMessage.CanNotDeleteUser); await UserManager.DeleteAsync(user); await CacheManager.GetCache(IwbZeroConsts.SystemUserCache).RemoveAsync(input.Id + ""); } private async Task BindAccount(int? accountType, string accountNo) { string userName = ""; if (accountType == AccountTypeDefinition.System) { var guid = await AppGuidManager.GetGuidFromFileAsync(AppGuidType.UserNo); CheckGuid(guid); userName = "S" + guid; } else if (accountType == AccountTypeDefinition.Guest) { var guid = await AppGuidManager.GetGuidFromFileAsync(AppGuidType.Guest); CheckGuid(guid); /*绑定账号。。。 */ if (string.IsNullOrEmpty(accountNo)) { } userName = "G" + guid; } else ThrowError(IwbLanguageMessage.InvalidUserType); return userName; } #endregion public async Task ChangeLanguage(ChangeUserLanguageDto input) { await SettingManager.ChangeSettingForUserAsync( AbpSession.ToUserIdentifier(), LocalizationSettingNames.DefaultLanguage, input.LanguageName ); } protected override User MapToEntity(UserCreateDto createInput) { var user = ObjectMapper.Map(createInput); user.SetNormalizedNames(); return user; } protected override void MapToEntity(UserUpdateDto input, User user) { ObjectMapper.Map(input, user); user.SetNormalizedNames(); } protected override UserDto MapToEntityDto(User user) { var userDto = base.MapToEntityDto(user); //var roles = RoleManager.Roles?.Where(r => user.Roles != null && user.Roles.Any(ur => ur.RoleId == r.Id)) //.Select(r => r.NormalizedName).ToList() ?? new List(); //if (roles.Any()) //{ // userDto.Roles = roles.ToArray(); //} if (user.Roles.Any()) { userDto.Roles = user.Roles.Select(a => a.RoleId.ToString()).ToArray(); } return userDto; } } }