Ruby on Rails' skip_before_action doesn't work as expected

2.5k Views Asked by At

There are 2 namespaces:

api/public
api/mobile

Doorkeeper authorization with proper scope is created in public controller. For example:

class API::Public::PostsController < ApplicationController
  before_action -> { doorkeeper_authorize! :public }

  def show
    @post = Post.find(params[:id])
  end
end

Controller in mobile namespace is inherited from controller in public namespace. For example:

class API::Mobile::PostsController < API::Public::PostsController
  skip_before_action :doorkeeper_authorize!
  before_action -> { doorkeeper_authorize! :mobile }
end

So the point here is that functionality is same and if there is some difference for mobile then action could be overridden in mobile namespace. Problem is that scopes are different for those 2 namespaces, but skipping doorkeeper_authorize! doesn't work.

Is there a way to solve this?

2

There are 2 best solutions below

3
On BEST ANSWER

skip_before_filter works for skipping methods, not skipping lambdas/procs. Try creating a method for the public authorization:

class API::Public::PostsController < ApplicationController
  before_action :authorize_public

  ...

  def authorize_public
    doorkeeper_authorize! :public
  end
end

class API::Mobile::PostsController < API::Public::PostsController
  skip_before_action :authorize_public
  ...
end
0
On

You could call a method within your lambda that returns what to authorize:

class API::Public::PostsController < ApplicationController
  before_action -> { doorkeeper_authorize! authorization_scope }

  def show
    @post = Post.find(params[:id])
  end

  protected
    def authorization_scope
      :public
    end
end

Then your subclasses only need to override the method without getting into a skip_before_filter pain

class API::Mobile::PostsController < API::Public::PostsController
  protected
    def authorization_scope
      :mobile
    end
end