CrazyIter_Bin 1 年之前
父節點
當前提交
65890066df

+ 5 - 1
TEAMModelOS.SDK/Helper/Network/IP2Region/IPSearcher.cs

@@ -3,6 +3,7 @@ using System.IO;
 using System.Text;
 using System.Threading.Tasks;
 using TEAMModelOS.SDK.IP2Region;
+using TEAMModelOS.SDK.Models;
 
 namespace TEAMModelOS.SDK
 {
@@ -375,6 +376,10 @@ namespace TEAMModelOS.SDK
         }
         public async Task<string> SearchIpAsync( string ip)
         {
+            if (ip.Contains("::"))
+            {
+                ip = "127.0.0.1";
+            }
             try
             {
                 DataBlock block = await MemorySearchAsync(ip);
@@ -397,7 +402,6 @@ namespace TEAMModelOS.SDK
             catch (Exception) {
                 return null;
             }
-           
         }
         /// <summary>
         /// Get the region throught the ip address with b-tree search algorithm.

+ 1 - 0
TEAMModelOS.SDK/Helper/Network/IP2Region/IPSearcherExtensions.cs

@@ -18,5 +18,6 @@ namespace TEAMModelOS.SDK
             services.TryAddSingleton(new IPSearcher(Path.Combine(path, "ip2region.db")));
             return services;
         }
+        
     }
 }

+ 1 - 1
TEAMModelOS.SDK/Models/Service/GroupListService.cs

