在使用Rails和Devise注册后,将用户登录到其子域

Rob*_*ers 16 ruby-on-rails multi-tenant devise

我在我的Rails 3应用程序中使用Devise进行身份验证.该应用程序使用PostgreSQL模式和Apartment gem来促进多租户.

创建帐户,登录和退出特定子域名的工作正常.用户只能在子域上登录其特定帐户,这很棒.

这是我遇到问题的地方......

全新用户点击注册网址:

http://foo.com/signup

默认情况下,当他们单击"提交"时,会创建新帐户,但会将用户发送到:

http://foo.com/dashboard

相反,我希望他们去:

http://myaccount.foo.com/dashboard

为了实现这一点,我覆盖了after_sign_up_path_for我的registrations_controller.rb文件中的方法:

def after_sign_up_path_for(resource)
  root_url(:subdomain => resource.account.subdomain)
end
Run Code Online (Sandbox Code Playgroud)

这按预期工作 - 它加载正确的URL - 但用户的会话是为根域(foo.com)而不是子域创建的,因此要求用户登录.

我发现的一个建议是config/initializers/session_store.rb改为:

config.session_store :cookie_store, :key => '_domain_session', :domain => :all
Run Code Online (Sandbox Code Playgroud)

但这允许任何人登录任何子域的帐户,这显然不是很酷.

问题:如何确保注册时创建的会话对注册过程中创建的子域有效

Gja*_*don 21

您可以domain: :all在config.session_store中使用选项,只需按照注释中的某些人的建议进行before_action.

所以你仍然会在config/initializers/session_store.rb或config/application.rb中获得代码:

config.session_store :cookie_store, :key => '_domain_session', :domain => :all
Run Code Online (Sandbox Code Playgroud)

然后在application_controller中添加以下代码:

#app/controllers/application_controller.rb
before_action :check_subdomain

def check_subdomain
  unless request.subdomain == current_user.account.subdomain
    redirect_to root_path, alert: "You are not authorized to access that subdomain."
  end
end
Run Code Online (Sandbox Code Playgroud)