明确允许控制器中的Doorkeeper范围

时间:2018-01-03 21:14:20

标签: ruby-on-rails doorkeeper

在我目前的应用中,我有两个门卫示波器,useradmin。在doorkeeper documentation中设置API的范围

class Api::V1::ProductsController < Api::V1::ApiController
  before_action -> { doorkeeper_authorize! :public }, only: :index
  before_action only: [:create, :update, :destroy] do
    doorkeeper_authorize! :admin, :write
  end

  ...
end

我不想在每个控制器中调用门卫,所以在我的ApplicationController中我有

module API
  module V1
    class ApplicationController < ActionController::API
      before_action { doorkeeper_authorize! :user, :project }
      ...

    end
  end
end

但我不想让:project访问每个控制器。有没有办法允许我在应用程序控制器user中允许before_action { doorkeeper_authorize! :user },并在每个控制器的基础上允许project?即:

module API
  module V1
    class SomeController < ApplicationController
      before_action only: [:index, :show] { doorkeeper_authorize! :project }

      ...
    end
  end
end

3 个答案:

答案 0 :(得分:0)

使用带controller_name的条件 - 像这样的史密斯:

before_action { doorkeeper_authorize! :project }, if: -> { controller_name == 'some' }

检查是否应该将一个参数传递给lambda,如:

if: ->(instance) { instance.controller_name == 'some' }

答案 1 :(得分:0)

我可以通过在API::V1::ApplicationController

中执行以下操作来解决此问题
module API
  module V1
    class ApplicationController < ActionController::API
      WHITELISTED_PROJECT_CONTROLLERS = %w( projects pre_task_plans
                                            job_hazard_analyses ).freeze

      before_action :authorize!

      def authorize!
        if project_scope?
          if !WHITELISTED_PROJECT_CONTROLLERS.include?(controller_name)
            return user_not_authorized
          end
        end
        doorkeeper_authorize! :user, :project
      end

      def project_scope?
        doorkeeper_token&.scopes&.any? { |s| s == 'project' }
      end

     ...

    end
  end
end

答案 2 :(得分:0)

也许创建自己的过滤器可能是一个选项

before_action :doorkeeper_user_authorize!,  only: [:create, :update, :destroy]
protected 

def doorkeeper_user_authorize!
  doorkeeper_authorize!( :user )
end 

def doorkeeper_project_authorize!
  doorkeeper_authorize!( :user, :project )
end 

然后在控制器中应允许项目的地方

skip_before_action :doorkeeper_user_authorize!
before_action :doorkeeper_project_authorize!