diff --git a/api/app/controllers/spree/api/images_controller.rb b/api/app/controllers/spree/api/images_controller.rb index c18a9b757d1..04524993770 100644 --- a/api/app/controllers/spree/api/images_controller.rb +++ b/api/app/controllers/spree/api/images_controller.rb @@ -15,7 +15,11 @@ def show def create authorize! :create, Image - @image = scope.images.create(image_params) + if valid_url? image_params[:attachment] + @image = scope.images.create(attachment: open(image_params[:attachment])) + else + @image = scope.images.create(image_params) + end respond_with(@image, status: 201, default_template: :show) end @@ -44,6 +48,13 @@ def scope Spree::Variant.find(params[:variant_id]) end end + + def valid_url?(url) + uri = URI.parse url + uri.is_a?(URI::HTTP) && !uri.host.blank? + rescue URI::InvalidURIError + false + end end end end diff --git a/api/spec/requests/spree/api/images_controller_spec.rb b/api/spec/requests/spree/api/images_controller_spec.rb index 6465005058d..63700922a4c 100644 --- a/api/spec/requests/spree/api/images_controller_spec.rb +++ b/api/spec/requests/spree/api/images_controller_spec.rb @@ -17,20 +17,34 @@ module Spree context "as an admin" do sign_in_as_admin! + context "can upload a new image" + it "for a variant" do + expect do + post spree.api_product_images_path(product.id), params: { + image: { + attachment: upload_image('thinking-cat.jpg'), + viewable_type: 'Spree::Variant', + viewable_id: product.master.to_param + }, + } + expect(response.status).to eq(201) + expect(json_response).to have_attributes(attributes) + end.to change(Image, :count).by(1) + end - it "can upload a new image for a variant" do - expect do - post spree.api_product_images_path(product.id), params: { - image: { - attachment: upload_image('thinking-cat.jpg'), - viewable_type: 'Spree::Variant', - viewable_id: product.master.to_param - }, - } - expect(response.status).to eq(201) - expect(json_response).to have_attributes(attributes) - end.to change(Image, :count).by(1) - end + it "from a valid URL" do + expect do + post spree.api_product_images_path(product.id), params: { + image: { + attachment: 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_92x30dp.png', + viewable_type: 'Spree::Variant', + viewable_id: product.master.to_param + }, + } + expect(response.status).to eq(201) + expect(json_response).to have_attributes(attributes) + end.to change(Image, :count).by(1) + end context "working with an existing product image" do let!(:product_image) { product.master.images.create!(attachment: image('thinking-cat.jpg')) }