@@ -495,7 +495,7 @@ namespace TEAMModelOS.SDK
                 {
 
                     var mb =  item.members.FindAll(x => x.id.Equals(userid)  && x.type==type);
-                    if (mb!=null) {
+                    if (mb.IsNotEmpty()) {
                         return (2, item, null);
                     }
                     //状态=6 ,人数已满,需要审核通过再加入。

+ 33 - 26
TEAMModelOS/Controllers/Client/AClassONEController.cs

@@ -106,33 +106,40 @@ namespace TEAMModelOS.Controllers
         public async Task<IActionResult> GetMiniAPPOpenid(JsonElement json)
         {
             // string Content = await responseMessage.Content.ReadAsStringAsync();
-            var location = _option.Location;
-            var clientID = _configuration.GetValue<string>("HaBookAuth:AClassONE:clientID");
-            var clientSecret = _configuration.GetValue<string>("HaBookAuth:AClassONE:clientSecret");
-            var wxappid = _configuration.GetValue<string>("HaBookAuth:WXMiniAPP:appid");
-            var wxsecret = _configuration.GetValue<string>("HaBookAuth:WXMiniAPP:secret");
-            if (location.Contains("China"))
-            {
-                location = "China";
-            }
-            else if (location.Contains("Global"))
-            {
-                location = "Global";
-            }
-            var token = await CoreTokenExtensions.CreateAccessToken(clientID, clientSecret, location);
-            //return Ok(new { token = new { token.TokenType,token.AccessToken } });
-            if (!json.TryGetProperty("js_code", out JsonElement js_code)) return BadRequest("js_code is null");
-            string url = $"https://api.weixin.qq.com/sns/jscode2session?appid={wxappid}&secret={wxsecret}&js_code={js_code}&grant_type=authorization_code";
-            HttpResponseMessage responseMessage = await _httpClient.CreateClient().GetAsync(url);
-            if (responseMessage.StatusCode == HttpStatusCode.OK)
-            {
-                JsonDocument document = JsonDocument.Parse(responseMessage.Content.ReadAsStream());
-                return Ok(new { miniappData = document, token = new { token.TokenType, token.AccessToken } });
+            try {
+                var location = _option.Location;
+                var clientID = _configuration.GetValue<string>("HaBookAuth:AClassONE:clientID");
+                var clientSecret = _configuration.GetValue<string>("HaBookAuth:AClassONE:clientSecret");
+                var wxappid = _configuration.GetValue<string>("HaBookAuth:WXMiniAPP:appid");
+                var wxsecret = _configuration.GetValue<string>("HaBookAuth:WXMiniAPP:secret");
+                if (location.Contains("China"))
+                {
+                    location = "China";
+                }
+                else if (location.Contains("Global"))
+                {
+                    location = "Global";
+                }
+                var token = await CoreTokenExtensions.CreateAccessToken(clientID, clientSecret, location);
+                //return Ok(new { token = new { token.TokenType,token.AccessToken } });
+                if (!json.TryGetProperty("js_code", out JsonElement js_code)) return BadRequest("js_code is null");
+                string url = $"https://api.weixin.qq.com/sns/jscode2session?appid={wxappid}&secret={wxsecret}&js_code={js_code}&grant_type=authorization_code";
+                HttpResponseMessage responseMessage = await _httpClient.CreateClient().GetAsync(url);
+                if (responseMessage.StatusCode == HttpStatusCode.OK)
+                {
+                    JsonDocument document = JsonDocument.Parse(responseMessage.Content.ReadAsStream());
+                    return Ok(new { miniappData = document, token = new { token.TokenType, token.AccessToken } });
+                }
+                else
+                {
+                    string Content = await responseMessage.Content?.ReadAsStringAsync();
+                    await _dingDing.SendBotMsg($"get-miniapp-userinfo:{Content}", GroupNames.成都开发測試群組);
+                    return BadRequest(Content);
+                }
             }
-            else
-            {
-                string Content = await responseMessage.Content?.ReadAsStringAsync();
-                return BadRequest(Content);
+            catch(Exception ex) {
+               await _dingDing.SendBotMsg($"get-miniapp-userinfo:{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
+                return BadRequest();
             }
         }
         /// <summary>

+ 226 - 20
TEAMModelOS/Controllers/System/BillController.cs

@@ -5,6 +5,7 @@ using DocumentFormat.OpenXml.Spreadsheet;
 using DocumentFormat.OpenXml.Wordprocessing;
 using FastJSON;
 using HTEXLib.COMM.Helpers;
+using IP2Region.Net.Abstractions;
 using Microsoft.AspNetCore.Authorization;
 using Microsoft.AspNetCore.Cors;
 using Microsoft.AspNetCore.Hosting;
@@ -38,6 +39,7 @@ using TEAMModelOS.SDK.DI;
 using TEAMModelOS.SDK.Extension;
 using TEAMModelOS.SDK.Helper.Common.JsonHelper;
 using TEAMModelOS.SDK.Helper.Common.JsonHelper.JsonPath;
+using TEAMModelOS.SDK.IP2Region;
 using TEAMModelOS.SDK.Models.Cosmos.BI.BISchool;
 using Top.Api;
 
@@ -55,9 +57,9 @@ namespace TEAMModelOS.Controllers
         private readonly IConfiguration _configuration;
         private readonly AzureStorageFactory _azureStorage;
         private readonly AzureRedisFactory _azureRedis;
-        private readonly IPSearcher _ipSearcher;
+        private readonly ISearcher _ipSearcher;
         private readonly Option _option;
-        public BillController(IHttpClientFactory httpClient, IConfiguration configuration, AzureStorageFactory azureStorage, IPSearcher searcher, DingDing dingDing, IOptionsSnapshot<Option> option)
+        public BillController(IHttpClientFactory httpClient, IConfiguration configuration, AzureStorageFactory azureStorage, ISearcher searcher, DingDing dingDing, IOptionsSnapshot<Option> option)
         {
             _httpClient = httpClient;
             _configuration = configuration;
@@ -77,6 +79,7 @@ namespace TEAMModelOS.Controllers
         [RequestSizeLimit(102_400_000_00)] //最大10000m左右
         public async Task<IActionResult> ReportApi(JsonElement json)
         {
+            var reg = _ipSearcher.SearchIp(json.GetProperty("ip").GetString());
             var untyped = new JsonParser().Parse(json.GetRawText());
             var selection = new JsonPathSelection(untyped);
             {
@@ -108,7 +111,7 @@ namespace TEAMModelOS.Controllers
                 else
                 {
                     List<ApiVist> vistsDay = new List<ApiVist>();
-                    List<(string uuid, List<string> tmdid, List<string> school)> uuidInfos = new List<(string uuid, List<string> tmdid, List<string> school)>();
+                    List<(string uuid, HttpLog httpLog, List<string> tmdid, List<string> school)> uuidInfos = new List<(string uuid, HttpLog httpLog, List<string> tmdid, List<string> school)>();
                     List<string> files = await _azureStorage.GetBlobContainerClient("0-service-log").List($"http-log/{time}");
                     foreach (var file in files)
                     {
@@ -122,13 +125,16 @@ namespace TEAMModelOS.Controllers
                             }
                             BlobDownloadResult result = await _azureStorage.GetBlobContainerClient("0-service-log").GetBlobClient($"http-log/{time}/{hour}.json").DownloadContentAsync();
                             var httpLogs = result.Content.ToObjectFromJson<List<HttpLog>>();
-                            (List<ApiVist> vists, List<(string uuid, List<string> tmdid, List<string> school)> uuidInfo)   = Convert(httpLogs);
+                            (List<ApiVist> vists, List<(string uuid, HttpLog httpLog, List<string> tmdid, List<string> school)> uuidInfo)   = await Convert(httpLogs);
                             vistsDay.AddRange(vists);
                             uuidInfos.AddRange(uuidInfo);
 
 
                         }
                     }
+
+                    vistsDay.FindAll(x => x.path.Contains("common/exam/upsert-record"));
+
                     List<(string tmd, bool exists, string scope)> tmdexists = new List<(string tmd, bool exists, string scope)>();
                     List<(string sch, bool exists)> schexists = new List<(string sch, bool exists)>();
                     var tmds = uuidInfos.SelectMany(x => x.tmdid).ToHashSet();
@@ -193,13 +199,16 @@ namespace TEAMModelOS.Controllers
                     }
                 }
             }
-            return Ok();
+            return Ok(reg);
         }
 
-        public (List<ApiVist> vists, List<(string uuid, List<string> tmdid, List<string> school)> uuidInfo) Convert(List<HttpLog> logs)
+
+
+
+        public async Task<(List<ApiVist> vists, List<(string uuid, HttpLog httpLog, List<string> tmdid, List<string> school)> uuidInfo)> Convert(List<HttpLog> logs)
         {
             List<ApiVist> vists = new List<ApiVist>();
-            List<(string uuid, List<string> tmdid, List<string> school)> uuidInfo = new List<(string uuid, List<string> tmdid, List<string> school)>();
+            List<(string uuid, HttpLog httpLog, List<string> tmdid, List<string> school)> uuidInfo = new List<(string uuid, HttpLog httpLog, List<string> tmdid, List<string> school)>();
             foreach (HttpLog log in logs)
             {
                 string uuid = Guid.NewGuid().ToString();
@@ -211,14 +220,14 @@ namespace TEAMModelOS.Controllers
                     var untyped = new JsonParser().Parse(log.param.GetRawText());
                     var selection = new JsonPathSelection(untyped);
                     string path = "$..[id_token,idToken,idtoken,tmdid,id,teacherId,teacher,tid,tId,userid,userId,code,studentId,student,studentid]";
-                    
+
                     var nodes_path = selection.SelectNodes(path);
                     foreach (var node in nodes_path)
                     {
                         // 只获取是字符串的 
                         if (node.Value is string)
                         {
-                            switch (true) 
+                            switch (true)
                             {
                                 case bool when node.Path.Contains("id_token")||node.Path.Contains("idToken")||node.Path.Contains("idtoken"):
                                     {
@@ -266,7 +275,7 @@ namespace TEAMModelOS.Controllers
                                                 }
                                             }
                                         }
-                                        break; 
+                                        break;
                                     }
                             }
                         }
@@ -484,9 +493,9 @@ namespace TEAMModelOS.Controllers
                                                 }
                                             }
                                         }
