RecordAPIOperationMiddleware.cs 15 KB

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