mcordell / grape_devise_token_auth

Grape compatibility for devise_token_auth + devise + rails setup
MIT License
41 stars 29 forks source link

Customize auth_error #8

Open proxygear opened 8 years ago

proxygear commented 8 years ago

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

vr4b4c commented 8 years ago

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):

# config/initializers/grape_devise_token_auth.rb
GrapeDeviseTokenAuth.setup!

module GrapeDeviseTokenAuth
  module AuthHelpers
    class Unauthorized < StandardError; end
  end
end
# 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.

mcordell commented 8 years ago

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