在运行时切换omniauth-shopify-oauth2 gem的提供程序? [英] Switch provider for the omniauth-shopify-oauth2 gem in runtime?

查看:102
本文介绍了在运行时切换omniauth-shopify-oauth2 gem的提供程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

omniauth-shopify-oauth2 的初始化程序应该看起来像这个:

The initializer for the omniauth-shopify-oauth2 gem is supposed to look like this:

# 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等).

However, in our Rails app resides a few different brands who offers the same functionality. Throughout the entire app, the request.domain of a request determines which brand you are exposed to (brand1.example.com, brand2.example.com, etc.).

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

We can easily store brand specific credentials and redirect the users to the brand specific authorization path:

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选择的.知道如何设置吗?

But I can't figure out how we can have different providers for the middleware, chosen based on the visited request.domain. Any idea how to set this up?

推荐答案

Omniauth在动态提供程序,这将对您有所帮助.像这样:

Omniauth provides documentation on Dynamic Providers, which will be helpful here. Something like:

# 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

这篇关于在运行时切换omniauth-shopify-oauth2 gem的提供程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