Global.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. using System.Buffers.Text;
  2. using System.Text.Json;
  3. using System.Text.Json.Serialization;
  4. using AntDesign;
  5. using CSRedis;
  6. using EasyTemplate.Tool.Entity;
  7. using EasyTemplate.Tool.Util;
  8. using Microsoft.AspNetCore.Http;
  9. using Microsoft.JSInterop;
  10. namespace EasyTemplate.Tool;
  11. public static class Global
  12. {
  13. /// <summary>
  14. ///
  15. /// </summary>
  16. public static string? ConfigId { get { return Setting.Get<string>("dbConnection:connectionConfigs:0:configId"); } }
  17. /// <summary>
  18. ///
  19. /// </summary>
  20. public static string? ConnectionString { get { return Setting.Get<string>("dbConnection:connectionConfigs:0:connectionString"); } }
  21. /// <summary>
  22. ///
  23. /// </summary>
  24. public static string? CacheConnectionString { get { return $"{Setting.Get<string>("Cache:RedisConnectionString")},prefix={Setting.Get<string>("Cache:InstanceName")}"; } }
  25. /// <summary>
  26. ///
  27. /// </summary>
  28. public static bool EnableInitTable { get { return Setting.Get<bool>("dbConnection:connectionConfigs:0:tableSettings:enableInitTable"); } }
  29. /// <summary>
  30. ///
  31. /// </summary>
  32. public static bool encryptResult { get { return Setting.Get<bool>("cryptogram:enabled"); } }
  33. /// <summary>
  34. ///
  35. /// </summary>
  36. public static string? CrypType { get { return Setting.Get<string>("cryptogram:cryptoType"); } }
  37. /// <summary>
  38. /// 登录过期时间
  39. /// </summary>
  40. public static int Expired { get { return Setting.Get<int>("App:ExpiredTime"); } }
  41. /// <summary>
  42. /// 上传地址
  43. /// </summary>
  44. public static string UploadUrl { get { return Setting.Get<string>("Upload:Url"); } }
  45. /// <summary>
  46. /// 富文本apikey
  47. /// </summary>
  48. public static string TinyMCEApiKey { get { return Setting.Get<string>("TinyMCE:ApiKey"); } }
  49. /// <summary>
  50. ///
  51. /// </summary>
  52. public static CSRedisClient Redis { get; set; }
  53. /// <summary>
  54. ///
  55. /// </summary>
  56. public static string CurrentPath { get; set; }
  57. /// <summary>
  58. ///
  59. /// </summary>
  60. public static long UserId { get; set; }
  61. /// <summary>
  62. ///
  63. /// </summary>
  64. public static SystemUser CurrentUser { get; set; }
  65. /// <summary>
  66. ///
  67. /// </summary>
  68. public static string? SystemName { get; set; }
  69. /// <summary>
  70. ///
  71. /// </summary>
  72. public static List<SystemMenu> Menus { get; set; } = new List<SystemMenu>();
  73. /// <summary>
  74. /// 获取host
  75. /// </summary>
  76. /// <param name="accessor"></param>
  77. /// <returns></returns>
  78. public static string GetHost(this IHttpContextAccessor accessor)
  79. {
  80. try
  81. {
  82. string host = accessor.HttpContext.Request.Headers["Host"];
  83. if (!string.IsNullOrWhiteSpace(host))
  84. {
  85. return $"{accessor.HttpContext.Request.Scheme}://{host}";
  86. }
  87. }
  88. catch (Exception ex) { }
  89. return "Empty Or Error Host";
  90. }
  91. /// <summary>
  92. /// 获取IP
  93. /// </summary>
  94. /// <param name="accessor"></param>
  95. /// <returns></returns>
  96. public static string GetIpv4(this IHttpContextAccessor accessor)
  97. {
  98. try
  99. {
  100. // 尝试从 X-Forwarded-For 头中获取真实 IP 地址
  101. var forwardedHeader = accessor.HttpContext.Request.Headers["X-Forwarded-For"];
  102. if (!string.IsNullOrEmpty(forwardedHeader))
  103. {
  104. // X-Forwarded-For 可能包含多个 IP 地址(逗号分隔),第一个是客户端的真实 IP
  105. return forwardedHeader.ToString().Split(',')[0].Trim();
  106. }
  107. // 如果没有 X-Forwarded-For 头,则回退到 RemoteIpAddress
  108. var remoteIpAddress = accessor.HttpContext.Connection.RemoteIpAddress;
  109. if (remoteIpAddress != null && remoteIpAddress.IsIPv4MappedToIPv6)
  110. {
  111. return remoteIpAddress.MapToIPv4().ToString();
  112. }
  113. }
  114. catch (Exception ex) { }
  115. return default;
  116. }
  117. public static async Task<SystemUser> GetUser(this IJSRuntime runtime)
  118. {
  119. var localStorageHelper = new LocalStorage(runtime);
  120. var user = await localStorageHelper.GetLocalStorage(LocalStorage.UserInfo);
  121. if (!string.IsNullOrWhiteSpace(user))
  122. {
  123. var suser = Crypto.AESDecrypt(user).ToEntity<SystemUser>();
  124. return suser;
  125. }
  126. return default;
  127. }
  128. public static SystemUser GetUserByToken(this IHttpContextAccessor accessor)
  129. {
  130. string token = accessor.HttpContext.Request.Headers["Authorization"];
  131. if (!string.IsNullOrEmpty(token))
  132. {
  133. token = token.Replace("Bearer ", "");
  134. var info = Jwt.Deserialize(token, out DateTime expired);
  135. if (info != null)
  136. {
  137. return new SystemUser() { Id = info.UserId, NickName = info.Name, };
  138. }
  139. }
  140. return null;
  141. }
  142. /// <summary>
  143. ///
  144. /// </summary>
  145. /// <param name="navigationManager"></param>
  146. public static void RedirectLogin(this Microsoft.AspNetCore.Components.NavigationManager navigationManager)
  147. {
  148. if (CurrentUser != null
  149. && CurrentUser.Id > 0
  150. && !string.IsNullOrWhiteSpace(CurrentUser.Account)
  151. && !string.IsNullOrWhiteSpace(CurrentUser.Password))
  152. return;
  153. navigationManager?.NavigateTo("/account/login");
  154. }
  155. public static async Task RedirectLogin(this Microsoft.AspNetCore.Components.NavigationManager navigationManager, IJSRuntime jSRuntime)
  156. {
  157. var localStorageHelper = new LocalStorage(jSRuntime);
  158. var json = await localStorageHelper.GetLocalStorage(LocalStorage.UserInfo);
  159. var user = Crypto.AESDecrypt(json).ToEntity<SystemUser>();
  160. if (user != null
  161. && user.Id > 0
  162. && !string.IsNullOrWhiteSpace(user.Account)
  163. && !string.IsNullOrWhiteSpace(user.Password))
  164. {
  165. if (user.Expired.Subtract(DateTime.Now).TotalDays > 0 && CurrentUser != null && user.Id == CurrentUser.Id)
  166. {
  167. return;
  168. }
  169. else
  170. {
  171. await localStorageHelper.RemoveLocalStorage(LocalStorage.AutoLogin);
  172. await localStorageHelper.RemoveLocalStorage(LocalStorage.UserInfo);
  173. }
  174. }
  175. navigationManager?.NavigateTo("/account/login");
  176. }
  177. }
  178. public class LongToDateTimeConverter : JsonConverter<DateTime>
  179. {
  180. public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  181. {
  182. if (Utf8Parser.TryParse(reader.ValueSpan, out long value, out _))
  183. return DateTime.UnixEpoch.AddMilliseconds(value);
  184. throw new FormatException();
  185. }
  186. public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
  187. {
  188. writer.WriteStringValue(
  189. JsonEncodedText.Encode(((long)(value - DateTime.UnixEpoch).TotalMilliseconds).ToString()));
  190. }
  191. }