| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457 |
- 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 WeApp.Authorization;
- using WeApp.Authorization.Users;
- using WeApp.BaseInfo;
- using WeApp.BaseSystem.Roles.Dto;
- using WeApp.BaseSystem.Users.Dto;
- using WeApp.CommonManager.States;
- using WeApp.Configuration;
- using IwbZero;
- using IwbZero.AppServiceBase;
- using IwbZero.Auditing;
- using IwbZero.Authorization.Base;
- using IwbZero.Authorization.Base.Users;
- using Microsoft.AspNet.Identity;
- namespace WeApp.BaseSystem.Users
- {
- [AbpAuthorize, AuditLog("系统用户", "用户")]
- public class UsersAppService : IwbAsyncCrudAppService<User, UserDto, long, IwbPagedRequestDto, UserCreateDto, UserUpdateDto>, IUsersAppService
- {
- private IRepository<SysFunction> FunRepository { get; }
- private LogInManager LogInManager { get; }
- public UsersAppService(
- IRepository<User, long> repository,
- UserManager userManager,
- ICacheManager cacheManager, LogInManager logInManager, IRepository<SysFunction> 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<SelectListItem> GetUserTypeSelect()
- {
- var sList = new List<SelectListItem>();
- 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<string[]> GetUserRoles(long userId)
- {
- var roleList = await UserManager.GetRolesAsync(userId);
- string[] roles = roleList.ToArray();
- return roles;
- }
- //[DisableAuditing]
- //public async Task<ListResultDto<RoleDto>> 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<RoleDto>(ObjectMapper.Map<List<RoleDto>>(roles));
- //}
- //[DisableAuditing]
- //public List<SelectListItem> GetRoleSelects()
- //{
- // var accountType = AbpSession.AccountType;
- // var sList = new List<SelectListItem>();
- // 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<bool> 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<long> 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<long> 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<Permission>();
- if (input.PermissionNames != null && input.PermissionNames.Any())
- {
- grantedPermissions = PermissionManager
- .GetAllPermissions()
- .Where(p => input.PermissionNames.Contains(p.Name))
- .ToList();
- }
- await UserManager.SetGrantedPermissionsAsync(user, grantedPermissions);
- }
- /// <summary>
- /// 用户权限
- /// </summary>
- /// <param name="userId"></param>
- /// <returns></returns>
- [DisableAuditing]
- [AbpAuthorize(PermissionNames.PagesSystemMgUserMgAuth)]
- public async Task<PermissionAuthDto> GetPermissions(long userId)
- {
- 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 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;
- }
- /// <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, long 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 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<ListResultDto<PermissionDto>> GetAllPermissions()
- {
- var permissions = PermissionManager.GetAllPermissions();
- return Task.FromResult(new ListResultDto<PermissionDto>(
- ObjectMapper.Map<List<PermissionDto>>(permissions)
- ));
- }
- #endregion
- #region CURD
- #region GET
- #region Get
- public async Task<UserDto> GetUser(EntityDto<long> 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<PagedResultDto<UserDto>> GetAll(IwbPagedRequestDto input)
- {
- IQueryable<User> 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<UserDto>(totalCount, entities.Select(MapToEntityDto).ToList());
- }
- protected override IQueryable<User> ApplySorting(IQueryable<User> 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<User>(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<long> 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<string> 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<User>(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<string>();
- //if (roles.Any())
- //{
- // userDto.Roles = roles.ToArray();
- //}
- if (user.Roles.Any())
- {
- userDto.Roles = user.Roles.Select(a => a.RoleId.ToString()).ToArray();
- }
- return userDto;
- }
- }
- }
|