attachments_controller.rb 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. # Copyright (C) 2012-2022 Zammad Foundation, https://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. view_type = params[:preview] ? 'preview' : nil
  8. send_data(
  9. download_file.content(view_type),
  10. filename: download_file.filename,
  11. type: download_file.content_type,
  12. disposition: download_file.disposition
  13. )
  14. end
  15. def create
  16. file = params[:File]
  17. content_type = file.content_type
  18. if !content_type || content_type == 'application/octet-stream'
  19. content_type = if MIME::Types.type_for(file.original_filename).first
  20. MIME::Types.type_for(file.original_filename).first.content_type
  21. else
  22. 'application/octet-stream'
  23. end
  24. end
  25. headers_store = {
  26. 'Content-Type' => content_type
  27. }
  28. store = Store.create!(
  29. object: 'UploadCache',
  30. o_id: params[:form_id],
  31. data: file.read,
  32. filename: file.original_filename,
  33. preferences: headers_store
  34. )
  35. render json: {
  36. success: true,
  37. data: {
  38. id: store.id,
  39. filename: file.original_filename,
  40. size: store.size,
  41. }
  42. }
  43. end
  44. def destroy
  45. Store.remove_item(download_file.id)
  46. render json: {
  47. success: true,
  48. }
  49. end
  50. def destroy_form
  51. Store.remove(
  52. object: 'UploadCache',
  53. o_id: params[:form_id],
  54. )
  55. render json: {
  56. success: true,
  57. }
  58. end
  59. private
  60. def authorize!
  61. record = download_file&.store_object&.name&.safe_constantize&.find(download_file.o_id)
  62. authorize(record) if record
  63. rescue Pundit::NotAuthorizedError
  64. raise ActiveRecord::RecordNotFound
  65. end
  66. end