UserService.cs 10 KB

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