RecordAPIOperationMiddleware.cs 15 KB

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