logs_http_access.rb 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. module ApplicationController::LogsHttpAccess
  3. extend ActiveSupport::Concern
  4. included do
  5. after_action :http_log
  6. end
  7. private
  8. def http_log_config(config)
  9. @http_log_support = config
  10. end
  11. # log http access
  12. def http_log
  13. return if !@http_log_support
  14. # request
  15. request_data = {
  16. content: '',
  17. content_type: request.headers['Content-Type'],
  18. content_encoding: request.headers['Content-Encoding'],
  19. source: request.headers['User-Agent'] || request.headers['Server'],
  20. }
  21. request.headers.each do |key, value|
  22. next if key[0, 5] != 'HTTP_'
  23. request_data[:content] += if key == 'HTTP_COOKIE'
  24. "#{key}: xxxxx\n"
  25. else
  26. "#{key}: #{value}\n"
  27. end
  28. end
  29. body = request.body.read
  30. if body
  31. request_data[:content] += "\n#{body}"
  32. end
  33. request_data[:content] = request_data[:content].slice(0, 8000)
  34. # response
  35. response_data = {
  36. code: response.status = response.code,
  37. content: '',
  38. content_type: nil,
  39. content_encoding: nil,
  40. source: nil,
  41. }
  42. response.headers.each do |key, value|
  43. response_data[:content] += "#{key}: #{value}\n"
  44. end
  45. body = response.body
  46. if body
  47. response_data[:content] += "\n#{body}"
  48. end
  49. response_data[:content] = response_data[:content].slice(0, 8000)
  50. record = {
  51. direction: 'in',
  52. facility: @http_log_support[:facility],
  53. url: url_for(only_path: false, overwrite_params: {}),
  54. status: response.status,
  55. ip: request.remote_ip,
  56. request: request_data,
  57. response: response_data,
  58. method: request.method,
  59. }
  60. HttpLog.create(record)
  61. end
  62. end