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.

Generate API V2 oAuth token for Admin Panel

Damian Legawiec402bd1419939
diff --git a/backend/app/controllers/spree/admin/base_controller.rb b/backend/app/controllers/spree/admin/base_controller.rb
index 2a1c5e122c..cec79a5c9d 100644
--- a/backend/app/controllers/spree/admin/base_controller.rb
+++ b/backend/app/controllers/spree/admin/base_controller.rb
@@ -9,6 +9,8 @@ module Spree
before_action :authorize_admin
before_action :generate_admin_api_key
+ helper_method :admin_oauth_token
+
protected
def action
@@ -53,6 +55,27 @@ module Spree
redirect_to edit_admin_order_customer_url(@order)
end
end
+
+ def admin_oauth_application
+ @admin_oauth_application ||= begin
+ Doorkeeper::Application.find_or_create_by!(name: 'Admin Panel', scopes: 'admin write read', redirect_uri: '')
+ end
+ end
+
+ # FIXME: auto-expire this token
+ def admin_oauth_token
+ user = try_spree_current_user
+ return unless user
+
+ @admin_oauth_token ||= begin
+ Doorkeeper::AccessToken.active_for(user).where(application_id: admin_oauth_application.id).last ||
+ Doorkeeper::AccessToken.create!(
+ resource_owner_id: user.id,
+ application_id: admin_oauth_application.id,
+ scopes: admin_oauth_application.scopes
+ )
+ end.token
+ end
end
end
end
diff --git a/backend/app/views/spree/admin/shared/_head.html.erb b/backend/app/views/spree/admin/shared/_head.html.erb
index 61beba6945..89cafe1c9d 100644
--- a/backend/app/views/spree/admin/shared/_head.html.erb
+++ b/backend/app/views/spree/admin/shared/_head.html.erb
@@ -22,6 +22,7 @@
<script>
<%== "var AUTH_TOKEN = #{form_authenticity_token.inspect};" %>
<%== "Spree.api_key = '#{try_spree_current_user.spree_api_key}';" if try_spree_current_user %>
+ <%== "var OAUTH_TOKEN = '#{admin_oauth_token}';" if defined?(admin_oauth_token) %>
<%== "var ADDRESS_FIELDS = #{Spree::Address::ADDRESS_FIELDS}" %>
<% if Rails.env.test? %>
jQuery.fx.off = false
diff --git a/core/lib/spree/testing_support/authorization_helpers.rb b/core/lib/spree/testing_support/authorization_helpers.rb
index 7af9f44a60..f2b592fd4e 100644
--- a/core/lib/spree/testing_support/authorization_helpers.rb
+++ b/core/lib/spree/testing_support/authorization_helpers.rb
@@ -37,10 +37,11 @@ module Spree
ability_class.register_ability(ability)
end
+ let(:admin_token) { Doorkeeper::AccessToken.create!(scopes: 'admin read write').token }
+
before do
- allow(Spree.user_class).to receive(:find_by).
- with(hash_including(:spree_api_key)).
- and_return(Spree.user_class.new)
+ allow(Spree.user_class).to receive(:find_by).and_return(Spree.user_class.new)
+ allow_any_instance_of(Spree::Admin::BaseController).to receive(:admin_oauth_token).and_return(admin_token)
end
end