attachments_controller.rb 2.2 KB

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