sets_headers.rb 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. module ApplicationController::SetsHeaders
  2. extend ActiveSupport::Concern
  3. included do
  4. before_action :cors_preflight_check
  5. after_action :set_access_control_headers, :set_cache_control_headers
  6. end
  7. private
  8. # For all responses in this controller, return the CORS access control headers.
  9. def set_access_control_headers
  10. return if @_auth_type != 'token_auth' && @_auth_type != 'basic_auth'
  11. set_access_control_headers_execute
  12. end
  13. def set_access_control_headers_execute
  14. headers['Access-Control-Allow-Origin'] = '*'
  15. headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE, PATCH, OPTIONS'
  16. headers['Access-Control-Max-Age'] = '1728000'
  17. 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'
  18. end
  19. def set_cache_control_headers
  20. # by default http cache is disabled
  21. # expires_now function only sets no-cache so we handle the headers by our own.
  22. headers['Cache-Control'] = 'no-cache, no-store, max-age=0, must-revalidate'
  23. headers['Pragma'] = 'no-cache'
  24. headers['Expires'] = '-1'
  25. end
  26. # If this is a preflight OPTIONS request, then short-circuit the
  27. # request, return only the necessary headers and return an empty
  28. # text/plain.
  29. def cors_preflight_check
  30. return if request.method != 'OPTIONS'
  31. headers['Access-Control-Allow-Origin'] = '*'
  32. headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE, PATCH, OPTIONS'
  33. 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'
  34. headers['Access-Control-Max-Age'] = '1728000'
  35. render plain: ''
  36. end
  37. end