RecordAPIOperationMiddleware.cs 15 KB

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