2

I am using Apartment and Devise gem for Muti-tenancy and authentication.

I have a sign_up page in root domain URL(example.com) where I get the subdomain details from user.

I need to sign_in the user after successfully saving the record and redirect to the new subdomain(sub.example.com).

Apartment Schemas:

Account => Common for all schemas(Public)

User => Created seperately for each schemas(Private)

RegistrationController:

class Users::RegistrationsController < Devise::RegistrationsController
  
  ...
  ...

  def create
    ActiveRecord::Base.transaction do
      @account = Account.new(account_params)
      if @account.valid?
        # Create & switch to the new tenant
        Apartment::Tenant.create(@account.subdomain)
        Apartment::Tenant.switch!(@account.subdomain)
        @account.save

        sign_in(:user, @account.user)
        redirect_to root_url(subdomain: "#{Apartment::Tenant.current}")
      else
        render :action => 'new'
      end
    end
  end

  ...
  ...

  protected
  def account_params
    params.require(:account).permit(:name, :subdomain, user_attributes: [:first_name, :last_name, :email, :password, :password_confirmation])
  end
end

The above code successfully redirects to the new subdomain but, It is not signing_in the user although I am signing_in the user before redirect.

Anyone please help me to redirect the user as signed_in to the new subdomain.

Thank you..

Community
  • 1
  • 1
Gokul
  • 3,101
  • 4
  • 27
  • 45
  • Does redirecting to `root_url` preserves the session cookies? – 31piy Jan 03 '17 at 11:46
  • @31piy, I tried removing the authentication in root_url and tried printing the session `p session['warden.user.user.key']` in controller action but it returns `nil` – Gokul Jan 03 '17 at 12:00
  • Please check if the session IDs are same before and after the redirection. – 31piy Jan 03 '17 at 12:02
  • @31piy The session id in the `create` action after calling `redirect_to` is `f3911a8b73e04ad0afbcb126412b5135` and the session id in the `root_path` action after redirection is `2e34cbab7f479107c7efb14b05425504` – Gokul Jan 03 '17 at 12:20
  • Yup, exactly! If sessions aren't same, then the signed in user won't be shared across the domains. You need to find a way so that the sessions can be shared between the domains. – 31piy Jan 04 '17 at 04:48

1 Answers1

0

Finally, solved this issue by adding :domain => :all or the rootdomain :domain => 'example.com' option in session_store which I found in this answer.

config/initializers/session_store.rb

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

(or)

config.session_store :cookie_store, :key => '_domain_session', :domain => 'example.com'
Community
  • 1
  • 1
Gokul
  • 3,101
  • 4
  • 27
  • 45