I use the devise's authenticate_user! method in a controller. This is working fine when the auth_token provided in the request is the correct one but if the authentication fails, I end up with:
curl -XGET 'http://localhost:3000/my_obj?auth_token=wrongtoken'
<html><body>You are being <a href="http://localhost:3000/users/sign_in">redirected</a>.</body></html>
As I use rabl, what is the best way to have something like
{'error' : 'authentication error'}
returned intead of the html redirection ?
I do that in avoid the filter with :format => :json response and do my own filter to render my JSON response if no current_user pass
class MyController < ApplicationController
before_filter :authenticate_user!, :unless => { request.format == :json }
before_filter :user_needed, :if => { request.format == :json }
def user_needed
unless current_user
render :json => {'error' => 'authentication error'}, :status => 401
end
end
end
An other way, can be cleaner is to define your own FailureApp ( https://github.com/plataformatec/devise/blob/master/lib/devise/failure_app.rb )
class MyFailureApp < Devise::FailureApp
def respond
if request.format == :json
json_failure
else
super
end
end
def json_failure
self.status = 401
self.content_type = 'application/json'
self.response_body = "{'error' : 'authentication error'}"
end
end
In your Devise config file add :
config.warden do |manager|
manager.failure_app = MyFailureApp
end