Class: Sevn::Ability

Inherits:
Object
  • Object
show all
Defined in:
lib/sevn/ability.rb

Instance Method Summary collapse

Constructor Details

#initialize(packs = {}) ⇒ Ability

Initialize ability object

Parameters:

packs

A Hash or rules to add with initialization

Returns:

self



12
13
14
15
16
17
18
# File 'lib/sevn/ability.rb', line 12

def initialize(packs={})
  raise Sevn::Errors::InitializeArgumentError.new unless packs.kind_of?(Hash)

  @rules_packs = {}

  packs.each { |name, pack| add_pack(name, pack) }
end

Instance Method Details

#allowed?(object, actions, subject, options = {}) ⇒ Boolean

Check if object can do actions in subject

Basically this method

  1. determine which rules pack it should use, by priority it would check:

- Use pack defined in options[:use_pack]
- Use pack defined by object method :sevn_rule_pack
- Use pack defined by object's class method :sevn_rule_pack
- Underscore object's class, and look for it
  1. check if any of results include allowed action

Parameters:

actions

Symbol or Array of Symbols of the actions to check

object

object trying to access resource

subject

resource to be accessed

options

a list of options to consider when checking.

Options:

use_pack

check for actions in the specified pack instead of auto-determining the pack.

Returns:

true or false

Exceptions:

if no pack can be determined for the current subject, it will raise a NoPackError

Returns:

  • (Boolean)


50
51
52
53
54
55
56
57
58
# File 'lib/sevn/ability.rb', line 50

def allowed?(object, actions, subject, options = {})
  # if multiple actions passed, check all actions to be allowed
  if actions.respond_to?(:each)
    actions.all? { |action| action_allowed?(object, action, subject, options) }
  else
    # single action check
    action_allowed?(object, actions, subject, options)
  end
end

#authorize!(object, actions, subject, options = {}) ⇒ Object

Check if object is authorized to do actions in subject if action is not allowed it will raise an Unauthorized error

Parameters:

actions

Symbol or Array of Symbols of the actions to check

object

object trying to access resource

subject

resource to be accessed

options

a list of options to consider when checking.

Options:

use_pack

check for actions in the specified pack instead of auto-determining the pack.

Returns:

subject

Exceptions:

if object is not allowed to do action on subject, it will raise an UnauthorizedError



83
84
85
86
87
88
# File 'lib/sevn/ability.rb', line 83

def authorize!(object, actions, subject, options = {})
  if !allowed?(object, actions, subject, options)
    raise Sevn::Errors::UnauthorizedError.new(object, actions, subject)
  end
  subject
end