grape_devise_token_auth icon indicating copy to clipboard operation
grape_devise_token_auth copied to clipboard

Customize auth_error

Open proxygear opened this issue 9 years ago • 2 comments

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

proxygear avatar Dec 15 '15 14:12 proxygear

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 up GrapeDeviseTokenAuth::AuthHelpers::Unauthorized instead GrapeDeviseTokenAuth::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.

vr4b4c avatar Jul 24 '16 10:07 vr4b4c

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

mcordell avatar Jul 25 '16 15:07 mcordell