Module: Rubee::Authorizable::ClassMethods

Defined in:
lib/rubee/controllers/extensions/authorizable.rb

Instance Method Summary collapse

Instance Method Details

#authorize(model: nil, response_hash: nil, role_field: :role, **roles) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/rubee/controllers/extensions/authorizable.rb', line 20

def authorize(model: nil, response_hash: nil, role_field: :role, **roles)
  @__authorizations ||= {}
  stringified_model_name = model.to_s
  @__authorizations[stringified_model_name] ||= {}
  @__authorizations[stringified_model_name].merge! roles
  model_klass = Object.const_get stringified_model_name.capitalize

  @__authorizations[stringified_model_name].each do |role, methods|
    methods = methods.is_a?(Array) ? methods : [methods]
    methods.each do |method|
      around method, ->(controller, &original_action) do
        if controller.send(:authorized?, role, model: model_klass, role_field:)
          original_action.call
        else
          response_object_hash = response_hash || { object: { error: 'Unauthorized' }, type: :json, status: 403 }
          controller.response_with(**response_object_hash)
        end
      end
    end
  end
end