RecordAPIOperationMiddleware.cs 15 KB

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