Andreas Lyngstad
Andreas Lyngstad

Reputation: 4927

redirect_to with params in rails

I have an application with subdomains. When a User logs in at the root domain. I want to redirect him/her to his/her firms subdomain. I am useing devise.

This is what I have so far

def create
  subdomain = request.subdomain
  user = User.find_by_email(params[:user][:email])
  if subdomain.present?
    resource = warden.authenticate!(auth_options)
    set_flash_message(:notice, :signed_in) if is_navigational_format?
    sign_in(resource_name, resource)
    redirect_to statistics_url
  else
    redirect_to sign_in_at_subdomain_url(:subdomain => user.firm.subdomain), :params => params
  end
end

def sign_in_at_subdomain
  resource = warden.authenticate!(auth_options)
  set_flash_message(:notice, :signed_in) if is_navigational_format?
  sign_in(resource_name, resource)
  redirect_to statistics_url
end

When the user login trough the login form, params gets sent to the create action, that devise use for authentication. As you see in my code, when a subdomain is present the login works great, but when it is not present I want to do a redirect to the subdomain and sign_in_at_subdomain.

How can I pass the parmas form the form trough the create action to the sign_in_at_subdomain action?

Upvotes: 0

Views: 748

Answers (1)

Syed Aslam
Syed Aslam

Reputation: 8807

You can use after_sign_in_path_for to sign_out the user from the root romain and sign him in to the subdomain he belongs to. The following is from the example Rails 3 app with basecamp like subdomains and authentication (using Devise).

def after_sign_in_path_for(resource_or_scope)
  scope = Devise::Mapping.find_scope!(resource_or_scope)
  subdomain_name = current_user.subdomain.name
  if current_subdomain.nil? 
    # logout of root domain and login by token to subdomain
    token =  Devise.friendly_token
    current_user.loginable_token = token
    current_user.save
    sign_out(current_user)
    flash[:notice] = nil
    home_path = valid_user_url(token, :subdomain => subdomain_name)
    return home_path 
  else
    if subdomain_name != current_subdomain.name 
      # user not part of current_subdomain
      sign_out(current_user)
      flash[:notice] = nil
      flash[:alert] = "Sorry, invalid user or password for subdomain"
    end
  end
  super
end

Upvotes: 1

Related Questions