Select Git revision
filedrop_file.rb

Teal authored
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