Devise not displaying error messge during an authentication failure?

前端 未结 4 1732
名媛妹妹
名媛妹妹 2021-01-03 22:35

I was expecting a flash notice when authentication failures occurs in devise. But get nothing during a authentication failure, just the page refreshes and remains still. I

4条回答
  •  死守一世寂寞
    2021-01-03 23:31

    I know this is old but I ended up here because I was having the same problem in rails 5.1 and the accepted answer didn't worked, so here's what I did. After overriding Devise::SessionController, add the following code to it:

    after_action :unauthenticated
    
    protected
    
    def unauthenticated
      flash[:alert] = t("devise.failure.#{request.env['warden'].message}") unless request.env['warden'].message.blank?
    end
    

    Also, on the same controller, copy and paste the code for the create method from your version of Devise, and remove the ! from warden.authenticate!. Because you removed the !, now you have to check if the resource is nil, and redirect if it is. In my case, the create method ended up like this:

    def create
      self.resource = warden.authenticate(auth_options)
      redirect_to root_path and return if resource.nil?
      set_flash_message!(:notice, :signed_in)
      sign_in(resource_name, resource)
      yield resource if block_given?
      respond_with resource, location: after_sign_in_path_for(resource)
    end
    

    Finally, you just have to print the flash messages on your views. I am using materialize, so I created a partial and added the following code to it (which you should customize to your own needs):

    <% flash.each do |type, message| %>
      <% if type == "notice" %>
        
      <% elsif type == "success" %>
        
      <% elsif type == "alert" %>
        
      <% end %>
    <% end %>
    

提交回复
热议问题