Skip to content

How To: Isolate users to log into a single subdomain

maxwell edited this page Oct 25, 2012 · 2 revisions

Assuming you want to separate user bases for each subdomain.

First, make sure you remove the email uniqueness constraint in a migration, and add it back with the scoped id

# db/migrate/0001_change_user_email_index.rb
def change
  remove_index :users, :email
  add_index :users, [:email, :subdomain_id], :unique => true
end

now in your user model, set request_keys to :subdomain

   # app/models/user.rb
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, request_keys: [:subdomain]

NOTE: you can also do this globally in your devise.rb initializer

Now all that is left is to override find_for_authentication in your user model

  # app/models/user.rb
  def self.find_for_authentication(warden_conditions)
    if subdomain = Subdomain.find_by_name(warden_conditions[:subdomain])
      subdomain.users.find_by_email(warden_conditions[:email])
    end
  end

Congrats, your users are now unique to each subdomain!

Clone this wiki locally