Devise: Login user and redirect to subdomain

3.4k views Asked by At

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..

1

There are 1 answers

0
Gokul On BEST ANSWER

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'