using System.Buffers.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using AntDesign;
using CSRedis;
using EasyTemplate.Tool.Entity;
using EasyTemplate.Tool.Util;
using Microsoft.AspNetCore.Http;
using Microsoft.JSInterop;
namespace EasyTemplate.Tool;
public static class Global
{
///
///
///
public static string? ConfigId { get { return Setting.Get("dbConnection:connectionConfigs:0:configId"); } }
///
///
///
public static string? ConnectionString { get { return Setting.Get("dbConnection:connectionConfigs:0:connectionString"); } }
///
///
///
public static string? CacheConnectionString { get { return $"{Setting.Get("Cache:RedisConnectionString")},prefix={Setting.Get("Cache:InstanceName")}"; } }
///
///
///
public static bool EnableInitTable { get { return Setting.Get("dbConnection:connectionConfigs:0:tableSettings:enableInitTable"); } }
///
///
///
public static bool encryptResult { get { return Setting.Get("cryptogram:enabled"); } }
///
///
///
public static string? CrypType { get { return Setting.Get("cryptogram:cryptoType"); } }
///
/// 登录过期时间
///
public static int Expired { get { return Setting.Get("App:ExpiredTime"); } }
///
/// 上传地址
///
public static string UploadUrl { get { return Setting.Get("Upload:Url"); } }
///
/// 富文本apikey
///
public static string TinyMCEApiKey { get { return Setting.Get("TinyMCE:ApiKey"); } }
///
///
///
public static CSRedisClient Redis { get; set; }
///
///
///
public static string CurrentPath { get; set; }
///
///
///
public static long UserId { get; set; }
///
///
///
public static SystemUser CurrentUser { get; set; }
///
///
///
public static string? SystemName { get; set; }
///
///
///
public static List Menus { get; set; } = new List();
///
/// 获取host
///
///
///
public static string GetHost(this IHttpContextAccessor accessor)
{
try
{
string host = accessor.HttpContext.Request.Headers["Host"];
if (!string.IsNullOrWhiteSpace(host))
{
return $"{accessor.HttpContext.Request.Scheme}://{host}";
}
}
catch (Exception ex) { }
return "Empty Or Error Host";
}
///
/// 获取IP
///
///
///
public static string GetIpv4(this IHttpContextAccessor accessor)
{
try
{
// 尝试从 X-Forwarded-For 头中获取真实 IP 地址
var forwardedHeader = accessor.HttpContext.Request.Headers["X-Forwarded-For"];
if (!string.IsNullOrEmpty(forwardedHeader))
{
// X-Forwarded-For 可能包含多个 IP 地址(逗号分隔),第一个是客户端的真实 IP
return forwardedHeader.ToString().Split(',')[0].Trim();
}
// 如果没有 X-Forwarded-For 头,则回退到 RemoteIpAddress
var remoteIpAddress = accessor.HttpContext.Connection.RemoteIpAddress;
if (remoteIpAddress != null && remoteIpAddress.IsIPv4MappedToIPv6)
{
return remoteIpAddress.MapToIPv4().ToString();
}
}
catch (Exception ex) { }
return default;
}
public static async Task GetUser(this IJSRuntime runtime)
{
var localStorageHelper = new LocalStorage(runtime);
var user = await localStorageHelper.GetLocalStorage(LocalStorage.UserInfo);
if (!string.IsNullOrWhiteSpace(user))
{
var suser = Crypto.AESDecrypt(user).ToEntity();
return suser;
}
return default;
}
public static SystemUser GetUserByToken(this IHttpContextAccessor accessor)
{
string token = accessor.HttpContext.Request.Headers["Authorization"];
if (!string.IsNullOrEmpty(token))
{
token = token.Replace("Bearer ", "");
var info = Jwt.Deserialize(token, out DateTime expired);
if (info != null)
{
return new SystemUser() { Id = info.UserId, NickName = info.Name, };
}
}
return null;
}
///
///
///
///
public static void RedirectLogin(this Microsoft.AspNetCore.Components.NavigationManager navigationManager)
{
if (CurrentUser != null
&& CurrentUser.Id > 0
&& !string.IsNullOrWhiteSpace(CurrentUser.Account)
&& !string.IsNullOrWhiteSpace(CurrentUser.Password))
return;
navigationManager?.NavigateTo("/account/login");
}
public static async Task RedirectLogin(this Microsoft.AspNetCore.Components.NavigationManager navigationManager, IJSRuntime jSRuntime)
{
var localStorageHelper = new LocalStorage(jSRuntime);
var json = await localStorageHelper.GetLocalStorage(LocalStorage.UserInfo);
var user = Crypto.AESDecrypt(json).ToEntity();
if (user != null
&& user.Id > 0
&& !string.IsNullOrWhiteSpace(user.Account)
&& !string.IsNullOrWhiteSpace(user.Password))
{
if (user.Expired.Subtract(DateTime.Now).TotalDays > 0 && CurrentUser != null && user.Id == CurrentUser.Id)
{
return;
}
else
{
await localStorageHelper.RemoveLocalStorage(LocalStorage.AutoLogin);
await localStorageHelper.RemoveLocalStorage(LocalStorage.UserInfo);
}
}
navigationManager?.NavigateTo("/account/login");
}
}
public class LongToDateTimeConverter : JsonConverter
{
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (Utf8Parser.TryParse(reader.ValueSpan, out long value, out _))
return DateTime.UnixEpoch.AddMilliseconds(value);
throw new FormatException();
}
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
writer.WriteStringValue(
JsonEncodedText.Encode(((long)(value - DateTime.UnixEpoch).TotalMilliseconds).ToString()));
}
}