-                                        break; 
+                                        break;
                                     }
-                              
+
                             }
                         }
 
@@ -572,77 +581,268 @@ namespace TEAMModelOS.Controllers
                 }
 
 
-                uuidInfo.Add((uuid, useridMatch, schoolMatch));
+                uuidInfo.Add((uuid, log, useridMatch, schoolMatch));
                 vists.Add(vist);
+                //处理 client
+                {
+                    if (!string.IsNullOrWhiteSpace(log.client))
+                    {
+                        if (log.client.Equals("IES", StringComparison.OrdinalIgnoreCase))
+                        {
+                            vist.client="ies5";
+                        }
+                        if (log.client.Equals("AClassONE", StringComparison.OrdinalIgnoreCase))
+                        {
+                            vist.client="aclassone";
+                        }
+                        if (log.client.Equals("BB", StringComparison.OrdinalIgnoreCase))
+                        {
+                            vist.client="habb";
+                        }
+                        if (log.client.Equals("HiTool", StringComparison.OrdinalIgnoreCase) ||log.client.Equals("HiTools", StringComparison.OrdinalIgnoreCase))
+                        {
+                            vist.client="hiscan";
+                        }
+                        if (log.client.Equals("HiTA", StringComparison.OrdinalIgnoreCase))
+                        {
+                            vist.client="hita";
+                        }
+                        if (log.client.Equals("HiTeachCC", StringComparison.OrdinalIgnoreCase))
+                        {
+                            vist.client="hiteachcc";
+                        }
+                        if (log.client.Equals("HiTeach", StringComparison.OrdinalIgnoreCase))
+                        {
+                            vist.client="hiteach";
+                        }
+                        if (log.client.Equals("Open", StringComparison.OrdinalIgnoreCase))
+                        {
+                            vist.client="open";
+                        }
+                    }
+                }
                 //补全站点
                 {
                     if (!string.IsNullOrWhiteSpace(log.host)
                         &&(log.host.Equals("teammodelos-yx.chinacloudsites.cn")||log.host.Equals("teammodelos.chinacloudsites.cn")
-                        ||log.host.Equals("yx.teammodel.cn")||log.host.Equals("scyx.teammodel.cn")  ||log.host.Equals("jinniu.teammodel.cn")))
+                        ||log.host.Equals("yx.teammodel.cn")))
                     {
+                        log.host="IES-正式站";
                         log.host="www.teammodel.cn";
+                        vist.client="ies5";
+                    }
+                    if (!string.IsNullOrWhiteSpace(log.host)
+                       &&(log.host.Equals("scyx.teammodel.cn")  ||log.host.Equals("jinniu.teammodel.cn")))
+                    {
+                        log.host="研修2.0-正式站";
+                        log.host="scyx.teammodel.cn";
+                        vist.client="ability";
                     }
