UserService.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System.Threading.Tasks;
  4. using Microsoft.AspNetCore.Mvc;
  5. using Microsoft.AspNetCore.Http;
  6. using Microsoft.Extensions.Options;
  7. using ZhonTai.Admin.Core.Attributes;
  8. using ZhonTai.Admin.Core.Configs;
  9. using ZhonTai.Admin.Core.Repositories;
  10. using ZhonTai.Common.Helpers;
  11. using ZhonTai.Admin.Core.Dto;
  12. using ZhonTai.Admin.Domain.Api;
  13. using ZhonTai.Admin.Domain.PermissionApi;
  14. using ZhonTai.Admin.Domain.Role;
  15. using ZhonTai.Admin.Domain.RolePermission;
  16. using ZhonTai.Admin.Domain.Tenant;
  17. using ZhonTai.Admin.Domain.User;
  18. using ZhonTai.Admin.Domain.UserRole;
  19. using ZhonTai.Admin.Services.Auth.Dto;
  20. using ZhonTai.Admin.Services.User.Dto;
  21. using ZhonTai.DynamicApi;
  22. using ZhonTai.DynamicApi.Attributes;
  23. using ZhonTai.Admin.Core.Helpers;
  24. using ZhonTai.Admin.Core.Consts;
  25. using ZhonTai.Admin.Domain.User.Dto;
  26. using ZhonTai.Admin.Services.Role.Dto;
  27. using Org.BouncyCastle.Crypto;
  28. namespace ZhonTai.Admin.Services.User;
  29. /// <summary>
  30. /// 用户服务
  31. /// </summary>
  32. [DynamicApi(Area = AdminConsts.AreaName)]
  33. public class UserService : BaseService, IUserService, IDynamicApi
  34. {
  35. private readonly AppConfig _appConfig;
  36. private readonly IUserRepository _userRepository;
  37. private readonly IRepositoryBase<UserRoleEntity> _userRoleRepository;
  38. private readonly ITenantRepository _tenantRepository;
  39. private readonly IApiRepository _apiRepository;
  40. private IRoleRepository _roleRepository => LazyGetRequiredService<IRoleRepository>();
  41. public UserService(
  42. AppConfig appConfig,
  43. IUserRepository userRepository,
  44. IRepositoryBase<UserRoleEntity> userRoleRepository,
  45. ITenantRepository tenantRepository,
  46. IApiRepository apiRepository
  47. )
  48. {
  49. _appConfig = appConfig;
  50. _userRepository = userRepository;
  51. _userRoleRepository = userRoleRepository;
  52. _tenantRepository = tenantRepository;
  53. _apiRepository = apiRepository;
  54. }
  55. /// <summary>
  56. /// 查询用户
  57. /// </summary>
  58. /// <param name="id"></param>
  59. /// <returns></returns>
  60. public async Task<IResultOutput> GetAsync(long id)
  61. {
  62. var entity = await _userRepository.Select
  63. .WhereDynamic(id)
  64. .IncludeMany(a => a.Roles.Select(b => new RoleEntity { Id = b.Id }))
  65. .ToOneAsync();
  66. var roles = await _roleRepository.Select.ToListAsync(a => new { a.Id, a.Name });
  67. return ResultOutput.Ok(new { Form = Mapper.Map<UserGetOutput>(entity), Select = new { roles } });
  68. }
  69. /// <summary>
  70. /// 查询列表
  71. /// </summary>
  72. /// <param name="input"></param>
  73. /// <returns></returns>
  74. public async Task<IResultOutput> GetListAsync([FromQuery] UserGetListInput input)
  75. {
  76. var list = await _userRepository.Select
  77. .WhereIf(input.Name.NotNull(), a => a.Name.Contains(input.Name))
  78. .OrderByDescending(true, c => c.Id)
  79. .ToListAsync<UserGetListOutput>();
  80. return ResultOutput.Ok(list);
  81. }
  82. /// <summary>
  83. /// 查询分页
  84. /// </summary>
  85. /// <param name="input"></param>
  86. /// <returns></returns>
  87. [HttpPost]
  88. public async Task<IResultOutput> GetPageAsync(PageInput input)
  89. {
  90. var list = await _userRepository.Select
  91. .WhereDynamicFilter(input.DynamicFilter)
  92. .Count(out var total)
  93. .OrderByDescending(true, a => a.Id)
  94. .IncludeMany(a => a.Roles.Select(b => new RoleEntity { Name = b.Name }))
  95. .Page(input.CurrentPage, input.PageSize)
  96. .ToListAsync();
  97. var data = new PageOutput<UserGetPageOutput>()
  98. {
  99. List = Mapper.Map<List<UserGetPageOutput>>(list),
  100. Total = total
  101. };
  102. return ResultOutput.Ok(data);
  103. }
  104. /// <summary>
  105. /// 查询登录用户信息
  106. /// </summary>
  107. /// <param name="id"></param>
  108. /// <returns></returns>
  109. public async Task<ResultOutput<AuthLoginOutput>> GetLoginUserAsync(long id)
  110. {
  111. var output = new ResultOutput<AuthLoginOutput>();
  112. var entityDto = await _userRepository.Select.DisableGlobalFilter("Tenant").WhereDynamic(id).ToOneAsync<AuthLoginOutput>();
  113. if (_appConfig.Tenant && entityDto?.TenantId.Value > 0)
  114. {
  115. var tenant = await _tenantRepository.Select.DisableGlobalFilter("Tenant").WhereDynamic(entityDto.TenantId).ToOneAsync(a => new { a.TenantType, a.DataIsolationType });
  116. if (null != tenant)
  117. {
  118. entityDto.TenantType = tenant.TenantType;
  119. entityDto.DataIsolationType = tenant.DataIsolationType;
  120. }
  121. }
  122. return output.Ok(entityDto);
  123. }
  124. /// <summary>
  125. /// 查询下拉数据
  126. /// </summary>
  127. /// <returns></returns>
  128. public async Task<IResultOutput> GetSelectAsync()
  129. {
  130. var roles = await _roleRepository.Select.ToListAsync(a => new { a.Id, a.Name });
  131. return ResultOutput.Ok(new { Select = new { roles } });
  132. }
  133. /// <summary>
  134. /// 查询用户基本信息
  135. /// </summary>
  136. /// <returns></returns>
  137. public async Task<IResultOutput> GetBasicAsync()
  138. {
  139. if (!(User?.Id > 0))
  140. {
  141. return ResultOutput.NotOk("未登录!");
  142. }
  143. var data = await _userRepository.GetAsync<UserUpdateBasicInput>(User.Id);
  144. return ResultOutput.Ok(data);
  145. }
  146. /// <summary>
  147. /// 查询用户权限信息
  148. /// </summary>
  149. /// <returns></returns>
  150. public async Task<IList<UserPermissionsOutput>> GetPermissionsAsync()
  151. {
  152. var key = string.Format(CacheKeys.UserPermissions, User.Id);
  153. var result = await Cache.GetOrSetAsync(key, async () =>
  154. {
  155. return await _apiRepository
  156. .Where(a => _userRoleRepository.Orm.Select<UserRoleEntity, RolePermissionEntity, PermissionApiEntity>()
  157. .InnerJoin((b, c, d) => b.RoleId == c.RoleId && b.UserId == User.Id)
  158. .InnerJoin((b, c, d) => c.PermissionId == d.PermissionId)
  159. .Where((b, c, d) => d.ApiId == a.Id).Any())
  160. .ToListAsync<UserPermissionsOutput>();
  161. });
  162. return result;
  163. }
  164. /// <summary>
  165. /// 新增用户
  166. /// </summary>
  167. /// <param name="input"></param>
  168. /// <returns></returns>
  169. [Transaction]
  170. public async Task<IResultOutput> AddAsync(UserAddInput input)
  171. {
  172. if (input.Password.IsNull())
  173. {
  174. input.Password = _appConfig.DefaultPassword;
  175. }
  176. input.Password = MD5Encrypt.Encrypt32(input.Password);
  177. var entity = Mapper.Map<UserEntity>(input);
  178. var user = await _userRepository.InsertAsync(entity);
  179. if (!(user?.Id > 0))
  180. {
  181. return ResultOutput.NotOk();
  182. }
  183. if (input.RoleIds != null && input.RoleIds.Any())
  184. {
  185. var roles = input.RoleIds.Select(a => new UserRoleEntity { UserId = user.Id, RoleId = a });
  186. await _userRoleRepository.InsertAsync(roles);
  187. }
  188. return ResultOutput.Ok();
  189. }
  190. /// <summary>
  191. /// 修改用户
  192. /// </summary>
  193. /// <param name="input"></param>
  194. /// <returns></returns>
  195. [Transaction]
  196. public async Task<IResultOutput> UpdateAsync(UserUpdateInput input)
  197. {
  198. if (!(input?.Id > 0))
  199. {
  200. return ResultOutput.NotOk();
  201. }
  202. var user = await _userRepository.GetAsync(input.Id);
  203. if (!(user?.Id > 0))
  204. {
  205. return ResultOutput.NotOk("用户不存在!");
  206. }
  207. Mapper.Map(input, user);
  208. await _userRepository.UpdateAsync(user);
  209. await _userRoleRepository.DeleteAsync(a => a.UserId == user.Id);
  210. if (input.RoleIds != null && input.RoleIds.Any())
  211. {
  212. var roles = input.RoleIds.Select(a => new UserRoleEntity { UserId = user.Id, RoleId = a });
  213. await _userRoleRepository.InsertAsync(roles);
  214. }
  215. return ResultOutput.Ok();
  216. }
  217. /// <summary>
  218. /// 更新用户基本信息
  219. /// </summary>
  220. /// <param name="input"></param>
  221. /// <returns></returns>
  222. public async Task<IResultOutput> UpdateBasicAsync(UserUpdateBasicInput input)
  223. {
  224. var entity = await _userRepository.GetAsync(input.Id);
  225. entity = Mapper.Map(input, entity);
  226. var result = (await _userRepository.UpdateAsync(entity)) > 0;
  227. //清除用户缓存
  228. await Cache.DelAsync(string.Format(CacheKeys.UserInfo, input.Id));
  229. return ResultOutput.Result(result);
  230. }
  231. /// <summary>
  232. /// 修改用户密码
  233. /// </summary>
  234. /// <param name="input"></param>
  235. /// <returns></returns>
  236. public async Task<IResultOutput> ChangePasswordAsync(UserChangePasswordInput input)
  237. {
  238. if (input.ConfirmPassword != input.NewPassword)
  239. {
  240. return ResultOutput.NotOk("新密码和确认密码不一致!");
  241. }
  242. var entity = await _userRepository.GetAsync(input.Id);
  243. var oldPassword = MD5Encrypt.Encrypt32(input.OldPassword);
  244. if (oldPassword != entity.Password)
  245. {
  246. return ResultOutput.NotOk("旧密码不正确!");
  247. }
  248. input.Password = MD5Encrypt.Encrypt32(input.NewPassword);
  249. entity = Mapper.Map(input, entity);
  250. var result = (await _userRepository.UpdateAsync(entity)) > 0;
  251. return ResultOutput.Result(result);
  252. }
  253. /// <summary>
  254. /// 彻底删除用户
  255. /// </summary>
  256. /// <param name="id"></param>
  257. /// <returns></returns>
  258. [Transaction]
  259. public async Task<IResultOutput> DeleteAsync(long id)
  260. {
  261. await _userRoleRepository.DeleteAsync(a => a.UserId == id);
  262. await _userRepository.DeleteAsync(m => m.Id == id);
  263. return ResultOutput.Ok();
  264. }
  265. /// <summary>
  266. /// 批量彻底删除用户
  267. /// </summary>
  268. /// <param name="ids"></param>
  269. /// <returns></returns>
  270. [Transaction]
  271. public async Task<IResultOutput> BatchDeleteAsync(long[] ids)
  272. {
  273. await _userRoleRepository.DeleteAsync(a => ids.Contains(a.UserId));
  274. await _userRepository.DeleteAsync(a => ids.Contains(a.Id));
  275. return ResultOutput.Ok();
  276. }
  277. /// <summary>
  278. /// 删除用户
  279. /// </summary>
  280. /// <param name="id"></param>
  281. /// <returns></returns>
  282. [Transaction]
  283. public async Task<IResultOutput> SoftDeleteAsync(long id)
  284. {
  285. await _userRoleRepository.DeleteAsync(a => a.UserId == id);
  286. await _userRepository.SoftDeleteAsync(id);
  287. return ResultOutput.Ok();
  288. }
  289. /// <summary>
  290. /// 批量删除用户
  291. /// </summary>
  292. /// <param name="ids"></param>
  293. /// <returns></returns>
  294. [Transaction]
  295. public async Task<IResultOutput> BatchSoftDeleteAsync(long[] ids)
  296. {
  297. await _userRoleRepository.DeleteAsync(a => ids.Contains(a.UserId));
  298. await _userRepository.SoftDeleteAsync(ids);
  299. return ResultOutput.Ok();
  300. }
  301. /// <summary>
  302. /// 上传头像
  303. /// </summary>
  304. /// <param name="file"></param>
  305. /// <returns></returns>
  306. [HttpPost]
  307. [Login]
  308. public async Task<IResultOutput> AvatarUpload([FromForm] IFormFile file)
  309. {
  310. var uploadConfig = LazyGetRequiredService<IOptionsMonitor<UploadConfig>>().CurrentValue;
  311. var uploadHelper = LazyGetRequiredService<UploadHelper>();
  312. var config = uploadConfig.Avatar;
  313. var res = await uploadHelper.UploadAsync(file, config, new { User.Id });
  314. if (res.Success)
  315. {
  316. return ResultOutput.Ok(res.Data.FileRelativePath);
  317. }
  318. return ResultOutput.NotOk(res.Msg ?? "上传失败!");
  319. }
  320. }