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

时间:2018-06-06 13:42:52

标签: ruby-on-rails oauth oauth-2.0 shopify omniauth

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选择不同的中间件提供商。知道如何设置吗?

1 个答案:

答案 0 :(得分:0)

<\ n> 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