content_security_policy.rb 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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].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 url_from_base_host
  20. host_to_url(base_host)
  21. end
  22. def host_to_url(host_string)
  23. uri_from_configuration_and_string(host_string) if host_string.present?
  24. end
  25. def s3_alias_host
  26. host_to_url ENV.fetch('S3_ALIAS_HOST', nil)
  27. end
  28. def s3_cloudfront_host
  29. host_to_url ENV.fetch('S3_CLOUDFRONT_HOST', nil)
  30. end
  31. def azure_alias_host
  32. host_to_url ENV.fetch('AZURE_ALIAS_HOST', nil)
  33. end
  34. def s3_hostname_host
  35. host_to_url ENV.fetch('S3_HOSTNAME', nil)
  36. end
  37. def uri_from_configuration_and_string(host_string)
  38. Addressable::URI.parse("#{host_protocol}://#{host_string}").tap do |uri|
  39. uri.path += '/' unless uri.path.blank? || uri.path.end_with?('/')
  40. end.to_s
  41. end
  42. def host_protocol
  43. Rails.configuration.x.use_https ? 'https' : 'http'
  44. end
  45. end