+                    if (!string.IsNullOrWhiteSpace(log.host)
+                       &&(log.host.Equals("open.teammodel.cn")))
+                    {
+                        log.host="开放平台-正式站";
+                        log.host="open.teammodel.cn";
+                        vist.client="open";
+                    }
+                    if (!string.IsNullOrWhiteSpace(log.host)
+                       &&(log.host.Equals("open-test.teammodel.cn")  ||log.host.Equals("zhiyin-test.teammodel.cn")))
+                    {
+                        log.host="开放平台-测试站";
+                        log.host="open-test.teammodel.cn";
+                        vist.client="open";
+                    }
+
+                    //
                     if (!string.IsNullOrWhiteSpace(log.host)
                         &&(log.host.Equals("teammodelos-rc.chinacloudsites.cn")))
                     {
+                        log.host="IES-RC站";
                         log.host="rc.teammodel.cn";
+                        vist.client="ies5";
                     }
                     if (!string.IsNullOrWhiteSpace(log.host)
-                        &&(log.host.Equals("teammodelos-test.chinacloudsites.cn") || log.host.Equals("zhiyin-test.teammodel.cn")))
+                        &&(log.host.Equals("teammodelos-test.chinacloudsites.cn")))
                     {
+                        log.host="IES-测试站";
                         log.host="test.teammodel.cn";
+                        vist.client="ies5";
                     }
                     if (!string.IsNullOrWhiteSpace(log.host)
                         &&(log.host.Equals("teammodelbi-test.chinacloudsites.cn")))
                     {
+                        log.host="BI-测试站";
                         log.host="bitest.teammodel.cn";
+                        vist.client="bi";
                     }
                     if (!string.IsNullOrWhiteSpace(log.host)
                         &&(log.host.Equals("teammodelbi.chinacloudsites.cn")))
                     {
+                        log.host="BI-正式站";
                         log.host="bi.teammodel.cn";
+                        vist.client="bi";
                     }
                     if (!string.IsNullOrWhiteSpace(log.host)
                         &&(log.host.Equals("teamcontest.chinacloudsites.cn")))
                     {
-                        log.host="bi.teammodel.cn";
+                        log.host="赛课-正式站";
+                        log.host="contest.teammodel.cn";
+                        vist.client="contest";
+
                     }
                     if (!string.IsNullOrWhiteSpace(log.host)
                         &&(log.host.Equals("contest.chinacloudsites.cn")))
                     {
+                        log.host="赛课-正式站";
                         log.host="contest.teammodel.cn";
+                        vist.client="contest";
                     }
                     if (!string.IsNullOrWhiteSpace(log.host)
                         &&(log.host.Equals("contest-test.chinacloudsites.cn")))
                     {
+                        log.host="赛课-测试站";
                         log.host="contest-test.teammodel.cn";
+                        vist.client="contest";
                     }
                     if (!string.IsNullOrWhiteSpace(log.host)
                         &&(log.host.Equals("hiteachcc.chinacloudsites.cn")))
                     {
+                        log.host="CC-正式站";
                         log.host="hiteachcc.teammodel.cn";
+                        vist.client="hiteachcc";
                     }
                     if (!string.IsNullOrWhiteSpace(log.host)
                         &&(log.host.Equals("appraisal.chinacloudsites.cn")))
                     {
+                        log.host="评价-正式站";
                         log.host="appraisal.teammodel.cn";
+                        vist.client="appraisal";
                     }
                     if (!string.IsNullOrWhiteSpace(log.host)
                         &&(log.host.Equals("appraisal-test.chinacloudsites.cn")))
                     {
+                        log.host="评价-测试站";
                         log.host="appraisal-test.teammodel.cn";
+                        vist.client="appraisal";
+                    }
+                    if (log.host.Equals("localhost")  &&  log.p.Equals("os"))
+                    {
+                        log.host="IES-测试站";
+                        log.host="test.teammodel.cn";
+                        vist.client="ies5";
+                    }
+                    else if (log.host.Equals("localhost")  && (log.p.Equals("bi")))
+                    {
+                        log.host="BI-测试站";
+                        log.host="bitest.teammodel.cn";
+                        vist.client="bi";
                     }
                 }
 
-                if (log.host.Equals("localhost")  &&  log.p.Equals("os")) 
+                //补全产品端
                 {
-                    log.host="test.teammodel.cn";
+                    //研修2.0
+                    if (log.path.Contains("research")  || log.path.Contains("study")  || log.path.Contains("standard-file"))
+                    {
+                        vist.client="ability";
+                    }
+
+                    if (log.path.StartsWith("/activity"))
+                    {
+                        vist.client="contest";
+                    }
+                    //小程序
+                    if (log.path.Contains("aclassone"))
+                    {
+                        vist.client="aclassone";
+                    }
+                    //  /// <summary>
+                    /// ExamInfo  qamode   書面問答類型 0:書面問答 1:紙本測驗 2:艺术评测
+                    /// </summary>
+                    //艺术评测
+                    if (log.path.Contains("art") ||log.path.Contains("aclassone/find-children-activity")  ||log.path.Contains("aclassone/find-teacher-activity") ||log.path.Contains("aclassone/find-summary-activity") ||log.path.Contains("aclassone/upload-all") ||log.path.Contains("aclassone/delete"))
+                    {
+                        vist.client="art";
+
+                    }
+
+                    if (log.path.Contains("habb"))
+                    {
+                        vist.client="habb";
+                    }
+                    //阅卷客户端
+                    if (log.path.Contains("hiscan"))
+                    {
+                        vist.client="hiscan";
+                    }
+                    if (log.path.Contains("hita"))
+                    {
+                        vist.client="hita";
+                    }
+                    if (log.path.Contains("hiteachcc"))
+                    {
+                        vist.client="hiteachcc";
+                    }
+                    if (log.path.Contains("sokrate"))
+                    {
+                        vist.client="sokrate";
+                    }
+                    if (log.path.Contains("sokrate") || log.path.Contains("score"))
+                    {
+                        vist.client="sokrate";
+                    }
+
+                    if (log.path.Contains("hiteach"))
+                    {
+                        vist.client="hiteach";
+                    }
+                    ///IES开放平台
+                    if (log.path.Contains("business")  || log.path.Contains("biz") || log.path.Contains("openapi-config")  || log.path.Contains("open-api"))
+                    {
+                        vist.client="open";
+                    }
+                    //从token的role 能否获取 开放平台
+                    //单点登录及第三方接口
+                    if (log.path.Contains("lepei") || log.path.Contains("sc/")  || log.path.Contains("/sso") || log.path.Contains("sc-init") || log.path.Contains("data-push") || log.path.Contains("xkw")|| log.path.Contains("tianbo")
+                        || log.path.Contains("oauth/check-bind")|| log.path.Contains("dingding")  || log.path.Contains("wechat")
+                        )
+                    {
+                        vist.client="sso-third";
+                    }
                 }
