attachments_controller.rb 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. # Copyright (C) 2012-2021 Zammad Foundation, http://zammad-foundation.org/
  2. class AttachmentsController < ApplicationController
  3. prepend_before_action :authorize!, only: %i[show destroy]
  4. prepend_before_action :authentication_check, except: %i[show destroy]
  5. prepend_before_action :authentication_check_only, only: %i[show destroy]
  6. def show
  7. content = @file.content_preview if params[:preview] && @file.preferences[:content_preview]
  8. content ||= @file.content
  9. send_data(
  10. content,
  11. filename: @file.filename,
  12. type: @file.preferences['Content-Type'] || @file.preferences['Mime-Type'] || 'application/octet-stream',
  13. disposition: sanitized_disposition
  14. )
  15. end
  16. def create
  17. file = params[:File]
  18. content_type = file.content_type
  19. if !content_type || content_type == 'application/octet-stream'
  20. content_type = if MIME::Types.type_for(file.original_filename).first
  21. MIME::Types.type_for(file.original_filename).first.content_type
  22. else
  23. 'application/octet-stream'
  24. end
  25. end
  26. headers_store = {
  27. 'Content-Type' => content_type
  28. }
  29. store = Store.add(
  30. object: 'UploadCache',
  31. o_id: params[:form_id],
  32. data: file.read,
  33. filename: file.original_filename,
  34. preferences: headers_store
  35. )
  36. render json: {
  37. success: true,
  38. data: {
  39. id: store.id,
  40. filename: file.original_filename,
  41. size: store.size,
  42. }
  43. }
  44. end
  45. def destroy
  46. Store.remove_item(@file.id)
  47. render json: {
  48. success: true,
  49. }
  50. end
  51. def destroy_form
  52. Store.remove(
  53. object: 'UploadCache',
  54. o_id: params[:form_id],
  55. )
  56. render json: {
  57. success: true,
  58. }
  59. end
  60. private
  61. def sanitized_disposition
  62. disposition = params.fetch(:disposition, 'inline')
  63. valid_disposition = %w[inline attachment]
  64. return disposition if valid_disposition.include?(disposition)
  65. raise Exceptions::Forbidden, "Invalid disposition #{disposition} requested. Only #{valid_disposition.join(', ')} are valid."
  66. end
  67. def authorize!
  68. @file = Store.find(params[:id])
  69. record = @file&.store_object&.name&.safe_constantize&.find(@file.o_id)
  70. authorize(record) if record
  71. rescue Pundit::NotAuthorizedError
  72. raise ActiveRecord::RecordNotFound
  73. end
  74. end