Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting issues when user cannot sign in using Devise

In my application I authenticate users using Devise and I noticed that you can change the page that one is redirected to if the sign in fails. On the wiki I found the following example:

class CustomFailure < Devise::FailureApp
  def redirect_url
    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

Following this example I created my own CustomFailure class(custom_failure.rb) and placed in the helper folder (not sure where to put it). This is the following class I created:

class CustomFailure < Devise::FailureApp
  def redirect_url
    new_user_session_url(:subdomain => 'secure')
  end

  # Redirect to root_url
  def respond
    if http_auth?
      http_auth
    else
      root_url
    end
  end
end

I also added the following in the config/initializers/devise.rb file (as the wiki states should be done):

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

Although I get no errors, when I incorrectly sign in it still redirects to the /users/sign_in page (not the root page) and nothing is loaded (the page is completely white even though the source is not empty). Is there comthing wrong with my CustomFailure class or maybe it is in the wrong folder?

I am using Rails 3.0.1 and Devise 1.1.rc0.

The wiki where this code is found is at: How To: Redirect to a specific page when the user can not be authenticated

like image 797
Fizz Avatar asked Nov 14 '10 23:11

Fizz


People also ask

Does redirect to stop execution?

Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".


1 Answers

Try putting custom_failure.rb into you lib folder as it is not a helper. Then make sure the file is loaded. Probably you would attempt to load all files in lib automatically.

EDIT: To achieve an auto loaded lib you would insert the following to your application.rb:

config.autoload_paths += %W(#{config.root}/lib)

EDIT2: you forgot to call redirect_to when trying to redirect. At the moment respond only returns root_url. Try this:

def respond
  if http_auth?
    http_auth
  else
    redirect_to root_url
  end
end

fyi: the devise-guys also perform this before redirecting:

store_location!
flash[:alert] = i18n_message unless flash[:notice]
like image 84
pex Avatar answered Nov 08 '22 18:11

pex