[英]Log a user into their subdomain after registration with Rails and Devise
我在我的Rails 3應用程序中使用Devise進行身份驗證。 該應用程序使用PostgreSQL模式和Apartment gem來促進多租戶。
創建帳戶后 ,登錄和退出特定子域名的工作正常。 用戶只能在子域上登錄其特定帳戶,這很棒。
這是我遇到問題的地方......
全新用戶點擊注冊網址:
http://foo.com/signup
默認情況下,當他們單擊“提交”時,會創建新帳戶,但會將用戶發送到:
http://foo.com/dashboard
相反,我希望他們去:
http://myaccount.foo.com/dashboard
為了實現這一點,我覆蓋了registrations_controller.rb
文件中的after_sign_up_path_for
方法:
def after_sign_up_path_for(resource)
root_url(:subdomain => resource.account.subdomain)
end
這按預期工作 - 它加載正確的URL - 但用戶的會話是為根域(foo.com)而不是子域創建的,因此要求用戶登錄。
我發現的一個建議是將config/initializers/session_store.rb
更改為:
config.session_store :cookie_store, :key => '_domain_session', :domain => :all
但這允許任何人登錄任何子域的帳戶,這顯然不是很酷。
問題:如何確保注冊時創建的會話對注冊過程中創建的子域有效
您可以在config.session_store中使用domain: :all
選項,只需按照注釋中某些人的建議使用before_action。
所以你仍然會在config / initializers / session_store.rb或config / application.rb中獲得代碼:
config.session_store :cookie_store, :key => '_domain_session', :domain => :all
然后在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
覆蓋設計會話控制器。
使用確切的路徑 app/controllers/devise/sessions_controller.rb
創建一個文件
覆蓋該控制器中的sessions_controller類。 粘貼在鏈接中找到的代碼中。 https://github.com/plataformatec/devise/blob/master/app/controllers/devise/sessions_controller.rb
class Devise::SessionsController < DeviseController
# copy-paste the devise session controller below.
...
end
編輯create
操作以滿足您的需要。
def create
self.resource = warden.authenticate!(auth_options)
set_flash_message(:notice, :signed_in) if is_flashing_format?
sign_in(resource_name, resource)
yield resource if block_given?
respond_with resource, :location => after_sign_in_path_for(resource)
end
我想知道我是否可以弄清楚如何使這項工作,但我確信你想要的結果可以通過覆蓋設計會話控制器來實現。
編輯
如果您使用的是跨子域Cookie,則可以使用before_filter強制執行子域會話。 例如
before_action do
redirect_to root_path, alert: 'That subdomain does not belong to you' if request.subdomain != current_user.subdomain
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.