attachments_controller.rb 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. class AttachmentsController < ApplicationController
  2. prepend_before_action :authentication_check, except: %i[show destroy]
  3. prepend_before_action :authentication_check_only, only: %i[show destroy]
  4. before_action :verify_object_permissions, only: %i[show destroy]
  5. def show
  6. content = @file.content_preview if params[:preview] && @file.preferences[:content_preview]
  7. content ||= @file.content
  8. send_data(
  9. content,
  10. filename: @file.filename,
  11. type: @file.preferences['Content-Type'] || @file.preferences['Mime-Type'] || 'application/octet-stream',
  12. disposition: sanitized_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.add(
  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(@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 sanitized_disposition
  61. disposition = params.fetch(:disposition, 'inline')
  62. valid_disposition = %w[inline attachment]
  63. return disposition if valid_disposition.include?(disposition)
  64. raise Exceptions::NotAuthorized, "Invalid disposition #{disposition} requested. Only #{valid_disposition.join(', ')} are valid."
  65. end
  66. def verify_object_permissions
  67. @file = Store.find(params[:id])
  68. klass = @file&.store_object&.name&.safe_constantize
  69. return if klass.send("can_#{params[:action]}_attachment?", @file, current_user)
  70. raise ActiveRecord::RecordNotFound
  71. end
  72. end