Skip to content
Snippets Groups Projects
Select Git revision
  • bbc29c4b503460af44cfd302c1d892087d90b6d9
  • main default protected
  • renovate/redis-5.x-lockfile
  • renovate/ruby
  • renovate/solid_queue-1.x-lockfile
  • renovate/selenium-webdriver-4.x-lockfile
  • renovate/icalendar-2.x-lockfile
  • renovate/debug-1.x-lockfile
  • renovate/turbo-rails-2.x-lockfile
  • renovate/gcr.io-kaniko-project-executor-1.x
  • eh22 protected
  • update-rubocop
12 results

filedrop_file.rb

Blame
  • filedrop_file.rb 1.34 KiB
    class FiledropFile < ApplicationRecord
      belongs_to :session
      validates :checksum, presence: true, format: { with: /\A[0-9a-fA-F]+\z/, message: "only allows hexadecimal characters" }
    
      def sanitize_filename(filename)
        filename.gsub(/[^\w\s.-]/, "_")
      end
    
      def safe_download_path(download_dir, filename)
        sanitized_filename = sanitize_filename(filename)
        output_path = File.join(download_dir, sanitized_filename)
        if File.expand_path(output_path).start_with?(File.expand_path(download_dir))
          output_path
        else
          raise "Invalid filename, potential directory traversal detected!"
        end
      end
    
      def download(url)
        if File.exist?(local_path)
          local_sha1 = Digest::SHA1.file(local_path).hexdigest
          return if local_sha1 == checksum
        end
    
        response = HTTParty.get(url)
        if response.success?
          File.open(local_path, "wb") do |file|
            file.write(response.body)
          end
          Rails.logger.debug("File downloaded successfully and saved as #{local_path}.")
        else
          Rails.logger.warn("Failed to download file #{name} for #{session.ref_id}: #{response.code} #{response.message}")
        end
      end
    
      def local_path
        dir = File.join(
          ActiveStorage::Blob.service.root,
          "filedrop",
          session.conference.slug,
          session.ref_id
        )
        FileUtils.mkdir_p(dir)
        File.join(dir, checksum)
      end
    end