Class: HaveAPI::Authorization

Inherits:
Object
  • Object
show all
Defined in:
lib/haveapi/authorization.rb

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ Authorization

Returns a new instance of Authorization.



3
4
5
# File 'lib/haveapi/authorization.rb', line 3

def initialize(&block)
  @block = block
end

Instance Method Details

#allowObject



44
45
46
# File 'lib/haveapi/authorization.rb', line 44

def allow
  throw(:rule, true)
end

#authorized?(user) ⇒ Boolean

Returns true if user is authorized. Block must call allow to authorize user, default rule is deny.

Returns:



9
10
11
12
13
14
15
16
# File 'lib/haveapi/authorization.rb', line 9

def authorized?(user)
  @restrict = []

  catch(:rule) do
    instance_exec(user, &@block) if @block
    deny # will not be called if block throws allow
  end
end

#denyObject



48
49
50
# File 'lib/haveapi/authorization.rb', line 48

def deny
  throw(:rule, false)
end

#filter_input(input, params) ⇒ Object



62
63
64
# File 'lib/haveapi/authorization.rb', line 62

def filter_input(input, params)
  filter_inner(input, @input, params, false)
end

#filter_output(output, params, format = false) ⇒ Object



66
67
68
# File 'lib/haveapi/authorization.rb', line 66

def filter_output(output, params, format = false)
  filter_inner(output, @output, params, format)
end

#input(whitelist: nil, blacklist: nil) ⇒ Object

Restrict parameters client can set/change.

whitelist

allow only listed parameters

blacklist

allow all parameters except listed ones



27
28
29
30
31
32
# File 'lib/haveapi/authorization.rb', line 27

def input(whitelist: nil, blacklist: nil)
  @input = {
      whitelist: whitelist,
      blacklist: blacklist,
  }
end

#output(whitelist: nil, blacklist: nil) ⇒ Object

Restrict parameters client can retrieve.

whitelist

allow only listed parameters

blacklist

allow all parameters except listed ones



37
38
39
40
41
42
# File 'lib/haveapi/authorization.rb', line 37

def output(whitelist: nil, blacklist: nil)
  @output = {
      whitelist: whitelist,
      blacklist: blacklist,
  }
end

#restrict(*args) ⇒ Object

Apply restrictions on query which selects objects from database. Most common usage is restrict user to access only objects he owns.



20
21
22
# File 'lib/haveapi/authorization.rb', line 20

def restrict(*args)
  @restrict << args.first
end

#restrictionsObject



52
53
54
55
56
57
58
59
60
# File 'lib/haveapi/authorization.rb', line 52

def restrictions
  ret = {}

  @restrict.each do |r|
    ret.update(r)
  end

  ret
end