Module: Sinatra::Authorize

Defined in:
lib/sinatra/authorize.rb,
lib/sinatra-authorize/version.rb

Defined Under Namespace

Classes: Condition

Constant Summary collapse

VERSION =
"0.0.2"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.registered(app) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/sinatra/authorize.rb', line 48

def registered(app)
  app.class_eval do
    alias :old_process_route :process_route

    def process_route(pattern, keys, conditions, &block)
      authorize_conditions = conditions.select do |cond|
        cond.is_a?(Authorize::Condition)
      end

      regular_conditions = conditions - authorize_conditions

      old_process_route(pattern, keys, regular_conditions) do
        throw :halt, 403 if authorize_route(authorize_conditions) == false
        yield
      end
    end

    def authorize_route(conditions)
      unless settings.respond_to? :authorize_block
        raise "No authorize block is defined."
      end

      [settings.authorize_default, *conditions].reverse.each do |cond|
        value = instance_eval(&cond)
        return value if value == true || value == false
      end

      settings.authorize_default.rule == :allow
    end
  end
end

Instance Method Details

#allow(*args) ⇒ Object



33
34
35
# File 'lib/sinatra/authorize.rb', line 33

def allow(*args)
  condition &(authorize_condition(:allow, args))
end

#authorize(opts = {}, &block) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/sinatra/authorize.rb', line 13

def authorize(opts = {}, &block)
  opts = {opts => []} if opts.is_a?(Symbol)

  if opts[:deny]
    args = *(opts[:deny])
    set :authorize_default, Proc.new { authorize_condition(:deny, args) }
  else
    args = *(opts[:allow] || [])
    set :authorize_default, Proc.new { authorize_condition(:allow, args) }
  end

  if block_given?
    define_method(:authorize_block, block)
    authorize_block = instance_method(:authorize_block)
    remove_method(:authorize_block)

    set :authorize_block, Proc.new { authorize_block }
  end
end

#authorize_condition(rule, args) ⇒ Object



41
42
43
44
45
# File 'lib/sinatra/authorize.rb', line 41

def authorize_condition(rule, args)
  Condition.new rule do
    settings.authorize_block.bind(self).call(rule, args) 
  end
end

#deny(*args) ⇒ Object



37
38
39
# File 'lib/sinatra/authorize.rb', line 37

def deny(*args)
  condition &(authorize_condition(:deny, args))
end