using System.Net; using System.Net.Sockets; using IPTools.Core; using Microsoft.AspNetCore.Http; using NPin.Framework.Core.Extensions; using SqlSugar; using UAParser; using Volo.Abp.Auditing; using Volo.Abp.Domain.Entities; namespace NPin.Framework.Upms.Domain.Entities; [SugarTable("SysLoginLog", "登录日志表")] [SugarIndex($"index_{nameof(LoginUser)}", nameof(LoginUser), OrderByType.Asc)] public class LoginLogAggregateRoot : AggregateRoot, ICreationAuditedObject { [SugarColumn(IsPrimaryKey = true)] public override Guid Id { get; protected set; } public DateTime CreationTime { get; set; } = DateTime.Now; public Guid? CreatorId { get; set; } [SugarColumn(ColumnDescription = "登录用户")] public string? LoginUser { get; set; } [SugarColumn(ColumnDescription = "登录用户ID")] public Guid LoginUserId { get; set; } [SugarColumn(ColumnDescription = "登录地点")] public string? LoginLocation { get; set; } [SugarColumn(ColumnDescription = "Ipv4")] public string? LoginIpv4 { get; set; } [SugarColumn(ColumnDescription = "Ipv6")] public string? LoginIpv6 { get; set; } [SugarColumn(ColumnDescription = "浏览器")] public string? Browser { get; set; } [SugarColumn(ColumnDescription = "操作系统")] public string? Os { get; set; } [SugarColumn(ColumnDescription = "登录信息")] public string? LoginMsg { get; set; } public static LoginLogAggregateRoot GetInfoByHttpContext(HttpContext httpContext) { // var ipInfo = httpContext.GetRemoteIpInfo(); string ipv4AddrStr = null; string ipv6AddrStr = null; var ipAddr = httpContext.GetClientIpAddress(); if (ipAddr != null) { switch (ipAddr.AddressFamily) { case AddressFamily.InterNetwork: ipv4AddrStr = ipAddr.ToString(); break; case AddressFamily.InterNetworkV6: ipv6AddrStr = ipAddr.ToString(); break; } } var location = IPAddress.IsLoopback(ipAddr) ? new IpInfo { Province = "本地", City = "本机" } : IpTool.Search(ipAddr.ToString()); var clientInfo = GetClientInfo(httpContext); return new LoginLogAggregateRoot { Browser = clientInfo.Device.Family, Os = clientInfo.OS.ToString(), LoginIpv4 = ipv4AddrStr, LoginIpv6 = ipv6AddrStr, LoginLocation = $"{location.Country}-{location.Province}-{location.City}" }; ClientInfo GetClientInfo(HttpContext ctx) => Parser.GetDefault().Parse(ctx.GetUserAgent()); } }