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

Viewed 6224

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 out of a specific subdomain is working great after an account is created. Users can only login on the subdomain for their specific account, which is great.

Here's where I'm running into issues...

A brand new user hits the sign up URL at:

http://foo.com/signup

By default, when they click submit, the new account is created, but the user is sent to:

http://foo.com/dashboard

Instead, I want them to go to:

http://myaccount.foo.com/dashboard

In order to achieve this, I overrode the after_sign_up_path_for method in my registrations_controller.rb file:

def after_sign_up_path_for(resource)
  root_url(:subdomain => resource.account.subdomain)
end

This works as intended--it loads the correct URL--but the user's session was created for the root domain (foo.com) instead of the subdomain, so the user is asked to sign in.

One suggestion I found is to change the config/initializers/session_store.rb to:

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

But this allows anyone to login to an account on any subdomain, which obviously isn't cool.

Question: How can I ensure that the session created upon signup is valid for the subdomain that was created during the signup process

2 Answers
Related