content_security_policy.rb 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. def sso_host
  13. return unless ENV['ONE_CLICK_SSO_LOGIN'] == 'true' && ENV['OMNIAUTH_ONLY'] == 'true' && Devise.omniauth_providers.length == 1
  14. provider = Devise.omniauth_configs[Devise.omniauth_providers[0]]
  15. @sso_host ||= begin
  16. case provider.provider
  17. when :cas
  18. provider.cas_url
  19. when :saml
  20. provider.options[:idp_sso_target_url]
  21. when :openid_connect
  22. provider.options.dig(:client_options, :authorization_endpoint) || OpenIDConnect::Discovery::Provider::Config.discover!(provider.options[:issuer]).authorization_endpoint
  23. end
  24. end
  25. end
  26. private
  27. def url_from_configured_asset_host
  28. Rails.configuration.action_controller.asset_host
  29. end
  30. def cdn_host_value
  31. s3_alias_host || s3_cloudfront_host || azure_alias_host || s3_hostname_host || swift_object_url
  32. end
  33. def paperclip_root_url
  34. root_url = ENV.fetch('PAPERCLIP_ROOT_URL', nil)
  35. return if root_url.blank?
  36. (Addressable::URI.parse(assets_host) + root_url).tap do |uri|
  37. uri.path += '/' unless uri.path.blank? || uri.path.end_with?('/')
  38. end.to_s
  39. end
  40. def url_from_base_host
  41. host_to_url(base_host)
  42. end
  43. def host_to_url(host_string)
  44. uri_from_configuration_and_string(host_string) if host_string.present?
  45. end
  46. def s3_alias_host
  47. host_to_url ENV.fetch('S3_ALIAS_HOST', nil)
  48. end
  49. def s3_cloudfront_host
  50. host_to_url ENV.fetch('S3_CLOUDFRONT_HOST', nil)
  51. end
  52. def azure_alias_host
  53. host_to_url ENV.fetch('AZURE_ALIAS_HOST', nil)
  54. end
  55. def s3_hostname_host
  56. host_to_url ENV.fetch('S3_HOSTNAME', nil)
  57. end
  58. def swift_object_url
  59. url = ENV.fetch('SWIFT_OBJECT_URL', nil)
  60. return if url.blank? || !url.start_with?('https://')
  61. url += '/' unless url.end_with?('/')
  62. url
  63. end
  64. def uri_from_configuration_and_string(host_string)
  65. Addressable::URI.parse("#{host_protocol}://#{host_string}").tap do |uri|
  66. uri.path += '/' unless uri.path.blank? || uri.path.end_with?('/')
  67. end.to_s
  68. end
  69. def host_protocol
  70. Rails.configuration.x.use_https ? 'https' : 'http'
  71. end
  72. end