LoginInfoService.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. using IdentityModel;
  2. using Microsoft.AspNetCore.Http;
  3. using Microsoft.Extensions.Configuration;
  4. using Microsoft.Extensions.Options;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Security.Claims;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. using TEAMModelOS.Model.Core.Dtos;
  12. using TEAMModelOS.Model.Core.Models;
  13. using TEAMModelOS.SDK.Context.Configuration;
  14. using TEAMModelOS.SDK.Context.Constant.Common;
  15. using TEAMModelOS.SDK.Context.Exception;
  16. using TEAMModelOS.SDK.Extension.DataResult.JsonRpcRequest;
  17. using TEAMModelOS.SDK.Extension.DataResult.JsonRpcResponse;
  18. using TEAMModelOS.SDK.Extension.HttpClient.Implements;
  19. using TEAMModelOS.SDK.Extension.JwtAuth.JwtHelper;
  20. using TEAMModelOS.SDK.Extension.JwtAuth.Models;
  21. using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
  22. using TEAMModelOS.SDK.Helper.Common.DateTimeHelper;
  23. using TEAMModelOS.SDK.Helper.Common.JsonHelper;
  24. using TEAMModelOS.SDK.Helper.Network.HttpHelper;
  25. using TEAMModelOS.SDK.Helper.Security.BCryptHelper;
  26. using TEAMModelOS.SDK.Module.AzureTable.Interfaces;
  27. using TEAMModelOS.Service.Core.Interfaces;
  28. namespace TEAMModelOS.Service.Core.Implements
  29. {
  30. public class LoginInfoService : ILoginInfoService
  31. {
  32. private IAzureTableDBRepository _repository;
  33. private IOptions<JwtSetting> _options;
  34. private IHttpContextAccessor _httpContextAccessor;
  35. private HttpClientUserInfo _httpClientService;
  36. public LoginInfoService(IAzureTableDBRepository repository, IOptions<JwtSetting> options, IHttpContextAccessor httpContextAccessor , HttpClientUserInfo httpClientService)
  37. {
  38. _httpContextAccessor = httpContextAccessor;
  39. _options = options;
  40. _repository = repository;
  41. _httpClientService = httpClientService;
  42. }
  43. public async Task<LoginResult> CheckLoginAsync(TicketInfo ticketInfo) {
  44. string jtoken = HttpContextHelper.GetValueInHttp(_httpContextAccessor.HttpContext.Request, Constants.AUTHORIZATION);
  45. if (string.IsNullOrEmpty(ticketInfo.Token))
  46. {
  47. LoginResult result = new LoginResult();
  48. if (string.IsNullOrEmpty(ticketInfo.Ticket))
  49. {
  50. result.CheckTicket = false;
  51. return result;
  52. }
  53. string code = BCryptHelper.Ecrypt(ticketInfo.Ticket + ticketInfo.TeamModelId);
  54. bool f = BCryptHelper.Verify(ticketInfo.Ticket + ticketInfo.TeamModelId, ticketInfo.Sign);
  55. LoginInfo login = _repository.FindOneByKey<LoginInfo>("Ticket", ticketInfo.Ticket).Result;
  56. if (login != null && !string.IsNullOrEmpty(login.Token))
  57. {
  58. result.CheckTicket = true;
  59. JwtResponse token = await CreateJwtToken(login);
  60. result.JwtToken = token;
  61. login.Token = token.Access_token;
  62. result.JwtToken.Scope = login.Scope;
  63. await _repository.Update<LoginInfo>(login);
  64. return result;
  65. }
  66. JosnRPCRequest<Dictionary<string, object>> request = new JosnRPCRequest<Dictionary<string, object>>
  67. {
  68. method = "UserInfo"
  69. };
  70. Dictionary<string, object> ticket = new Dictionary<string, object>
  71. {
  72. { "ticket", ticketInfo.Ticket }
  73. };
  74. request.@params = ticket;
  75. string data = MessagePackHelper.ObjectToJson(request);
  76. string jsonStr = _httpClientService.HttpPost(BaseConfigModel.Configuration["HaBookAuth:AccountUrl"], data, Constants.CONTENT_TYPE_JSON, Encoding.UTF8);
  77. if (!string.IsNullOrEmpty(jsonStr))
  78. {
  79. JosnRPCResponse<TeamModelIdInfo> response = MessagePackHelper.JsonToObject<JosnRPCResponse<TeamModelIdInfo>>(jsonStr);
  80. if (response.error == null && response != null)
  81. {
  82. result.CheckTicket = true;
  83. LoginInfo loginInfo = new LoginInfo
  84. {
  85. PartitionKey = response.result.cellphone,
  86. Phone = response.result.cellphone,
  87. RowKey = Guid.NewGuid().ToString(),
  88. TeamModelId = response.result.id,
  89. Name = response.result.name,
  90. Ticket = ticketInfo.Ticket,
  91. CountryCode = response.result.countryCode
  92. };
  93. TeamModelUser user= await _repository.FindOneByKey<TeamModelUser>("TeamModelId", response.result.id);
  94. if (user == null || string.IsNullOrEmpty(user.RowKey))
  95. {
  96. user = new TeamModelUser { RowKey = Guid.NewGuid().ToString(), PartitionKey = loginInfo.CountryCode ,RegisterTime=DateTimeHelper.ConvertToTimeStamp13(DateTime.Now) };
  97. }
  98. user.Cellphone = response.result.cellphone;
  99. user.NickName = response.result.name;
  100. if (string.IsNullOrEmpty(user.FullName)) {
  101. user.FullName = response.result.name;
  102. }
  103. user.TeamModelId = response.result.id;
  104. user.CountryCode = response.result.countryCode;
  105. JwtResponse jwtToken = await CreateJwtToken(loginInfo);
  106. loginInfo.Token = jwtToken.Access_token;
  107. loginInfo.Scope = jwtToken.Scope;
  108. result.JwtToken = jwtToken;
  109. await _repository.Save<LoginInfo>(loginInfo);
  110. await _repository.SaveOrUpdate<TeamModelUser>(user);
  111. return result;
  112. }
  113. else
  114. {
  115. result.CheckTicket = false;
  116. return result;
  117. }
  118. }
  119. else
  120. {
  121. result.CheckTicket = false;
  122. return result;
  123. }
  124. }
  125. else
  126. {
  127. ClaimModel claimModel = JwtHelper.SerializeJWT(ticketInfo.Token);
  128. var dateTime = DateTimeHelper.ConvertToTimeStamp10(DateTime.Now);
  129. var expExt=claimModel.Claim.TryGetValue("exp",out var exp);
  130. if (expExt==false || dateTime > long.Parse(exp.ToString()))
  131. {
  132. throw new BizException(401, "Unauthorized");
  133. }
  134. Dictionary<string, object> msp = new Dictionary<string, object>
  135. {
  136. { "Token", ticketInfo.Token }
  137. };
  138. LoginInfo loginInfo = _repository.FindOneByDict<LoginInfo>(msp).Result;
  139. if (loginInfo != null && !string.IsNullOrEmpty(loginInfo.Token))
  140. {
  141. return new LoginResult { JwtToken = new JwtResponse { Access_token=loginInfo.Token ,Scope=loginInfo.Scope}, CheckTicket = true };
  142. }
  143. else
  144. {
  145. throw new BizException(401, "Unauthorized");
  146. }
  147. }
  148. }
  149. public async Task<JwtResponse> CreateJwtToken(LoginInfo loginInfo)
  150. {
  151. Dictionary<string, object> dict = new Dictionary<string, object>
  152. {
  153. { "Phone", loginInfo.CountryCode + loginInfo.Phone },
  154. { "TeamModelId", loginInfo.TeamModelId }
  155. };
  156. string role = "";
  157. List<RoleUser> roleUsers = await _repository.FindListByDict<RoleUser>(dict);
  158. if (roleUsers.IsNotEmpty()) {
  159. foreach (RoleUser roleUser in roleUsers)
  160. {
  161. role = role + roleUser.RoleCode + ",";
  162. }
  163. }
  164. role= role.Substring(0, role.Length - 1);
  165. ClaimModel model = new ClaimModel
  166. {
  167. Scope = "WebApp"
  168. };
  169. model.Claims.Add(new Claim(JwtClaimTypes.Name, loginInfo.Name));
  170. model.Claims.Add(new Claim(JwtClaimTypes.Id, loginInfo.TeamModelId));
  171. ////保护隐私
  172. //model.Claims.Add(new Claim(JwtClaimTypes.PhoneNumber, loginInfo.Phone));
  173. model.Claims.AddRange(role.Split(',').Select(s => new Claim(JwtClaimTypes.Role, s)));
  174. model.Roles.Add(role);
  175. JwtResponse jwtResponse = JwtHelper.IssueJWT(model, _options.Value);
  176. return jwtResponse;
  177. }
  178. public Task<LoginInfo> SaveLoginInfoAsync(LoginInfo loginInfo)
  179. {
  180. return _repository.Save<LoginInfo>(loginInfo);
  181. }
  182. }
  183. }