Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Add storefront API endpoint for file download.

Matthew Kennedy214b3ca78ef3
diff --git a/api/app/controllers/spree/api/v2/storefront/digitals_controller.rb b/api/app/controllers/spree/api/v2/storefront/digitals_controller.rb
new file mode 100644
index 0000000000..65749de8f7
--- /dev/null
+++ b/api/app/controllers/spree/api/v2/storefront/digitals_controller.rb
@@ -0,0 +1,40 @@
+module Spree
+ module Api
+ module V2
+ module Storefront
+ class DigitalsController < ::Spree::Api::V2::ResourceController
+ def download
+ if attachment.present?
+ if digital_link.authorize!
+ send_file(
+ ActiveStorage::Blob.service.path_for(attachment.key),
+ filename: attachment.record.attachment_file_name,
+ type: attachment.record.attachment_content_type,
+ status: :ok
+ ) and return
+ end
+ else
+ Rails.logger.error I18n.t('spree.api.v2.digitals.missing_file')
+ end
+
+ render json: { error: I18n.t('spree.api.v2.digitals.unauthorized') }, status: 403
+ end
+
+ private
+
+ def model_class
+ Spree::Digital
+ end
+
+ def digital_link
+ @digital_link ||= DigitalLink.find_by!(token: params[:token])
+ end
+
+ def attachment
+ @attachment ||= digital_link.digital.try(:attachment) if digital_link.present?
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/api/config/locales/en.yml b/api/config/locales/en.yml
index 83c3eba6fb..7eb8f34287 100644
--- a/api/config/locales/en.yml
+++ b/api/config/locales/en.yml
@@ -40,3 +40,6 @@ en:
must_be_an_integer: "Sorry, you must pass an integer value, eg. 5"
cms_sections:
pass_position_index: "Pass 'new_position_idx' with an interger value in the request body"
+ digitals:
+ unauthorized: "Error, you are not authorized to access this asset"
+ missing_file: "Missing Digital Item: attachment"
diff --git a/api/config/routes.rb b/api/config/routes.rb
index edadd8876b..5ad25f44c4 100644
--- a/api/config/routes.rb
+++ b/api/config/routes.rb
@@ -178,6 +178,8 @@ Spree::Core::Engine.add_routes do
delete 'remove_item/:item_id', to: 'wishlists#remove_item', as: :remove_item
end
end
+
+ get '/digitals/:token', to: 'digitals#download', as: 'digital'
end
namespace :platform do