RecordAPIOperationMiddleware.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. using AlibabaCloud.OpenApiClient.Models;
  2. using Aspose.Words;
  3. using NPOI.HSSF.Record;
  4. using OASystem.API.OAMethodLib;
  5. using OASystem.Domain.Attributes;
  6. using OASystem.Domain.Entities.Customer;
  7. using OASystem.Infrastructure.Repositories.CRM;
  8. using System.ComponentModel.DataAnnotations;
  9. using System.Diagnostics;
  10. using static Google.Protobuf.Reflection.SourceCodeInfo.Types;
  11. using static OASystem.API.OAMethodLib.JWTHelper;
  12. using UAParser;
  13. using System.Collections.Generic;
  14. using XAct;
  15. using NPOI.SS.Formula.Functions;
  16. using QuzrtzJob.Factory;
  17. namespace OASystem.API.Middlewares
  18. {
  19. /// <summary>
  20. /// 指定API操作记录信息
  21. /// </summary>
  22. public class RecordAPIOperationMiddleware
  23. {
  24. private readonly RequestDelegate _next;
  25. private readonly HttpClient _httpClient;
  26. private readonly IConfiguration _config;
  27. private readonly SqlSugarClient _sqlSugar;
  28. private readonly ILogger<RecordAPIOperationMiddleware> _logger;
  29. public RecordAPIOperationMiddleware(RequestDelegate next, IConfiguration config, ILogger<RecordAPIOperationMiddleware> logger, HttpClient httpClient, SqlSugarClient sqlSugar)
  30. {
  31. _next = next;
  32. _httpClient = httpClient;
  33. _config = config;
  34. _sqlSugar = sqlSugar;
  35. }
  36. public async Task InvokeAsync(HttpContext context)
  37. {
  38. // 启用请求体流的缓冲,允许多次读取
  39. context.Request.EnableBuffering();
  40. // 读取请求体内容
  41. var requestBodyText = await ReadRequestBody(context.Request);
  42. // 检查控制器方法是否使用了自定义属性
  43. var endpoint = context.GetEndpoint();
  44. var apiLogAttribute = endpoint?.Metadata?.GetMetadata<ApiLogAttribute>();
  45. if (apiLogAttribute != null)
  46. {
  47. var startTime = DateTime.UtcNow;
  48. int portType = 1, userId = 0, id = 0, status = 0;
  49. string updatePreData = string.Empty, updateBefData = string.Empty;
  50. bool param5Bool = false, param6Bool = false;
  51. try
  52. {
  53. userId = await ReadToken(context);
  54. if (!string.IsNullOrEmpty(requestBodyText))
  55. {
  56. object param1 = string.Empty, param2 = string.Empty, param3 = string.Empty, param4 = string.Empty, param5 = string.Empty, param6 = string.Empty;
  57. var requestBodyJson = JsonConvert.DeserializeObject<Dictionary<string, object>>(requestBodyText);
  58. bool exists1 = requestBodyJson.TryGetValue("portType", out param1);
  59. bool exists2 = requestBodyJson.TryGetValue("userId", out param2);
  60. bool exists3 = requestBodyJson.TryGetValue("currUserId", out param3);
  61. bool exists4 = requestBodyJson.TryGetValue("createUserId", out param4);
  62. bool exists5 = requestBodyJson.TryGetValue("id", out param5);
  63. bool exists6 = requestBodyJson.TryGetValue("status", out param6);
  64. if (exists1) int.TryParse(param1.ToString(), out portType);
  65. //用户Id处理
  66. if (userId < 1)
  67. {
  68. if (apiLogAttribute.OperationEnum == OperationEnum.Login)
  69. {
  70. var number = requestBodyJson?["number"].ToString();
  71. if (!string.IsNullOrEmpty(number))
  72. {
  73. var info = await _sqlSugar.Queryable<Sys_Users>().Where(x => x.IsDel == 0 && x.Number.Equals(number)).FirstAsync();
  74. userId = info.Id;
  75. }
  76. }
  77. else
  78. {
  79. if (exists2) if (int.TryParse(param2.ToString(), out userId)) { }
  80. else if (exists3) if (int.TryParse(param3.ToString(), out userId)) { }
  81. else if (exists4) if (int.TryParse(param4.ToString(), out userId)) { }
  82. }
  83. }
  84. //编辑前数据查询;
  85. if (exists5) param5Bool = int.TryParse(param5.ToString(), out id);
  86. if (exists5) param6Bool = int.TryParse(param6.ToString(), out status);
  87. if (param6Bool)
  88. {
  89. // 2 修改
  90. if (status == 2) updatePreData = await TableInfoToJson(apiLogAttribute.TableName, id);
  91. }
  92. else if (param5Bool)
  93. {
  94. // id > 0 修改
  95. if (id > 0) updatePreData = await TableInfoToJson(apiLogAttribute.TableName, id);
  96. }
  97. }
  98. }
  99. catch (JsonException) { }
  100. // 保存原始响应体流
  101. var originalResponseBody = context.Response.Body;
  102. // 创建一个新的内存流来捕获响应体
  103. using var responseMemoryStream = new MemoryStream();
  104. context.Response.Body = responseMemoryStream;
  105. // 调用下一个中间件
  106. await _next(context);
  107. // 重置响应体流的位置
  108. responseMemoryStream.Position = 0;
  109. // 读取响应体内容
  110. var responseBodyText = await ReadResponseBody(responseMemoryStream);
  111. // 将响应体内容写回原始响应体流
  112. await responseMemoryStream.CopyToAsync(originalResponseBody);
  113. //修改后数据查询
  114. if (param6Bool)
  115. {
  116. // 2 修改
  117. if (status == 2) updateBefData = await TableInfoToJson(apiLogAttribute.TableName, id);
  118. }
  119. else if (param5Bool)
  120. {
  121. // id > 0 修改
  122. if (id > 0) updateBefData = await TableInfoToJson(apiLogAttribute.TableName, id);
  123. }
  124. string remoteIp = string.Empty,
  125. location = string.Empty;
  126. // 检查请求头中的X-Forwarded-For,以获取真实的客户端IP地址
  127. if (context.Request.Headers.ContainsKey("X-Forwarded-For"))
  128. {
  129. remoteIp = context.Request.Headers["X-Forwarded-For"].ToString().Split(',', StringSplitOptions.RemoveEmptyEntries)[0];
  130. _logger.LogInformation($"IP:{remoteIp}");
  131. }
  132. else
  133. {
  134. remoteIp = context.Connection.RemoteIpAddress?.ToString();
  135. }
  136. //(remoteIp, location) = await GetIpInfo();
  137. //remoteIp = await GetExternalIp();
  138. //location = await GetIpLocation(remoteIp);
  139. string deviceType = string.Empty, browser = string.Empty, os = string.Empty;
  140. var userAgent = context.Request.Headers["User-Agent"].FirstOrDefault();
  141. if (!string.IsNullOrEmpty(userAgent))
  142. {
  143. // 解析User-Agent头
  144. var parser = Parser.GetDefault();
  145. var client = parser.Parse(userAgent);
  146. // 提取浏览器信息
  147. browser = client.UA.Family; // 浏览器名称
  148. var browserVersion = client.UA.Major + "." + client.UA.Minor + "." + client.UA.Patch; // 浏览器版本
  149. browser += $"({browserVersion})";
  150. // 提取操作系统信息
  151. os = client.OS.Family; // 操作系统名称
  152. var osVersion = string.Empty; // 操作系统版本
  153. if (!string.IsNullOrEmpty(client.OS.Major)) osVersion += client.OS.Major ;
  154. if (!string.IsNullOrEmpty(client.OS.Minor)) osVersion += "." + client.OS.Minor;
  155. if (!string.IsNullOrEmpty(client.OS.Patch)) osVersion += "." + client.OS.Patch;
  156. if (!string.IsNullOrEmpty(osVersion)) os += $"({osVersion})";
  157. // 提取设备信息
  158. deviceType = client.Device.Family; // 设备类型,如 'mobile', 'tablet', 'desktop' 等
  159. }
  160. // 记录请求结束时间
  161. var endTime = DateTime.UtcNow;
  162. // 计算耗时
  163. var duration = (long)(endTime - startTime).TotalMilliseconds;
  164. var logInfo = new Crm_TableOperationRecord() {
  165. TableName = apiLogAttribute.TableName,
  166. PortType = portType,
  167. OperationItem = apiLogAttribute.OperationEnum,
  168. DataId = apiLogAttribute.DataId,
  169. RequestUrl = context.Request.Path,
  170. RemoteIp = remoteIp,
  171. Location = location,
  172. RequestParam =!string.IsNullOrEmpty(requestBodyText) ? JsonConvert.SerializeObject(requestBodyText) : null,
  173. ReturnResult = !string.IsNullOrEmpty(responseBodyText) ? JsonConvert.SerializeObject(responseBodyText) : null,
  174. Elapsed = duration,
  175. Status = context.Response.StatusCode.ToString(),
  176. CreateUserId = userId,
  177. UpdatePreData = updatePreData,
  178. UpdateBefData = updateBefData,
  179. Browser= browser,
  180. Os = os,
  181. DeviceType = deviceType,
  182. };
  183. // 存储到数据库
  184. await _sqlSugar.Insertable(logInfo).ExecuteCommandAsync();
  185. }
  186. else
  187. {
  188. await _next(context);
  189. }
  190. }
  191. private async Task<string> TableInfoToJson(string tableName,int id)
  192. {
  193. if (_sqlSugar.DbMaintenance.IsAnyTable(tableName))
  194. {
  195. var info = await _sqlSugar.Queryable<dynamic>(tableName).Where("id=@id", new { id = id }).FirstAsync();
  196. return JsonConvert.SerializeObject(info);
  197. }
  198. return string.Empty;
  199. }
  200. private async Task<string> ReadRequestBody(HttpRequest request)
  201. {
  202. request.EnableBuffering();
  203. using var reader = new StreamReader(
  204. request.Body,
  205. Encoding.UTF8,
  206. detectEncodingFromByteOrderMarks: false,
  207. bufferSize: 8192,
  208. leaveOpen: true
  209. );
  210. var body = await reader.ReadToEndAsync();
  211. request.Body.Position = 0;
  212. return body;
  213. }
  214. private async Task<string> ReadResponseBody(Stream stream)
  215. {
  216. using var reader = new StreamReader(
  217. stream,
  218. Encoding.UTF8,
  219. detectEncodingFromByteOrderMarks: false,
  220. bufferSize: 8192,
  221. leaveOpen: true
  222. );
  223. var body = await reader.ReadToEndAsync();
  224. stream.Position = 0;
  225. return body;
  226. }
  227. private async Task<int> ReadToken(HttpContext context)
  228. {
  229. var authHeader = context.Request.Headers["Authorization"].FirstOrDefault();
  230. // 检查Authorization头是否存在且以"Bearer "开头
  231. if (!string.IsNullOrEmpty(authHeader) && authHeader.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
  232. {
  233. var authInfo = JwtHelper.SerializeJwt(authHeader);
  234. if (authInfo != null) return authInfo.UserId;
  235. }
  236. return 0;
  237. }
  238. private async Task<(string ip,string local)> GetIpInfo()
  239. {
  240. string ip = string.Empty, local = string.Empty;
  241. var response = await _httpClient.GetAsync("https://api.vore.top/api/IPdata");
  242. response.EnsureSuccessStatusCode();
  243. var json = await response.Content.ReadAsStringAsync();
  244. var ipInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json);
  245. if (ipInfo.code == 200)
  246. {
  247. ip = ipInfo.ipinfo.text;
  248. local = $"{ipInfo.adcode.o}";
  249. }
  250. return (ip,local);
  251. }
  252. private async Task<string> GetExternalIp()
  253. {
  254. var response = await _httpClient.GetAsync("https://ifconfig.me");
  255. response.EnsureSuccessStatusCode();
  256. return await response.Content.ReadAsStringAsync();
  257. }
  258. private async Task<string> GetIpLocation(string ip)
  259. {
  260. var response = await _httpClient.GetAsync($"https://ipinfo.io/{ip}/json?&language=zh-CN");
  261. response.EnsureSuccessStatusCode();
  262. var json = await response.Content.ReadAsStringAsync();
  263. var ipInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json);
  264. return $"{ipInfo.country}, {ipInfo.city}";
  265. }
  266. }
  267. }