RecordAPIOperationMiddleware.cs 14 KB

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