Module: ActionPolicy::Controller

Extended by:
ActiveSupport::Concern
Includes:
Behaviour, Behaviours::Memoized, Behaviours::Namespaced, Behaviours::ThreadMemoized
Defined in:
lib/action_policy/rails/controller.rb

Overview

Controller concern. Add ‘authorize!` and `allowed_to?` methods, provide `verify_authorized` hook.

Instance Method Summary collapse

Methods included from Behaviours::Namespaced

prepended

Methods included from Behaviours::Memoized

#__policies_cache__, #__policy_memoize__, prepended

Methods included from Behaviours::ThreadMemoized

#__policy_thread_memoize__, prepended

Methods included from Behaviour

#allowance_to, #allowed_to?, #authorization_context, #authorization_rule_for, included, #lookup_authorization_policy

Methods included from Behaviours::Scoping

#authorization_scope_type_for, #authorized_scope

Methods included from Behaviours::PolicyFor

#authorization_context, #authorization_namespace, #authorization_strict_namespace, #build_authorization_context, #default_authorization_policy_class, #implicit_authorization_target!, #policy_for, #policy_for_cache_key

Instance Method Details

#authorize!(record = :__undef__, to: nil, **options) ⇒ Object

Authorize action against a policy.

Policy is inferred from record (unless explicitly specified through ‘with` option).

If action is not provided, it’s inferred from ‘action_name`.

If record is not provided, tries to infer the resource class from controller name (i.e. ‘controller_name.classify.safe_constantize`).

Raises ‘ActionPolicy::Unauthorized` if check failed.

Returns:

  • the policy record



50
51
52
53
54
55
56
57
# File 'lib/action_policy/rails/controller.rb', line 50

def authorize!(record = :__undef__, to: nil, **options)
  to ||= :"#{action_name}?"

  policy_record = super

  self.authorize_count += 1
  policy_record
end

#authorize_countObject



70
71
72
# File 'lib/action_policy/rails/controller.rb', line 70

def authorize_count
  @authorize_count ||= 0
end

#implicit_authorization_targetObject

Tries to infer the resource class from controller name (i.e. ‘controller_name.classify.safe_constantize`).



61
62
63
# File 'lib/action_policy/rails/controller.rb', line 61

def implicit_authorization_target
  controller_name&.classify&.safe_constantize
end

#skip_verify_authorized!Object



74
75
76
# File 'lib/action_policy/rails/controller.rb', line 74

def skip_verify_authorized!
  @verify_authorized_skipped = true
end

#verify_authorizedObject



65
66
67
68
# File 'lib/action_policy/rails/controller.rb', line 65

def verify_authorized
  Kernel.raise UnauthorizedAction.new(controller_path, action_name) if
    authorize_count.zero? && !verify_authorized_skipped
end