RecordAPIOperationMiddleware.cs 13 KB

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