在运行时切换 omniauth-shopify-oauth2 gem 的提供商?

Switch provider for the omniauth-shopify-oauth2 gem in runtime?

omniauth-shopify-oauth2 gem 的初始值设定项应该如下所示:

# config/initializers/omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
  provider :shopify, ENV['SHOPIFY_API_KEY'], ENV['SHOPIFY_SHARED_SECRET']
end

但是,在我们的 Rails 应用程序中有几个提供相同功能的不同品牌。在整个应用程序中,请求的 request.domain 决定了您接触到的品牌(brand1.example.combrand2.example.com 等)。

我们可以轻松存储特定于品牌的凭据并将用户重定向到特定于品牌的授权路径:

https://example.myshopify.com/admin/oauth/authorize?client_id=brand1&scope=read_orders,read_products&redirect_uri=https://brand1.example.com/auth/shopify/callback

但我无法弄清楚我们如何为中间件提供不同的提供程序,这些提供程序是根据访问的 request.domain 选择的。知道如何设置吗?

Omniauth 提供了关于 Dynamic Providers 的文档,这将对您有所帮助。类似于:

# config/initializers/omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
  provider :shopify, setup: lambda do |env|

    # Do logic to get correct credentials for request.
    # For example, if you store the credentials on a model called Brand,
    # and have it keyed on "subdomain":
    request = ActionDispatch::Request.new(env)
    brand = Brand.find_by(subdomain: request.subdomain)

    env['omniauth.strategy'].options.merge!({
      client_id: brand.client_id,
      client_secret: brand.client_secret
    })

    # `site` needs to be set. This is part of the shopify provider setup phase, which we are overriding
    env['omniauth.strategy'].options[:client_options][:site] = "https://#{ request.GET['shop'] }"
  end
end