Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Devise failure authentication via json sends back html instead of json

I have managed to setup json authentication. I implemented the following code:

class Users:: SessionsController < Devise::SessionsController
  def create
    respond_to do |format|  
      format.html { super }  
      format.json {  
        warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#failure")  
        render :json => {:success => true}  
      }
    end  
  end

  def destroy
    respond_to do |format|
      format.html {super}
      format.json {  
        Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name)
        render :json => {}
      }
    end
  end

  def failure
    render :json => {:success => false, :errors => ["Login Failed"]}
  end
end

This works fine, but when authentication fails, the failure doesnt return the json failure. I have a custom failure for devise. If I remove the redirect_url or remove the customer failure completely, then the authentication returns a json with the failure message. My custom failure is as follows:

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

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

end

Anyway to keep the redirect if its an html request, and return a json with a failure msg if its a json request?

Thanks!

like image 300
Karan Avatar asked Jun 30 '12 20:06

Karan


1 Answers

You have to tell warden to use that custom failure.

def failure
  respond_to do |format|
    format.html {super}
    format.json do
      warden.custom_failure!
      render :json => {:success => false, :errors => ["Login Failed"]}
    end
  end
end
like image 76
aledalgrande Avatar answered Oct 12 '22 23:10

aledalgrande