Module: Authorization::Controller::Grape

Defined in:
lib/declarative_authorization/controller/grape.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object

:nodoc:



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/declarative_authorization/controller/grape.rb', line 23

def self.included(base) # :nodoc:
  base.extend ClassMethods

  base.extend ::Authorization::Controller::DSL

  base.module_eval do
    add_filter!
  end

  base.helpers do
    include ::Authorization::Controller::Runtime

    def authorization_engine
      ::Authorization::Engine.instance
    end

    def filter_access_filter # :nodoc:
      begin
        route
      rescue
        # Acceessing route raises an exception when the response is a 405 MethodNotAllowed
        return
      end
      unless allowed?("#{request.request_method} #{route.origin}")
        if respond_to?(:permission_denied, true)
          # permission_denied needs to render or redirect
          send(:permission_denied)
        else
          error!('You are not allowed to access this action.', 403)
        end
      end
    end

    def logger
      ::Rails.logger
    end

    def api_class
      if options[:for].respond_to?(:base)
        # Grape >= 1.2.0 endpoint
        # Authorization::Controller::Grape can be included into either Grape::API
        # or Grape::API::Instance, so we need to check both.
        [
          options[:for],
          options[:for].base
        ].detect { |api| api.respond_to?(:decl_auth_context) }
      else
        # Grape < 1.2.0 endpoint
        options[:for]
      end
    end
  end
end