diff --git a/app/controllers/concerns/shopify_app/require_known_shop.rb b/app/controllers/concerns/shopify_app/require_known_shop.rb new file mode 100644 index 000000000..7f05b6846 --- /dev/null +++ b/app/controllers/concerns/shopify_app/require_known_shop.rb @@ -0,0 +1,39 @@ +# frozen_string_literal: true + +module ShopifyApp + module RequireKnownShop + extend ActiveSupport::Concern + + included do + before_action :check_shop_domain + before_action :check_shop_known + end + + def current_shopify_domain + return if params[:shop].blank? + @shopify_domain ||= ShopifyApp::Utils.sanitize_shop_domain(params[:shop]) + end + + private + + def check_shop_domain + redirect_to(ShopifyApp.configuration.login_url) unless current_shopify_domain + end + + def check_shop_known + @shop = SessionRepository.retrieve_shop_session_by_shopify_domain(current_shopify_domain) + redirect_to(shop_login) unless @shop + end + + def shop_login + url = URI(ShopifyApp.configuration.login_url) + + url.query = URI.encode_www_form( + shop: params[:shop], + return_to: request.fullpath, + ) + + url.to_s + end + end +end diff --git a/test/controllers/concerns/require_known_shop_test.rb b/test/controllers/concerns/require_known_shop_test.rb new file mode 100644 index 000000000..8c8c47f03 --- /dev/null +++ b/test/controllers/concerns/require_known_shop_test.rb @@ -0,0 +1,63 @@ +# frozen_string_literal: true + +class RequireKnownShopTest < ActionController::TestCase + class UnauthenticatedTestController < ActionController::Base + include ShopifyApp::RequireKnownShop + + def index + render html: '