sets_headers.rb 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. # Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. module ApplicationController::SetsHeaders
  3. extend ActiveSupport::Concern
  4. included do
  5. before_action :cors_preflight_check
  6. after_action :set_access_control_headers, :set_cache_control_headers
  7. end
  8. private
  9. # For all responses in this controller, return the CORS access control headers.
  10. def set_access_control_headers
  11. return if @_auth_type != 'token_auth' && @_auth_type != 'basic_auth'
  12. set_access_control_headers_execute
  13. end
  14. def set_access_control_headers_execute
  15. headers['Access-Control-Allow-Origin'] = '*'
  16. headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE, PATCH, OPTIONS'
  17. headers['Access-Control-Max-Age'] = '1728000'
  18. headers['Access-Control-Allow-Headers'] = 'Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control, Accept-Language' # rubocop:disable Zammad/DetectTranslatableString
  19. end
  20. def set_cache_control_headers
  21. # by default http cache is disabled
  22. # expires_now function only sets no-cache so we handle the headers by our own.
  23. headers['Cache-Control'] = 'no-cache, no-store, max-age=0, must-revalidate'
  24. headers['Pragma'] = 'no-cache'
  25. headers['Expires'] = '-1'
  26. end
  27. # If this is a preflight OPTIONS request, then short-circuit the
  28. # request, return only the necessary headers and return an empty
  29. # text/plain.
  30. def cors_preflight_check
  31. return if request.method != 'OPTIONS'
  32. headers['Access-Control-Allow-Origin'] = '*'
  33. headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE, PATCH, OPTIONS'
  34. headers['Access-Control-Allow-Headers'] = 'Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control, Accept-Language' # rubocop:disable Zammad/DetectTranslatableString
  35. headers['Access-Control-Max-Age'] = '1728000'
  36. render plain: ''
  37. end
  38. end
  39. module ActionDispatch
  40. class Response
  41. def merge_and_normalize_cache_control!(...)
  42. # Mutilate this Rails 6.1 method which does not allow us to specify
  43. # our custom Cache-Control header.
  44. end
  45. end
  46. end