【问题标题】:How to use dynamic scoping with devise and omniauth如何将动态范围与设计和omniauth一起使用
【发布时间】:2014-09-16 17:08:50
【问题描述】:

我正在将旧应用程序从 rails 3.0 升级到 rails 4.1,并且在设置设计和omniauth 的路线时遇到问题。目前的路线如下所示:

scope "(:locale)", locale: /#{I18n.available_locales.join("|")}/ do
      devise_for :users, controllers: {
            omniauth_callbacks: "users/omniauth_callbacks"
      }

当我运行它时,我收到以下错误:

 Devise does not support scoping omniauth callbacks under a dynamic segment (RuntimeError)
 and you have set "/(:locale)/users". You can work around by passing
 `skip: :omniauth_callbacks` and manually defining the routes. Here is an example:

match "/users/auth/:provider",
  constraints: { provider: /google|facebook/ },
  to: "devise/omniauth_callbacks#passthru",
  as: :omniauth_authorize,
  via: [:get, :post]

match "/users/auth/:action/callback",
  constraints: { action: /google|facebook/ },
  to: "devise/omniauth_callbacks",
  as: :omniauth_callback,
  via: [:get, :post]

我尝试了多种方式手动定义路由,但是当我运行测试时,我的路由都不起作用。有谁知道用 devise_for 处理这些动态段的正确方法吗?

【问题讨论】:

    标签: ruby-on-rails-3 ruby-on-rails-4 devise routes omniauth


    【解决方案1】:

    我在 routes.rb

    中添加了 devise_for 2 次
    devise_for :users, skip: [:session, :password, :registration], controllers: { omniauth_callbacks: "users/omniauth_callbacks" }
    
    scope ":locale", locale: /#{I18n.available_locales.join("|")}/ do
       devise_for :users, skip: [:omniauth_callbacks]
    

    找到答案here

    此外,您需要为omniauth 自定义故障块来处理登录期间的错误(例如用户取消):

    # In config/initializers/omniauth.rb
    require 'devise/omniauth'
    # Work around for bug when scoping paths
    # See: https://github.com/spree/spree_social/issues/130
    OmniAuth.config.on_failure = Proc.new do |env|
      env['devise.mapping'] = Devise.mappings[:user]
      controller_name  = ActiveSupport::Inflector.camelize(env['devise.mapping'].controllers[:omniauth_callbacks])
      controller_klass = ActiveSupport::Inflector.constantize("#{controller_name}Controller")
      controller_klass.action(:failure).call(env)
    end
    

    【讨论】:

    【解决方案2】:

    我想添加到设计的 wiki 上提供的解决方案:https://github.com/plataformatec/devise/wiki/How-To:-OmniAuth-inside-localized-scope

    如果您已经在使用设置阶段(devise.rb 中的setup: true),您可以跳过创建新控制器(在他们的示例中为omniauth_controller.rb),只需将session[:omniauth_login_locale] = I18n.locale 添加到setup 操作。最终我的routes.rb 看起来像这样:

      devise_for :users, skip: [:session, :password, :registration, :confirmation], controllers: { omniauth_callbacks: 'omniauth_callbacks' }
    
      scope '(:locale)', locale: /en|zh/ do
        devise_for :users, skip: :omniauth_callbacks
    
        devise_scope :user do
          get 'auth/:provider/setup' => 'omniauth_callbacks#setup'
        end
      end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多