-                else  if (log.host.Equals("localhost")  && ( log.p.Equals("bi")))
+
+                //处理IP转地区
+                vist.region=_ipSearcher.SearchIp(vist.ip);
+                if (!string.IsNullOrWhiteSpace(vist.region))
                 {
-                    log.host="bitest.teammodel.cn";
+                    var regions = vist.region.Split("·");
+                    if (regions.Length==4) 
+                    {
+                        vist.area=  regions[0];
+                        vist.province   = regions[1];
+                        vist.city = regions[2];
+                    }
+                    if (regions.Length==3)
+                    {
+                        vist.area=  regions[0];
+                        vist.province   = regions[1];
+                    }
+                    if (regions.Length==2)
+                    {
+                        vist.area=  regions[0];
+                        vist.province   = regions[1];
+                    }
+                    if (regions.Length==1)
+                    {
+                        vist.area=  regions[0];
+                    }
+                }
+                //处理地区转经纬度
+                { 
+                    
                 }
                 vist.host= log.host;
+                vist.hostName=log.hostName;
             }
             return (vists, uuidInfo);
         }
@@ -1326,11 +1526,16 @@ namespace TEAMModelOS.Controllers
         public string tname { get; set; }
         public string school { get; set; }
         public string ip { get; set; }
+        public string region { get; set; }
+        public string area { get; set; }
+        public string province { get; set; }
+        public string city { get; set; }
         public long time { get; set; }
         /// <summary>
         /// 
         /// </summary>
         public string host { get; set; }
+        public string hostName = "其他";
         /// <summary>
         /// tokenid
         /// </summary>
@@ -1342,6 +1547,7 @@ namespace TEAMModelOS.Controllers
         public string ip { get; set; }
         public long time { get; set; }
         public string host { get; set; }
+        public string hostName = "其他";
         public string tid { get; set; }
         public string path { get; set; }
         public string client { get; set; }

+ 36 - 0
TEAMModelOS/Filter/IpToRegion.cs

@@ -0,0 +1,36 @@
+using IP2Region.Net.Abstractions;
+using System.Threading.Tasks;
+using System;
+
+namespace TEAMModelOS
+{
+    public static class IpToRegion
+    {
+        public static string  SearchIp(this ISearcher _ipSearcher, string ip)
+        {
+            if (ip.Contains("::"))
+            {
+                ip = "127.0.0.1";
+            }
+            try
+            {
+                string region = _ipSearcher.Search(ip);
+                if (!string.IsNullOrWhiteSpace(region))
+                {
+                    region =region.Replace("0|0|0|0|", "").Replace("0|0|0|", "").Replace("|0|0|0|0", "").Replace("|0|0|0|", "").Replace("|0|0|0", "").Replace("|0|0|", "").Replace("|0|0", "").Replace("|0|", "·").Replace("|0", "").Replace("|", "·");
+                    //if (!string.IsNullOrWhiteSpace(region))
+                    //{
+                    //    region = region.Replace("中国·", "").Replace("中国", "").Replace("台湾省", "台湾");
+                    //}
+                    return region;
+                }
+                else { return null; }
+
+            }
+            catch (Exception)
+            {
+                return string.Empty;
+            }
+        }
+    }
+}

+ 145 - 96
TEAMModelOS/Filter/RequestAuditFilter.cs

@@ -16,6 +16,7 @@ using TEAMModelOS.SDK.DI;
 using Microsoft.Extensions.Primitives;
 using HTEXLib.Helpers.ShapeHelpers;
 using TEAMModelOS.Controllers;
