Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Devise + Subdomain - Redirect user for sign_in

I am using devise gem in a rails application with multiple subdomains. Each subdomain is handled by respective controller, which look like this:

class Subdomain1Controller < ApplicationController
  before_filter :authenticate_user!
  def index
  end
end

With above controller implementation, Devise always keep subdomain while redirecting user to login page. In above case, Devise redirect user to http://subdomain1.acmesite/users/sign_in instead of a common sign_in Url.

This leads to having multiple sign_in urls for each sub-domains.

http://subdomain1.acmesite/users/sign_in
http://subdomain2.acmesite/users/sign_in
http://subdomain3.acmesite/users/sign_in

I am wondering if it's possible to override devise method to exclude subdomain part from the url and yet keeping the previous page url information. More preciously, I wants Devise to redirect user to a specific Url (like: http://acmesite/users/sign_in) irrespective of subdomain and after successful authentication, Devise should return user back to the caller subdomain+page.

like image 438
Firoz Ansari Avatar asked Dec 20 '11 04:12

Firoz Ansari


1 Answers

You need to write a custom FailureApp which kicks in when the user is unauthenticated.

From How To: Redirect to a specific page when the user can not be authenticated

class CustomFailure < Devise::FailureApp
  def redirect_url
    #return super unless [:worker, :employer, :user].include?(scope) #make it specific to a scope
     new_user_session_url(:subdomain => 'secure')
  end

  # You need to override respond to eliminate recall
  def respond
    if http_auth?
      http_auth
    else
      redirect
    end
  end
end

And add the following in config/initializers/devise.rb:

config.warden do |manager|
  manager.failure_app = CustomFailure
end

If you’re getting an uninitialized constant CustomFailure error, and you’ve put the CustomFailure class under your /lib directory, make sure to autoload your lib files in your application.rb file, like below

config.autoload_paths += %W(#{config.root}/lib)
like image 100
Prathan Thananart Avatar answered Sep 20 '22 17:09

Prathan Thananart