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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With