在 Rails 和 Devise 注册后,将用户登录到他们的子域 [英] Log a user into their subdomain after registration with Rails and Devise

查看:18
本文介绍了在 Rails 和 Devise 注册后,将用户登录到他们的子域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using Devise for authentication in my Rails 3 app. The application uses PostgreSQL schemas and the Apartment gem to facilitate multi-tenancy.

在创建帐户后登录和退出特定子域效果很好.用户只能登录其特定帐户的子域,这很好.

Logging in and out of a specific subdomain is working great after an account is created. Users can only login on the subdomain for their specific account, which is great.

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

Here's where I'm running into issues...

一个全新的用户点击注册网址:

A brand new user hits the sign up URL at:

http://foo.com/signup

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

By default, when they click submit, the new account is created, but the user is sent to:

http://foo.com/dashboard

相反,我希望他们去:

http://myaccount.foo.com/dashboard

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

In order to achieve this, I overrode the after_sign_up_path_for method in my registrations_controller.rb file:

def after_sign_up_path_for(resource)
  root_url(:subdomain => resource.account.subdomain)
end

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

This works as intended--it loads the correct URL--but the user's session was created for the root domain (foo.com) instead of the subdomain, so the user is asked to sign in.

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

One suggestion I found is to change the config/initializers/session_store.rb to:

config.session_store :cookie_store, :key => '_domain_session', :domain => :all

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

But this allows anyone to login to an account on any subdomain, which obviously isn't cool.

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

Question: How can I ensure that the session created upon signup is valid for the subdomain that was created during the signup process

推荐答案

您可以在 config.session_store 中使用 domain: :all 选项,并按照评论中的某些建议使用 before_action.

You could use domain: :all option in your config.session_store and just have a before_action just as suggested by some in the comments.

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

So you'll still have the code in config/initializers/session_store.rb or in config/application.rb:

config.session_store :cookie_store, :key => '_domain_session', :domain => :all

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

Then in your application_controller add the following code:

#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

这篇关于在 Rails 和 Devise 注册后,将用户登录到他们的子域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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