Global.cs 8.0 KB

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