You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

215 lines
8.0 KiB

6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
  1. using Microsoft.AspNetCore.Authentication;
  2. using Microsoft.AspNetCore.Authorization;
  3. using Microsoft.AspNetCore.Http;
  4. using Microsoft.AspNetCore.Identity;
  5. using Microsoft.AspNetCore.Mvc;
  6. using Microsoft.Extensions.Caching.Distributed;
  7. using Microsoft.Extensions.Configuration;
  8. using OpenIddict.Abstractions;
  9. using Shentun.Peis.Enums;
  10. using Shentun.Peis.Models;
  11. using Shentun.Peis.SysParmValues;
  12. using SqlSugar;
  13. using System;
  14. using System.Collections.Generic;
  15. using System.Linq;
  16. using System.Net.Http;
  17. using System.Net.Http.Headers;
  18. using System.Security.Claims;
  19. using System.Text;
  20. using System.Text.Json;
  21. using System.Threading.Tasks;
  22. using Volo.Abp;
  23. using Volo.Abp.Application.Services;
  24. using Volo.Abp.Caching;
  25. using Volo.Abp.Domain.Repositories;
  26. using Volo.Abp.Identity;
  27. namespace Shentun.Peis.ThirdUsers
  28. {
  29. /// <summary>
  30. /// 第三方用户
  31. /// </summary>
  32. [ApiExplorerSettings(GroupName = "Work")]
  33. [Authorize]
  34. public class ThirdUserAppService : ApplicationService
  35. {
  36. private readonly IConfiguration _configuration;
  37. private readonly IDistributedCache<string, string> _cache;
  38. private readonly IRepository<ThirdUser, Guid> _thirdUserRepository;
  39. private readonly CacheService _cacheService;
  40. private readonly IRepository<IdentityUser, Guid> _identityUserRepository;
  41. public ThirdUserAppService(
  42. IConfiguration configuration,
  43. IDistributedCache<string, string> cache,
  44. IRepository<ThirdUser, Guid> thirdUserRepository,
  45. CacheService cacheService,
  46. IRepository<IdentityUser, Guid> identityUserRepository)
  47. {
  48. _configuration = configuration;
  49. _cache = cache;
  50. _thirdUserRepository = thirdUserRepository;
  51. _cacheService = cacheService;
  52. _identityUserRepository = identityUserRepository;
  53. }
  54. /// <summary>
  55. /// 微信用户登录
  56. /// </summary>
  57. /// <param name="input"></param>
  58. /// <returns></returns>
  59. [AllowAnonymous]
  60. [HttpPost("api/app/ThirdUser/WeChatUserLogin")]
  61. public async Task<ThirdLoginDto> WeChatUserLoginAsync(WeChatUserLoginInputDto input)
  62. {
  63. var dic = new Dictionary<string, object>
  64. {
  65. {"jsCode",input.JsCode},
  66. {"client_id","Peis_MiniProgram"},
  67. {"mobile_phone",input.MobilePhone},
  68. {"grant_type","mini_program"},
  69. {"scope","Peis"}
  70. };
  71. //
  72. var dicStr = dic.Select(m => m.Key + "=" + m.Value).DefaultIfEmpty().Aggregate((m, n) => m + "&" + n);
  73. var token = await GetTokenAsync(dicStr);
  74. var options = new DistributedCacheEntryOptions()
  75. .SetAbsoluteExpiration(TimeSpan.FromDays(3));
  76. var sessionKey = CacheKeys.SessionKey + Guid.NewGuid().ToString();
  77. var sessionKeyValue = Guid.NewGuid().ToString();
  78. _cache.Set(sessionKey, sessionKeyValue, options);
  79. token.SessionKey = sessionKey;
  80. token.SessionKeyValue = sessionKeyValue;
  81. return token;
  82. }
  83. /// <summary>
  84. /// 获取第三方用户信息
  85. /// </summary>
  86. /// <returns></returns>
  87. [HttpPost("api/app/ThirdUser/GetList")]
  88. public async Task<List<ThirdUserDto>> GetListAsync(ThirdUserInputDto input)
  89. {
  90. var query = await _thirdUserRepository.GetQueryableAsync();
  91. if (input.AbpUserId != null)
  92. {
  93. query = query.Where(m => m.AbpUserId == input.AbpUserId);
  94. }
  95. if (input.UserRegisterFlag != null)
  96. {
  97. query = query.Where(m => m.UserRegisterFlag == input.UserRegisterFlag);
  98. }
  99. if (input.IsActive != null)
  100. {
  101. query = query.Where(m => m.IsActive == input.IsActive);
  102. }
  103. if (!string.IsNullOrWhiteSpace(input.MobilePhone))
  104. {
  105. query = query.Where(m => m.MobilePhone == input.MobilePhone);
  106. }
  107. if (!string.IsNullOrWhiteSpace(input.WechatOpenId))
  108. {
  109. query = query.Where(m => m.WechatOpenId == input.WechatOpenId);
  110. }
  111. var entListDto = query.OrderByDescending(o => o.CreationTime).ToList().Select(s => new ThirdUserDto
  112. {
  113. AbpUserId = s.AbpUserId,
  114. CreationTime = s.CreationTime,
  115. CreatorId = s.CreatorId,
  116. CreatorName = _cacheService.GetSurnameAsync(s.CreatorId).GetAwaiter().GetResult(),
  117. Id = s.Id,
  118. IsActive = s.IsActive,
  119. LastModificationTime = s.LastModificationTime,
  120. LastModifierId = s.LastModifierId,
  121. LastModifierName = _cacheService.GetSurnameAsync(s.LastModifierId).GetAwaiter().GetResult(),
  122. MobilePhone = s.MobilePhone,
  123. UserRegisterFlag = s.UserRegisterFlag,
  124. WechatOpenId = s.WechatOpenId
  125. }).ToList();
  126. return entListDto;
  127. }
  128. /// <summary>
  129. /// 绑定第三方用户归属到系统用户
  130. /// </summary>
  131. /// <returns></returns>
  132. [HttpPost("api/app/ThirdUser/BindThirdUserInAbpUser")]
  133. public async Task BindThirdUserInAbpUserAsync(BindThirdUserInAbpUserInputDto input)
  134. {
  135. var identityUser = await _identityUserRepository.FirstOrDefaultAsync(f => f.Id == input.AbpUserId);
  136. if (identityUser == null)
  137. {
  138. throw new UserFriendlyException("系统用户不存在");
  139. }
  140. var thirdUser = await _thirdUserRepository.FirstOrDefaultAsync(f => f.Id == input.ThirdUserId);
  141. if (thirdUser == null)
  142. {
  143. throw new UserFriendlyException("第三方用户不存在");
  144. }
  145. thirdUser.AbpUserId = input.AbpUserId;
  146. await _thirdUserRepository.UpdateAsync(thirdUser);
  147. }
  148. private async Task<ThirdLoginDto> GetTokenAsync(string request)
  149. {
  150. using var client = new HttpClient();
  151. HttpContent httpContent = new StringContent(request);
  152. httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
  153. var url = _configuration.GetSection("AuthServer").
  154. GetSection("Authority").Value + "/connect/token";
  155. var tokenResult = await client.PostAsync(url
  156. , httpContent);
  157. var tokenResultStr = await tokenResult.Content.ReadAsStringAsync();
  158. if (tokenResult.IsSuccessStatusCode)
  159. {
  160. var thirdLoginDto = new ThirdLoginDto();
  161. if (!string.IsNullOrEmpty(tokenResultStr))
  162. {
  163. if (tokenResultStr.ToLower().Contains("openid"))
  164. {
  165. thirdLoginDto = JsonSerializer.Deserialize<ThirdLoginDto>(tokenResultStr,
  166. new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
  167. }
  168. else
  169. {
  170. var signResult = JsonSerializer.Deserialize<SignInResultDto>(tokenResultStr,
  171. new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
  172. thirdLoginDto = new ThirdLoginDto
  173. {
  174. IsToken = "Y",
  175. ExpiresIn = signResult.expires_in,
  176. AccessToken = signResult.access_token,
  177. RefreshToken = signResult.refresh_token
  178. };
  179. }
  180. return thirdLoginDto;
  181. }
  182. else
  183. {
  184. throw new UserFriendlyException("token值为空");
  185. }
  186. }
  187. else
  188. {
  189. throw new UserFriendlyException("获取token失败:" + tokenResultStr);
  190. }
  191. }
  192. }
  193. }