Module: Cul::Omniauth::Abilities

Extended by:
ActiveSupport::Concern
Defined in:
app/models/concerns/cul/omniauth/abilities.rb

Defined Under Namespace

Modules: ClassMethods, Comparisons, Empty

Instance Method Summary collapse

Instance Method Details

#initialize(user = nil, opts = {}) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'app/models/concerns/cul/omniauth/abilities.rb', line 7

def initialize(user=nil, opts={})
  if user
    @user = user
    opts = {user_id: user.uid}.merge(opts)
  else
    @user = User.new
  end
  roles = opts[:roles] || Empty::HASH
  if @user
    role_permissions = self.class.config.select do |role,config|
      roles.include?(role) or @user.role?(role)
    end
  else
    role_permissions = {}
  end
  role_permissions[:'*'] = self.class.config.fetch(:*,Empty::HASH)
  role_permissions.each do |role, config|
    config.fetch(:can,Empty::HASH).each do |action, conditions|
      if conditions.blank?
        can action, :all
      else
        can action, Cul::Omniauth::AbilityProxy do |proxy|
          combine_with = conditions.fetch(:combine_with,:and).to_sym
          r = (combine_with == :and)
          if !!proxy
            conditions.fetch(:if,Empty::HASH).each do |property, comparisons|
              p = value_for_property(proxy, property, opts)
              if combine_with == :and
                r &= !!p
                r &= comparisons.detect {|c,v| Comparisons.send(c, p, v)}
              elsif p
                r ||= comparisons.detect {|c,v| Comparisons.send(c, p, v)}
              end
            end
            conditions.fetch(:unless,Empty::HASH).each do |property, comparisons|
              p = value_for_property(proxy, property, opts)
              if p
                if combine_with == :and
                  r &= !comparisons.detect {|c,v| Comparisons.send(c, p, v)}
                else
                  r ||= !comparisons.detect {|c,v| Comparisons.send(c, p, v)}
                end
              end
            end
          end
          r
        end
      end
    end
  end
end