Securing File Uploads

#14 Securing File Uploads
8/22/2015

Summary

Be default, Refile does not have a way to secure file downloads. It relies on a generated hash that is unknown to users unless the page renders that image or has a download to that file. This is okay sometimes, however, protecting the file from being downloaded for those who have the URL is a bit more involved.
0
rails security uploads

Summary

config/initializers/refile.rb
    Refile.configure do |config|
      # config.allow_uploads_to = ["cache"]
      # config.allow_downloads_from = :all
      # config.allow_origin = "*"
      # config.logger = Logger.new(STDOUT) unless ENV["RACK_ENV"] == "test"
      # config.mount_point = "attachments"
      config.automount = false
      # config.content_max_age = 60 * 60 * 24 * 365
      # config.types[:image] = Refile::Type.new(:image, content_type: %w[image/jpeg image/gif image/png])
    end
config/routes.rb    resources :users do
      get :download
    end
users_controller.rb    def download_file
      @user = User.friendly.find(params[:user_id])
      authorize @user
      send_file @user.resume.download.path, disposition: :inline, filename: @user.resume_filename
    end

    def download
    # def download_image
      @user = User.find(params[:user_id])
      authorize @user
      processor = Refile.processor(:fill, Refile::MiniMagick.new(:fill))
      temp_file = Tempfile.new('profile_image')
      temp_file.binmode
      temp_file.write @user.profile_image.read
      temp_file.rewind
      image_file = MiniMagick::Image.new(temp_file.path)
      file = processor.fill(image_file, 150, 150)
      temp_file.close
      send_file file.path, disposition: :inline, filename: @user.profile_image_filename
    end
app/policies/user_policy.rb    class UserPolicy
      attr_reader :current_user, :user

      def initialize(current_user, user)
        @current_user = current_user
        @user = user
      end

      def download?
        @current_user == @user
      end
    end
show.html.erb    

<p>   <%= image_tag user_download_path(@user) if policy(@user).download? %>     <%# image_tag attachment_url(@user, :profile_image, :fill, 150, 150, format: "jpg") %> </p>

migration to add properties to the profile image    class AddProfilePropertiesToUsers < ActiveRecord::Migration
      def change
        add_column :users, :profile_image_filename, :string
        add_column :users, :profile_image_size, :integer
        add_column :users, :profile_image_content_type, :string
      end
    end