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

前端 未结 2 1066
温柔的废话
温柔的废话 2020-12-13 15:42

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 ou

相关标签:
2条回答
  • 2020-12-13 16:07

    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
    
    0 讨论(0)
  • 2020-12-13 16:11

    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
    
    0 讨论(0)
提交回复
热议问题