简体   繁体   中英

Rails 3, Devise not displaying error message on authentication failure

I am using Rails 3 and Devise.

I have this in {rails_root}/lib/custom_failure.rb and the required loading code in my Devise initializer.

class CustomFailure < Devise::FailureApp

  def redirect_url
    root_path
  end

  def respond
    if http_auth?
      http_auth
    else
      redirect_to root_url
    end
  end
end

The file is loaded, and the user is redirected to the root_url when authentication fails. The problem is no error messages are displayed when authentication fails, however all other devise messages are working fine (Successful login etc).

I have this in my application layout

  <% flash.each do |name, msg| %>
    <%= content_tag :div, msg, :id => "flash_#{name}" %>
  <% end -%>

Edit: The final working code. Turns out my biggest mistake was not restarting the server. CustomFailure is a lib and is only loaded once.

  def respond
    if http_auth?
      http_auth
    else
      flash[:notice] = "Error message goes here"
      redirect_to root_url
    end
  end

Could it be that the flash message is getting eaten by the redirect? The flash is only good for the next request, so maybe the redirect is getting the flash message, but it's gone on the next request ( root_url ). You might have to do an internal redirect or pass the flash vars through to the next request.

Can I ask why you're doing an external redirect on failure instead of just showing the login form again with the error messages?

You can also just add flash[:alert] in respond action as:

class CustomFailure < Devise::FailureApp
    def redirect_url
        root_url
    end
    def respond
        if http_auth?
            http_auth
        else
            flash[:alert] = i18n_message unless flash[:notice]
            redirect_to root_url
        end
    end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM