content_security_policy.rb 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # frozen_string_literal: true
  2. class ContentSecurityPolicy
  3. def base_host
  4. Rails.configuration.x.web_domain
  5. end
  6. def assets_host
  7. url_from_configured_asset_host || url_from_base_host
  8. end
  9. def media_hosts
  10. [assets_host, cdn_host_value, paperclip_root_url].compact
  11. end
  12. private
  13. def url_from_configured_asset_host
  14. Rails.configuration.action_controller.asset_host
  15. end
  16. def cdn_host_value
  17. s3_alias_host || s3_cloudfront_host || azure_alias_host || s3_hostname_host
  18. end
  19. def paperclip_root_url
  20. root_url = ENV.fetch('PAPERCLIP_ROOT_URL', nil)
  21. return if root_url.blank?
  22. (Addressable::URI.parse(assets_host) + root_url).tap do |uri|
  23. uri.path += '/' unless uri.path.blank? || uri.path.end_with?('/')
  24. end.to_s
  25. end
  26. def url_from_base_host
  27. host_to_url(base_host)
  28. end
  29. def host_to_url(host_string)
  30. uri_from_configuration_and_string(host_string) if host_string.present?
  31. end
  32. def s3_alias_host
  33. host_to_url ENV.fetch('S3_ALIAS_HOST', nil)
  34. end
  35. def s3_cloudfront_host
  36. host_to_url ENV.fetch('S3_CLOUDFRONT_HOST', nil)
  37. end
  38. def azure_alias_host
  39. host_to_url ENV.fetch('AZURE_ALIAS_HOST', nil)
  40. end
  41. def s3_hostname_host
  42. host_to_url ENV.fetch('S3_HOSTNAME', nil)
  43. end
  44. def uri_from_configuration_and_string(host_string)
  45. Addressable::URI.parse("#{host_protocol}://#{host_string}").tap do |uri|
  46. uri.path += '/' unless uri.path.blank? || uri.path.end_with?('/')
  47. end.to_s
  48. end
  49. def host_protocol
  50. Rails.configuration.x.use_https ? 'https' : 'http'
  51. end
  52. end