Module: CantCantCant

Defined in:
lib/cant_cant_cant.rb

Defined Under Namespace

Modules: Generators

Constant Summary collapse

PermissionDenied =
Class.new(RuntimeError)
InvalidConfiguration =
Class.new(RuntimeError)
UnfilledAction =
Class.new(RuntimeError)

Class Method Summary collapse

Class Method Details

.all_actionsObject



70
71
72
73
74
75
76
77
78
# File 'lib/cant_cant_cant.rb', line 70

def all_actions
  @all_actions = nil unless @config.caching
  @all_actions ||= permission_table
                   .values
                   .map(&:keys)
                   .flatten
                   .uniq
                   .to_set
end

.allow?(action, roles) ⇒ Boolean

Returns:

  • (Boolean)


37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/cant_cant_cant.rb', line 37

def allow?(action, roles)
  return true if allowed_actions_for(roles).include? action
  return false if denied_actions_for(roles).include?(action)

  case @config.report_unfilled_actions
  # when :ignore, do nothing
  when :warn
    warn "Please fill in CantCantCant permission #{action}"
  when :raise
    raise UnfilledAction, [action, roles]
  end

  case @config.default_policy
  when :allow then true
  when :deny  then false
  end
end

.allowed_actions_for(roles) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/cant_cant_cant.rb', line 55

def allowed_actions_for(roles)
  roles = [roles] unless roles.is_a? Array
  key = roles.sort.join(',')
  return @allow_cache[key] if @allow_cache[key] && @config.caching

  perms = permission_table
          .values_at(*roles.map(&:to_s))
          .select(&:present?)
  allowed_perms = perms
                  .map { |x| x.select { |_, v| v == 'allow' }.keys }
                  .flatten
                  .uniq
  @allow_cache[key] = allowed_perms.to_set
end

.denied_actions_for(roles) ⇒ Object



80
81
82
83
84
85
# File 'lib/cant_cant_cant.rb', line 80

def denied_actions_for(roles)
  roles = [roles] unless roles.is_a? Array
  key = roles.sort.join(',')
  return @deny_cache[key] if @deny_cache[key] && @config.caching
  @deny_cache[key] = all_actions - allowed_actions_for(roles)
end

.initialize(config, &block) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/cant_cant_cant.rb', line 12

def initialize(config, &block)
  @config_file = config

  @config = OpenStruct.new(
    injection_mode: :base_controller,
    base_controller: ActionController::Base,
    default_policy: :allow,
    report_unfilled_actions: :ignore,
    caching: true
  )
  @config.instance_eval(&block) if block_given?

  @allow_cache = {}
  @deny_cache = {}

  validate_config

  case @config.injection_mode
  when :base_controller
    inject_base_controller
  when :individual
    inject_individual_actions
  end
end