FIX: `FileHelper` should prioritize response content-type.

Request to a URL with `.png` extension may return a jpg
instead causing us to attach the wrong extension to an
upload.
This commit is contained in:
Guo Xiang Tan 2018-07-30 10:48:44 +08:00
parent fc3b904e1f
commit b94633e844
3 changed files with 29 additions and 6 deletions

View File

@ -32,7 +32,15 @@ class UserAvatar < ActiveRecord::Base
)
if tempfile
upload = UploadCreator.new(tempfile, 'gravatar.png', origin: gravatar_url, type: "avatar").create_for(user_id)
ext = File.extname(tempfile)
ext = '.png' if ext.blank?
upload = UploadCreator.new(
tempfile,
"gravatar#{ext}",
origin: gravatar_url,
type: "avatar"
).create_for(user_id)
if gravatar_upload_id != upload.id
gravatar_upload&.destroy!

View File

@ -54,15 +54,13 @@ class FileHelper
end
end
# first run
tmp_file_ext = File.extname(uri.path)
if tmp_file_ext.blank? && response.content_type.present?
if response.content_type.present?
ext = MiniMime.lookup_by_content_type(response.content_type)&.extension
ext = "jpg" if ext == "jpe"
tmp_file_ext = "." + ext if ext.present?
end
tmp_file_ext ||= File.extname(uri.path)
tmp = Tempfile.new([tmp_file_name, tmp_file_ext])
tmp.binmode
end

View File

@ -12,7 +12,6 @@ describe FileHelper do
end
describe "download" do
it "correctly raises an OpenURI HTTP error if it gets a 404 even with redirect" do
url = "http://fourohfour.com/404"
stub_request(:get, url).to_return(status: 404, body: "404")
@ -69,6 +68,24 @@ describe FileHelper do
)
expect(tmpfile.read[0..5]).to eq("GIF89a")
end
describe 'when url is a jpeg' do
let(:url) { "https://eviltrout.com/trout.jpg" }
it "should prioritize the content type returned by the response" do
stub_request(:get, url).to_return(body: png, headers: {
"content-type": "image/png"
})
tmpfile = FileHelper.download(
url,
max_file_size: 10000,
tmp_file_name: 'trouttmp'
)
expect(File.extname(tmpfile)).to eq('.png')
end
end
end
end