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

#authorization_context, #authorization_rule_for, included

Methods included from Behaviours::PolicyFor

#authorization_context, #authorization_namespace, #policy_for

Instance Method Details

#allowed_to?(rule, record = :__undef__, **options) ⇒ Boolean

Checks that an activity is allowed for the current context (e.g. user).

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

Returns true of false.

Returns:

  • (Boolean)


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

def allowed_to?(rule, record = :__undef__, **options)
  record = controller_name.classify.safe_constantize if
    record == :__undef__

  super(rule, record, **options)
end

#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.



44
45
46
47
48
49
50
51
52
53
# File 'lib/action_policy/rails/controller.rb', line 44

def authorize!(record = :__undef__, to: nil, **options)
  record = controller_name.classify.safe_constantize if
    record == :__undef__

  to ||= :"#{action_name}?"

  super(record, to: to, **options)

  self.authorize_count += 1
end

#authorize_countObject



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

def authorize_count
  @authorize_count ||= 0
end

#verify_authorizedObject

Raises:



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

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