+using System.Net;
 
 namespace TEAMModelOS.Filter
 {
@@ -23,128 +24,176 @@ namespace TEAMModelOS.Filter
     {
         //private readonly ILogger _logger;
         private readonly HttpTrigger _httpTrigger;
-        public RequestAuditFilter(/*ILoggerFactory loggerFactory*/HttpTrigger httpTrigger)
+        private readonly DingDing _dingding;
+        public RequestAuditFilter(/*ILoggerFactory loggerFactory*/HttpTrigger httpTrigger, DingDing dingding)
         {
             //  _logger = loggerFactory.CreateLogger<RequestAuditFilter>();
             _httpTrigger = httpTrigger;
+            _dingding=dingding;
         }
         public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
         {
-            string id = string.Empty, name = string.Empty, picture = string.Empty, school = string.Empty, scope = string.Empty, roles = string.Empty;
-                 
-            //============== 这里是执行方法之前获取数据 ====================
+            try
+            {
+                string id = string.Empty, name = string.Empty, picture = string.Empty, school = string.Empty, scope = string.Empty, roles = string.Empty;
+                //============== 这里是执行方法之前获取数据 ====================
 
-            // 获取控制器、路由信息
-            //var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
+                // 获取控制器、路由信息
+                //var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
 
-            // 获取请求的方法
-            //var method = actionDescriptor.MethodInfo;
+                // 获取请求的方法
+                //var method = actionDescriptor.MethodInfo;
 
-            // 获取 HttpContext 和 HttpRequest 对象
-            var httpContext = context.HttpContext;
-           string ua = httpContext.GetUserAgent();
-            var httpRequest = httpContext.Request;
+                // 获取 HttpContext 和 HttpRequest 对象
+                var httpContext = context.HttpContext;
+                string ua = httpContext.GetUserAgent();
+                var httpRequest = httpContext.Request;
 
-            // 获取客户端 Ipv4 地址
-            var remoteIPv4 = httpContext.GetRemoteIpAddressToIPv4();
+                // 获取客户端 Ipv4 地址
+                var remoteIPv4 = httpContext.GetRemoteIpAddressToIPv4();
 
-            // 获取请求的 Url 地址
-            // var requestUrl = httpRequest.GetRequestUrlAddress();
+                // 获取请求的 Url 地址
+                // var requestUrl = httpRequest.GetRequestUrlAddress();
 
 
-            // 获取来源 Url 地址
-            var refererUrl = httpRequest.GetRefererUrlAddress();
+                // 获取来源 Url 地址
+                var refererUrl = httpRequest.GetRefererUrlAddress();
 
-            // 获取请求参数(写入日志,需序列化成字符串后存储)
-            var parameters = context.ActionArguments;
+                // 获取请求参数(写入日志,需序列化成字符串后存储)
+                var parameters = context.ActionArguments;
 
-            // 获取操作人(必须授权访问才有值)"userId" 为你存储的 claims type,jwt 授权对应的是 payload 中存储的键名
-            //var userId = httpContext.User?.FindFirstValue("userId");
-            var authtoken = context.HttpContext.GetXAuth("AuthToken");
-            string tokenSha = string.Empty, client = string.Empty;
-            if (context.HttpContext.Request.Headers.TryGetValue("Authorization", out StringValues Authorization))
-            {
-                var jwt = new JwtSecurityTokenHandler().ReadJwtToken(Authorization.ToString().Replace("Bearer ", ""));
-                client= roles = jwt.Claims.FirstOrDefault(claim => claim.Type.Equals("roles"))?.Value;
-                tokenSha= ShaHashHelper.GetSHA1(Authorization.ToString());
-            }
-            if (context.HttpContext.Request.Headers.TryGetValue("X-Auth-IdToken", out StringValues XAuthIdToken))
-            {
-                var jwt = new JwtSecurityTokenHandler().ReadJwtToken(XAuthIdToken);
-                id = jwt.Payload.Sub;
-                name = jwt.Claims.FirstOrDefault(claim => claim.Type.Equals("name"))?.Value;
-                if (string.IsNullOrEmpty(tokenSha))
+                // 获取操作人(必须授权访问才有值)"userId" 为你存储的 claims type,jwt 授权对应的是 payload 中存储的键名
+                //var userId = httpContext.User?.FindFirstValue("userId");
+                var authtoken = context.HttpContext.GetXAuth("AuthToken");
+                string tokenSha = string.Empty, client = string.Empty;
+                if (context.HttpContext.Request.Headers.TryGetValue("Authorization", out StringValues Authorization) && Authorization.Any())
                 {
-                    tokenSha= ShaHashHelper.GetSHA1(XAuthIdToken.ToString());
+                    try
+                    {
+                        var jwt = new JwtSecurityTokenHandler().ReadJwtToken(Authorization.ToString().Replace("Bearer ", ""));
+                        client= roles = jwt.Claims.FirstOrDefault(claim => claim.Type.Equals("roles"))?.Value;
+                        tokenSha= ShaHashHelper.GetSHA1(Authorization.ToString());
+                    }
+                    catch (Exception ex)
+                    {
+                       // await _dingding.SendBotMsg($"{ex.Message}\n{ex.StackTrace}\n{Authorization}\n{httpRequest.PathBase}{httpRequest.Path}", GroupNames.成都开发測試群組);
+                    }
                 }
-            }
-            if (context.HttpContext.Request.Headers.TryGetValue("X-Auth-School", out StringValues XAuthSchool))
-            {
-                try
+                if (context.HttpContext.Request.Headers.TryGetValue("X-Auth-IdToken", out StringValues XAuthIdToken)  && XAuthIdToken.Any())
                 {
-                    school = XAuthSchool.ToString();
+                    try
+                    {
+                        var jwt = new JwtSecurityTokenHandler().ReadJwtToken(XAuthIdToken.ToString());
+                        id = jwt.Payload.Sub;
+                        name = jwt.Claims.FirstOrDefault(claim => claim.Type.Equals("name"))?.Value;
+                        if (string.IsNullOrEmpty(tokenSha))
+                        {
+                            tokenSha= ShaHashHelper.GetSHA1(XAuthIdToken.ToString());
+                        }
+                    }
+                    catch (Exception ex)
+                    {
+                        await _dingding.SendBotMsg($"{ex.Message}\n{ex.StackTrace}\n{XAuthIdToken}\n{httpRequest.PathBase}{httpRequest.Path}", GroupNames.成都开发測試群組);
+                    }
                 }
-                catch (Exception ex) { }
-            }
 
-            if (!string.IsNullOrWhiteSpace(authtoken))
-            {
-                var jwt = new JwtSecurityTokenHandler().ReadJwtToken(authtoken);
-                id = jwt.Payload.Sub;
-                school = jwt.Payload.Azp;
-                name = jwt.Claims.FirstOrDefault(claim => claim.Type.Equals("name"))?.Value;
-                scope = jwt.Claims.FirstOrDefault(claim => claim.Type.Equals("scope"))?.Value;
+                if (context.HttpContext.Request.Headers.TryGetValue("X-Auth-School", out StringValues XAuthSchool) && XAuthSchool.Any())
+                {
+                    try
+                    {
+                        school = XAuthSchool.ToString();
+                    }
+                    catch (Exception ex) { }
+                }
+                if (context.HttpContext.Request.Headers.TryGetValue("X-Auth-ApiToken", out StringValues XAutApiToken) && XAutApiToken.Any())
+                {
+                    try
+                    {
+                        var jwt = new JwtSecurityTokenHandler().ReadJwtToken(XAutApiToken);
+                        id = jwt.Payload.Sub;
+
+                        if (string.IsNullOrEmpty(tokenSha))
+                        {
+                            tokenSha= jwt.Payload.Jti;
+                        }
+                        client="Open";
+                    }
+                    catch (Exception ex) {
+
+                        await _dingding.SendBotMsg($"{ex.Message}\n{ex.StackTrace}\n{XAutApiToken}\n{httpRequest.PathBase}{httpRequest.Path}", GroupNames.成都开发測試群組);
+                    }
+                }
+                if (!string.IsNullOrWhiteSpace(authtoken))
+                {
+                    try
+                    {
+                        var jwt = new JwtSecurityTokenHandler().ReadJwtToken(authtoken);
+                        id = jwt.Payload.Sub;
+                        school = jwt.Payload.Azp;
+                        name = jwt.Claims.FirstOrDefault(claim => claim.Type.Equals("name"))?.Value;
+                        scope = jwt.Claims.FirstOrDefault(claim => claim.Type.Equals("scope"))?.Value;
+                        if (string.IsNullOrEmpty(tokenSha))
+                        {
+                            tokenSha= ShaHashHelper.GetSHA1(authtoken);
+                        }
+                    }
+                    catch (Exception ex)
+                    {
+                        await _dingding.SendBotMsg($"{ex.Message}\n{ex.StackTrace}\n{authtoken}\n{httpRequest.PathBase}{httpRequest.Path}", GroupNames.成都开发測試群組);
+                    }
+                }
+                string secChUaPlatform = string.Empty;
+                if (httpContext.Request.Headers.TryGetValue("Sec-Ch-Ua-Platform", out var values))
+                {
+                    secChUaPlatform = values.FirstOrDefault();
+                }
                 if (string.IsNullOrEmpty(tokenSha))
+
                 {
-                    tokenSha= ShaHashHelper.GetSHA1(authtoken);
+                    tokenSha= ShaHashHelper.GetSHA1($"{ua}{remoteIPv4}{httpRequest.Host}{secChUaPlatform}");
                 }
-            }
-            string secChUaPlatform = string.Empty;
-            if (httpContext.Request.Headers.TryGetValue("Sec-Ch-Ua-Platform", out var values))
-            {
-                secChUaPlatform = values.FirstOrDefault();
-            }
-            if (string.IsNullOrEmpty(tokenSha)) 
-            
-            {
-                tokenSha= ShaHashHelper.GetSHA1($"{ua}{remoteIPv4}{httpRequest.Host}{secChUaPlatform}");
-            }
                 // 请求时间
                 var requestedTime = DateTimeOffset.Now.GetGMTTime(8).ToUnixTimeMilliseconds();
-            //============== 这里是执行方法之后获取数据 ====================
-            var actionContext = await next();
-            // 获取返回的结果
-            // var returnResult = actionContext.Result;
-
-            // 判断是否请求成功,没有异常就是请求成功
-            // var isRequestSucceed = actionContext.Exception == null;
-
-            // 获取调用堆栈信息,提供更加简单明了的调用和异常堆栈
-            // var stackTrace = EnhancedStackTrace.Current();
-            // string region = await _searcher.SearchIpAsync(remoteIPv4);
-            //同一个账号,同一IP,同一接口,UA标识(UA标识随意切换则表示可能会存在DDOS),时间段
-            //_logger.LogInformation(new{ ua=httpContext.GetUserAgent(), ip=remoteIPv4,time=requestedTime,path =$"{httpRequest.PathBase}{httpRequest.Path}",host= $"{httpRequest.Host}", param=parameters,id ,name ,school,succeed =isRequestSucceed }.ToJsonString());
-          
-            var data = new  
+                //============== 这里是执行方法之后获取数据 ====================
+                var actionContext = await next();
+                // 获取返回的结果
+                // var returnResult = actionContext.Result;
+
+                // 判断是否请求成功,没有异常就是请求成功
+                // var isRequestSucceed = actionContext.Exception == null;
+
+                // 获取调用堆栈信息,提供更加简单明了的调用和异常堆栈
+                // var stackTrace = EnhancedStackTrace.Current();
+                // string region = await _searcher.SearchIpAsync(remoteIPv4);
+                //同一个账号,同一IP,同一接口,UA标识(UA标识随意切换则表示可能会存在DDOS),时间段
+                //_logger.LogInformation(new{ ua=httpContext.GetUserAgent(), ip=remoteIPv4,time=requestedTime,path =$"{httpRequest.PathBase}{httpRequest.Path}",host= $"{httpRequest.Host}", param=parameters,id ,name ,school,succeed =isRequestSucceed }.ToJsonString());
+
+                var data = new
+                {
+                    //ua =ua,
+                    ip = remoteIPv4,
+                    time = requestedTime,
+                    path = $"{httpRequest.PathBase}{httpRequest.Path}",
+                    host = $"{httpRequest.Host}",
+                    param = parameters,
+                    id = id,
+                    name = name,
+                    school = school,
+                    client = client,
+                    tid = tokenSha,
+                    scope = scope,
+                    // referer = refererUrl,
+                    //platform = secChUaPlatform,
+                    p = "os",
+                    //idToken=XAuthIdToken
+                };
+                _= _httpTrigger.RequestHttpTrigger(data, "China", "http-log");
+            }
+            catch (Exception ex)
             {
-                //ua =ua,
-                ip = remoteIPv4,
-                time = requestedTime,
-                path = $"{httpRequest.PathBase}{httpRequest.Path}",
-                host = $"{httpRequest.Host}",
-                param = parameters,
-                id = id,
-                name = name,
-                school = school,
-                client = client,
-                tid = tokenSha,
-                scope = scope,
-                // referer = refererUrl,
-                //platform = secChUaPlatform,
-                p = "os",
-                //idToken=XAuthIdToken
-            };
-            _= _httpTrigger.RequestHttpTrigger(data, "China", "http-log");
+                await _dingding.SendBotMsg($"{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
+                var actionContext = await next();
+            }
 
         }
     }

二進制
TEAMModelOS/JsonFile/Core/ip2region.xdb


File diff suppressed because it is too large
+ 26690 - 0
TEAMModelOS/JsonFile/Core/latlng.json


+ 5 - 0
TEAMModelOS/Startup.cs

@@ -1,6 +1,7 @@
 using System;
 using System.Collections.Generic;
 using System.IdentityModel.Tokens.Jwt;
+using System.IO;
 using System.IO.Compression;
 using System.Linq;
 using System.Net.Http;
@@ -14,6 +15,8 @@ using DinkToPdf;
 using DinkToPdf.Contracts;
 using HTEXLib.Builders;
 using HTEXLib.Translator;
+using IP2Region.Net.Abstractions;
+using IP2Region.Net.XDB;
 using Lib.AspNetCore.ServerSentEvents;
 using Microsoft.AspNetCore.Authentication.JwtBearer;
 using Microsoft.AspNetCore.Builder;
@@ -159,6 +162,8 @@ namespace TEAMModelOS
             string path = $"{ environment.ContentRootPath}/JsonFile/Core";
             services.AddHtexTranslator(path);
             services.AddIPSearcher(path);
+            
+            services.AddSingleton<ISearcher>(new Searcher(CachePolicy.File, Path.Combine(path, "ip2region.xdb")));
             services.AddServerSentEvents(o =>
             {
                 o.KeepaliveMode = ServerSentEventsKeepaliveMode.Always;

+ 4 - 0
TEAMModelOS/TEAMModelOS.csproj

@@ -7,6 +7,7 @@
     <PackageReference Include="DotNetZip" Version="1.16.0" />
 	<PackageReference Include="DinkToPdf" Version="1.0.8" />
 	<PackageReference Include="EPPlus" Version="6.2.6" />
+	<PackageReference Include="IP2Region.Net" Version="2.0.2" />
 	<PackageReference Include="JsonPath.Net" Version="0.7.1" />
     <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
 	<PackageReference Include="SKIT.FlurlHttpClient.Wechat.TenpayV3" Version="2.20.0" />
@@ -63,6 +64,9 @@
 		<None Update="JsonFile\Core\ip2region.db">
 		  <CopyToOutputDirectory>Always</CopyToOutputDirectory>
 		</None>
+		<None Update="JsonFile\Core\ip2region.xdb">
+		  <CopyToOutputDirectory>Always</CopyToOutputDirectory>
+		</None>
 		<None Update="JsonFile\Core\mail.html">
 		  <CopyToOutputDirectory>Always</CopyToOutputDirectory>
 		</None>