grape_devise_token_auth
grape_devise_token_auth copied to clipboard
Customize auth_error
It would be awesome to configure error answer.
In my case I would like to return a json like {error: :not_logged}
in addition of the 401
First of, thank you so much for creating this, absolute life saver.
This is purely observational based, I noticed when exception is kind of StandardError
I'm able to catch it with Grape::API.rescue_from
. That said, GrapeDeviseTokenAuth::Unauthorized
inherits from Exception
thus because reasons I'm unable to customize the response. Changing superclass to StandardError
would resolve our problems.
Currently, I use following hack(because ruby does not allow to redefine class with different superclass):
- create new Unauthorized class closer to authenticate method in
GrapeDeviseTokenAuth::AuthHelpers
# config/initializers/grape_devise_token_auth.rb
GrapeDeviseTokenAuth.setup!
module GrapeDeviseTokenAuth
module AuthHelpers
class Unauthorized < StandardError; end
end
end
- rely on
Rails
autoloading system to pick upGrapeDeviseTokenAuth::AuthHelpers::Unauthorized
insteadGrapeDeviseTokenAuth::Unauthorized
- override response using:
# app/api/v1/root.rb
module Api
module V1
class Root < Grape::API
rescue_from GrapeDeviseTokenAuth::AuthHelpers::Unauthorized do |e|
error!({error: 'Unauthorized'}, 403)
end
...
It's not pretty but it works. Hit me with more elegant solution If you found one.
Thats a good point, it should inherit from StandardError. I'd accept a PR or I can make the change when I get around to it