has_download.rb 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. # Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. module ApplicationController::HasDownload
  3. extend ActiveSupport::Concern
  4. included do
  5. around_action do |_controller, block|
  6. subscriber = proc do
  7. policy = ActionDispatch::ContentSecurityPolicy.new
  8. policy.default_src :none
  9. # The 'plugin_types' rule is deprecated and should be changed in the future.
  10. policy.plugin_types 'application/pdf'
  11. request.content_security_policy = policy
  12. end
  13. ActiveSupport::Notifications.subscribed(subscriber, 'send_file.action_controller') do
  14. ActiveSupport::Notifications.subscribed(subscriber, 'send_data.action_controller') do
  15. block.call
  16. end
  17. end
  18. end
  19. end
  20. private
  21. def file_id
  22. @file_id ||= params[:id]
  23. end
  24. def download_file
  25. @download_file ||= ::ApplicationController::HasDownload::DownloadFile.new(file_id, disposition: sanitized_disposition)
  26. end
  27. def sanitized_disposition
  28. disposition = params.fetch(:disposition, 'inline')
  29. valid_disposition = %w[inline attachment]
  30. return disposition if valid_disposition.include?(disposition)
  31. raise Exceptions::Forbidden, "Invalid disposition #{disposition} requested. Only #{valid_disposition.join(', ')} are valid."
  32. end
  33. end