Log a user into their subdomain after registration with Rails and Devise

蹲街弑〆低调 提交于 2019-11-28 18:23:59

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.

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

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

Override the devise session controller.

Create a file with the exact path app/controllers/devise/sessions_controller.rb

Override the sessions_controller class in that controller. Paste in the code found at the link. 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

Edit the create action to suit your needs.

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

I'm looking to see if I can figure out how exactly to make this work, but I know for sure that the result you want is attainable by overriding the devise session controller.

EDIT

If you are using cross-subdomain cookies, you could enforce the subdomain session with a before_filter. For example

before_action do 
    redirect_to root_path, alert: 'That subdomain does not belong to you' if request.subdomain != current_user.subdomain
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!