UsersAppService.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using System.Web.Mvc;
  6. using System.Web.WebPages;
  7. using Abp.Application.Services.Dto;
  8. using Abp.Auditing;
  9. using Abp.Authorization;
  10. using Abp.Domain.Repositories;
  11. using Abp.Localization;
  12. using Abp.MultiTenancy;
  13. using Abp.Runtime.Caching;
  14. using Abp.Runtime.Session;
  15. using WeApp.Authorization;
  16. using WeApp.Authorization.Users;
  17. using WeApp.BaseInfo;
  18. using WeApp.BaseSystem.Roles.Dto;
  19. using WeApp.BaseSystem.Users.Dto;
  20. using WeApp.CommonManager.States;
  21. using WeApp.Configuration;
  22. using IwbZero;
  23. using IwbZero.AppServiceBase;
  24. using IwbZero.Auditing;
  25. using IwbZero.Authorization.Base;
  26. using IwbZero.Authorization.Base.Users;
  27. using Microsoft.AspNet.Identity;
  28. namespace WeApp.BaseSystem.Users
  29. {
  30. [AbpAuthorize, AuditLog("系统用户", "用户")]
  31. public class UsersAppService : IwbAsyncCrudAppService<User, UserDto, long, IwbPagedRequestDto, UserCreateDto, UserUpdateDto>, IUsersAppService
  32. {
  33. private IRepository<SysFunction> FunRepository { get; }
  34. private LogInManager LogInManager { get; }
  35. public UsersAppService(
  36. IRepository<User, long> repository,
  37. UserManager userManager,
  38. ICacheManager cacheManager, LogInManager logInManager, IRepository<SysFunction> funRepository)
  39. : base(repository)
  40. {
  41. UserManager = userManager;
  42. LogInManager = logInManager;
  43. FunRepository = funRepository;
  44. CacheManager = cacheManager;
  45. }
  46. protected override string KeyExistMessage => string.Format(L(IwbLanguageMessage.KeyExistMessageFormatter), L("user"));
  47. protected override string KeyNotExistMessage => string.Format(L(IwbLanguageMessage.KeyNotExistMessageFormatter), L("user"));
  48. #region Select
  49. [DisableAuditing]
  50. public List<SelectListItem> GetUserTypeSelect()
  51. {
  52. var sList = new List<SelectListItem>();
  53. var list = StatesManager.GetStateList("UserRole", "UserRoleType");
  54. foreach (var l in list)
  55. {
  56. if (int.TryParse(l.CodeValue, out var userType))
  57. {
  58. if (userType <= AbpSession.UserType && AbpSession.UserName != UserBase.AdminUserName)
  59. {
  60. continue;
  61. }
  62. sList.Add(new SelectListItem { Text = l.DisplayValue, Value = l.CodeValue });
  63. }
  64. }
  65. return sList;
  66. }
  67. #endregion
  68. #region Roles
  69. [DisableAuditing]
  70. public async Task<string[]> GetUserRoles(long userId)
  71. {
  72. var roleList = await UserManager.GetRolesAsync(userId);
  73. string[] roles = roleList.ToArray();
  74. return roles;
  75. }
  76. //[DisableAuditing]
  77. //public async Task<ListResultDto<RoleDto>> GetRoles()
  78. //{
  79. // var accountType = AbpSession.AccountType;
  80. // var roles = await RoleRepository.GetAllListAsync(a =>
  81. // (AbpSession.UserName == UserBase.AdminUserName || a.RoleType > AbpSession.UserType) &&
  82. // (accountType == 1 || a.AccountType == accountType));
  83. // return new ListResultDto<RoleDto>(ObjectMapper.Map<List<RoleDto>>(roles));
  84. //}
  85. //[DisableAuditing]
  86. //public List<SelectListItem> GetRoleSelects()
  87. //{
  88. // var accountType = AbpSession.AccountType;
  89. // var sList = new List<SelectListItem>();
  90. // var list = RoleRepository.GetAllList(a =>
  91. // (AbpSession.UserName == UserBase.AdminUserName || a.RoleType > AbpSession.UserType) &&
  92. // (accountType == AccountTypeDefinition.System || a.AccountType == accountType));
  93. // foreach (var l in list)
  94. // {
  95. // sList.Add(new SelectListItem { Text = l.DisplayName, Value = l.Name });
  96. // }
  97. // return sList;
  98. //}
  99. #endregion
  100. #region Password
  101. [AbpAuthorize, AuditLog("修改密码")]
  102. public async Task<bool> ChangePassword(ChangePasswordDto input)
  103. {
  104. if (AbpSession.UserId == null)
  105. {
  106. ThrowError(IwbLanguageMessage.UserSessionTimeout);
  107. }
  108. var user = await UserManager.GetUserByIdAsync(AbpSession.UserId ?? 0);
  109. var loginAsync = await LogInManager.LoginAsync(user.UserName, input.CurrentPassword, shouldLockout: false);
  110. if (loginAsync.Result != IwbLoginResultType.Success)
  111. {
  112. ThrowError(IwbLanguageMessage.PasswordError);
  113. }
  114. //if (!new Regex(AccountAppService.PasswordRegex).IsMatch(input.NewPassword))
  115. //{
  116. // throw new UserFriendlyException("Passwords must be at least 8 characters, contain a lowercase, uppercase, and number.");
  117. //}
  118. user.Password = new PasswordHasher().HashPassword(input.NewPassword);
  119. await Repository.UpdateAsync(user);
  120. return true;
  121. }
  122. [AbpAuthorize(PermissionNames.PagesSystemMgUserMgResetPassword), AuditLog("重置密码")]
  123. public async Task ResetPassword(EntityDto<long> input)
  124. {
  125. var user = await UserManager.GetUserByIdAsync(input.Id);
  126. if (user == null)
  127. {
  128. CheckErrors(NotExistMessage);
  129. return;
  130. }
  131. if (user.UserType <= AbpSession.UserType && AbpSession.UserName != UserBase.AdminUserName && AbpSession.UserName != UserBase.SystemUserName)
  132. {
  133. ThrowError(IwbLanguageMessage.NoPermissionUpdateUser);
  134. }
  135. var password = await SettingManager.GetSettingValueAsync(IwbSettingNames.UserDefaultPassword);
  136. user.Password = new PasswordHasher().HashPassword(password);
  137. await Repository.UpdateAsync(user);
  138. }
  139. [AbpAuthorize(PermissionNames.PagesSystemMgUserMgResetLock), AuditLog("解除登陆锁定")]
  140. public async Task ResetLock(EntityDto<long> input)
  141. {
  142. var user = await UserManager.GetUserByIdAsync(input.Id);
  143. if (user == null)
  144. {
  145. CheckErrors(NotExistMessage);
  146. return;
  147. }
  148. if (user.UserType <= AbpSession.UserType && AbpSession.UserName != UserBase.AdminUserName && AbpSession.UserName != UserBase.SystemUserName)
  149. {
  150. ThrowError(IwbLanguageMessage.NoPermissionUpdateUser);
  151. }
  152. await UserManager.UnLockUserLogin(user);
  153. }
  154. #endregion
  155. #region Auth
  156. [AbpAuthorize(PermissionNames.PagesSystemMgUserMgAuth), AuditLog("用户权限配置")]
  157. public async Task Auth(AuthDto input)
  158. {
  159. var user = await UserManager.GetUserByIdAsync(input.Id);
  160. if (user.UserName == UserBase.AdminUserName)
  161. {
  162. ThrowError(IwbLanguageMessage.CanNotUpdateAdminPermission);
  163. }
  164. var grantedPermissions = new List<Permission>();
  165. if (input.PermissionNames != null && input.PermissionNames.Any())
  166. {
  167. grantedPermissions = PermissionManager
  168. .GetAllPermissions()
  169. .Where(p => input.PermissionNames.Contains(p.Name))
  170. .ToList();
  171. }
  172. await UserManager.SetGrantedPermissionsAsync(user, grantedPermissions);
  173. }
  174. /// <summary>
  175. /// 用户权限
  176. /// </summary>
  177. /// <param name="userId"></param>
  178. /// <returns></returns>
  179. [DisableAuditing]
  180. [AbpAuthorize(PermissionNames.PagesSystemMgUserMgAuth)]
  181. public async Task<PermissionAuthDto> GetPermissions(long userId)
  182. {
  183. var permissions = (await GetAllPermissions()).Items;
  184. List<PermissionDto> currentPerms = new List<PermissionDto>();
  185. if (AbpSession.UserName == UserBase.AdminUserName)
  186. {
  187. currentPerms.AddRange(permissions);
  188. }
  189. else
  190. {
  191. foreach (var perm in permissions)
  192. {
  193. if (await PermissionChecker.IsGrantedAsync(perm.Name))
  194. currentPerms.Add(perm);
  195. }
  196. }
  197. var permission = permissions.FirstOrDefault(a => a.Name == PermissionNames.Pages);
  198. var model = new PermissionAuthDto();
  199. if (permission != null)
  200. {
  201. var fun = await CacheManager.GetCache(IwbCacheNames.FunctionCache)
  202. .GetAsync(permission.Name, () => FunRepository.FirstOrDefaultAsync(a => a.PermissionName == permission.Name));
  203. model.Name = permission.Name;
  204. model.IsAuth = await UserManager.IsGrantedAsync(userId, permission.Name, true);
  205. model.PermDisplayName = fun.FunctionName;
  206. model.Sort = fun.Sort;
  207. model.Icon = fun.Icon;
  208. model.IsOpen = fun.Depth < 2;
  209. model.Children = await GetPermissionTree(permission.Name, currentPerms, userId);
  210. }
  211. return model;
  212. }
  213. /// <summary>
  214. /// 获取用户权限树
  215. /// </summary>
  216. /// <param name="parentName"></param>
  217. /// <param name="permissions"></param>
  218. /// <param name="userId"></param>
  219. /// <returns></returns>
  220. private async Task<List<PermissionAuthDto>> GetPermissionTree(string parentName, List<PermissionDto> permissions, long userId)
  221. {
  222. var parentPerms = permissions.Where(a => a.Parent?.Name == parentName).OrderBy(a => a.Sort).ToList();
  223. var list = new List<PermissionAuthDto>();
  224. if (parentPerms.Any())
  225. {
  226. foreach (var p in parentPerms)
  227. {
  228. var fun = await CacheManager.GetCache(IwbCacheNames.FunctionCache)
  229. .GetAsync(p.Name, () => FunRepository.FirstOrDefaultAsync(a => a.PermissionName == p.Name));
  230. var model = new PermissionAuthDto
  231. {
  232. Name = p.Name,
  233. IsAuth = await UserManager.IsGrantedAsync(userId, p.Name, true),
  234. PermDisplayName = fun.FunctionName,
  235. Sort = fun.Sort,
  236. Icon = fun.Icon,
  237. IsOpen = fun.Depth < 2,
  238. Children = await GetPermissionTree(p.Name, permissions, userId)
  239. };
  240. list.Add(model);
  241. }
  242. }
  243. return list;
  244. }
  245. [DisableAuditing]
  246. private Task<ListResultDto<PermissionDto>> GetAllPermissions()
  247. {
  248. var permissions = PermissionManager.GetAllPermissions();
  249. return Task.FromResult(new ListResultDto<PermissionDto>(
  250. ObjectMapper.Map<List<PermissionDto>>(permissions)
  251. ));
  252. }
  253. #endregion
  254. #region CURD
  255. #region GET
  256. #region Get
  257. public async Task<UserDto> GetUser(EntityDto<long> input)
  258. {
  259. var user = await GetEntityById(input.Id);
  260. var userRoles = await UserManager.GetRolesAsync(user.Id);
  261. var dto = MapToEntityDto(user);
  262. dto.Roles = userRoles.Select(ur => ur).ToArray();
  263. return dto;
  264. }
  265. #endregion
  266. #endregion
  267. [DisableAuditing]
  268. [AbpAuthorize(PermissionNames.PagesSystemMgUserMgQuery)]
  269. public override async Task<PagedResultDto<UserDto>> GetAll(IwbPagedRequestDto input)
  270. {
  271. IQueryable<User> query = CreateFilteredQuery(input);
  272. // ReSharper disable once RedundantLogicalConditionalExpressionOperand
  273. if (AbpSession.UserName != UserBase.AdminUserName && !(IwbConsts.MultiTenancyEnabled && AbpSession.MultiTenancySide.HasFlag(MultiTenancySides.Host)))
  274. query = query.Where(a => a.UserName != UserBase.AdminUserName &&
  275. (a.UserType > AbpSession.UserType) &&
  276. (AbpSession.AccountType == AccountTypeDefinition.System || a.AccountType == AbpSession.AccountType));
  277. var totalCount = await AsyncQueryableExecuter.CountAsync(query);
  278. query = ApplySorting(query, input);
  279. query = ApplyPaging(query, input);
  280. var entities = await AsyncQueryableExecuter.ToListAsync(query);
  281. return new PagedResultDto<UserDto>(totalCount, entities.Select(MapToEntityDto).ToList());
  282. }
  283. protected override IQueryable<User> ApplySorting(IQueryable<User> query, IwbPagedRequestDto input)
  284. {
  285. query = base.ApplySorting(query, input);
  286. //return query.OrderBy(r => r.UserType).ThenBy(a=>a.UserName);
  287. return query;
  288. }
  289. [AbpAuthorize(PermissionNames.PagesSystemMgUserMgCreate)]
  290. public override async Task Create(UserCreateDto input)
  291. {
  292. if (input.UserType <= AbpSession.UserType && AbpSession.UserName != UserBase.AdminUserName && AbpSession.UserName != UserBase.SystemUserName)
  293. {
  294. ThrowError(IwbLanguageMessage.NoPermissionUpdateUserType);
  295. }
  296. var user = ObjectMapper.Map<User>(input);
  297. user.UserName = await BindAccount(input.AccountType, input.AccountNo);
  298. user.TenantId = AbpSession.TenantId;
  299. user.IsEmailConfirmed = true;
  300. var password = await SettingManager.GetSettingValueAsync(IwbSettingNames.UserDefaultPassword);
  301. CheckErrors(await UserManager.CreateAsync(user, password));
  302. if (!input.RoleNames.IsEmpty())
  303. {
  304. var roles = input.RoleNames.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
  305. if (roles.Any())
  306. {
  307. CheckErrors(await UserManager.SetRoles(user, roles));
  308. }
  309. }
  310. await CurrentUnitOfWork.SaveChangesAsync();
  311. }
  312. [AbpAuthorize(PermissionNames.PagesSystemMgUserMgUpdate)]
  313. public override async Task Update(UserUpdateDto input)
  314. {
  315. if (AbpSession.UserName != UserBase.AdminUserName && AbpSession.UserName != UserBase.SystemUserName)
  316. {
  317. var oldUser = await GetEntityById(input.Id);
  318. if (oldUser?.UserType <= AbpSession.UserType) ThrowError(IwbLanguageMessage.NoPermissionUpdateUser);
  319. if (input.UserType <= AbpSession.UserType) ThrowError(IwbLanguageMessage.NoPermissionUpdateUserType);
  320. }
  321. var user = await UserManager.GetUserByIdAsync(input.Id);
  322. if (input.AccountType != user.AccountType) ThrowError(IwbLanguageMessage.CanNotUpdateAccountType);
  323. /*修改绑定账号。。。 */
  324. MapToEntity(input, user);
  325. CheckErrors(await UserManager.UpdateAsync(user));
  326. if (!input.RoleNames.IsEmpty())
  327. CheckErrors(await UserManager.SetRoles(user, input.RoleNames.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)));
  328. CacheManager.GetCache(IwbZeroConsts.SystemUserCache)
  329. .Set(input.Id + "", Repository.FirstOrDefault(input.Id));
  330. }
  331. [AbpAuthorize(PermissionNames.PagesSystemMgUserMgDelete)]
  332. public override async Task Delete(EntityDto<long> input)
  333. {
  334. var user = await UserManager.GetUserByIdAsync(input.Id);
  335. if (user.UserName == UserBase.AdminUserName || user.UserName == UserBase.SystemUserName || user.UserType <= AbpSession.UserType)
  336. ThrowError(IwbLanguageMessage.CanNotDeleteUser);
  337. await UserManager.DeleteAsync(user);
  338. await CacheManager.GetCache(IwbZeroConsts.SystemUserCache).RemoveAsync(input.Id + "");
  339. }
  340. private async Task<string> BindAccount(int? accountType, string accountNo)
  341. {
  342. string userName = "";
  343. if (accountType == AccountTypeDefinition.System)
  344. {
  345. var guid = await AppGuidManager.GetGuidFromFileAsync(AppGuidType.UserNo);
  346. CheckGuid(guid);
  347. userName = "S" + guid;
  348. }
  349. else if (accountType == AccountTypeDefinition.Guest)
  350. {
  351. var guid = await AppGuidManager.GetGuidFromFileAsync(AppGuidType.Guest);
  352. CheckGuid(guid);
  353. /*绑定账号。。。 */
  354. if (string.IsNullOrEmpty(accountNo))
  355. {
  356. }
  357. userName = "G" + guid;
  358. }
  359. else
  360. ThrowError(IwbLanguageMessage.InvalidUserType);
  361. return userName;
  362. }
  363. #endregion
  364. public async Task ChangeLanguage(ChangeUserLanguageDto input)
  365. {
  366. await SettingManager.ChangeSettingForUserAsync(
  367. AbpSession.ToUserIdentifier(),
  368. LocalizationSettingNames.DefaultLanguage,
  369. input.LanguageName
  370. );
  371. }
  372. protected override User MapToEntity(UserCreateDto createInput)
  373. {
  374. var user = ObjectMapper.Map<User>(createInput);
  375. user.SetNormalizedNames();
  376. return user;
  377. }
  378. protected override void MapToEntity(UserUpdateDto input, User user)
  379. {
  380. ObjectMapper.Map(input, user);
  381. user.SetNormalizedNames();
  382. }
  383. protected override UserDto MapToEntityDto(User user)
  384. {
  385. var userDto = base.MapToEntityDto(user);
  386. //var roles = RoleManager.Roles?.Where(r => user.Roles != null && user.Roles.Any(ur => ur.RoleId == r.Id))
  387. //.Select(r => r.NormalizedName).ToList() ?? new List<string>();
  388. //if (roles.Any())
  389. //{
  390. // userDto.Roles = roles.ToArray();
  391. //}
  392. if (user.Roles.Any())
  393. {
  394. userDto.Roles = user.Roles.Select(a => a.RoleId.ToString()).ToArray();
  395. }
  396. return userDto;
  397. }
  398. }
  399. }