Class: Mumukit::Auth::Permissions

Inherits:
Object
  • Object
show all
Includes:
Roles
Defined in:
lib/mumukit/auth/permissions.rb

Constant Summary

Constants included from Roles

Roles::ROLES

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(scopes = {}) ⇒ Permissions

Returns a new instance of Permissions.



6
7
8
9
10
# File 'lib/mumukit/auth/permissions.rb', line 6

def initialize(scopes={})
  raise 'invalid scopes' if scopes.any? { |key, value| value.class != Mumukit::Auth::Scope  }

  @scopes = scopes.with_indifferent_access
end

Instance Attribute Details

#scopesObject

Returns the value of attribute scopes.



4
5
6
# File 'lib/mumukit/auth/permissions.rb', line 4

def scopes
  @scopes
end

Class Method Details

.dump(user) ⇒ Object



54
55
56
# File 'lib/mumukit/auth/permissions.rb', line 54

def self.dump(user)
  user.to_json
end

.load(json) ⇒ Object



46
47
48
49
50
51
52
# File 'lib/mumukit/auth/permissions.rb', line 46

def self.load(json)
  if json.nil?
    parse({})
  else
    parse(JSON.parse(json))
  end
end

.parse(hash) ⇒ Object



42
43
44
# File 'lib/mumukit/auth/permissions.rb', line 42

def self.parse(hash)
  new(Hash[hash.map { |role, grants| [role, Mumukit::Auth::Scope.parse(grants)] }])
end

Instance Method Details

#add_permission!(role, *grants) ⇒ Object



24
25
26
27
# File 'lib/mumukit/auth/permissions.rb', line 24

def add_permission!(role, *grants)
  self.scopes[role] ||= Mumukit::Auth::Scope.new
  scope_for(role)&.add_grant! *grants
end

#as_json(options = {}) ⇒ Object



38
39
40
# File 'lib/mumukit/auth/permissions.rb', line 38

def as_json(options={})
  scopes.as_json(options)
end

#has_permission?(role, resource_slug) ⇒ Boolean

Returns:

  • (Boolean)


12
13
14
# File 'lib/mumukit/auth/permissions.rb', line 12

def has_permission?(role, resource_slug)
  !!scope_for(role)&.allows?(resource_slug)
end

#has_role?(role) ⇒ Boolean

Returns:

  • (Boolean)


16
17
18
# File 'lib/mumukit/auth/permissions.rb', line 16

def has_role?(role)
  scopes[role].present?
end

#remove_permission!(role, grant) ⇒ Object



29
30
31
# File 'lib/mumukit/auth/permissions.rb', line 29

def remove_permission!(role, grant)
  scope_for(role)&.remove_grant!(grant)
end

#scope_for(role) ⇒ Object



20
21
22
# File 'lib/mumukit/auth/permissions.rb', line 20

def scope_for(role)
  self.scopes[role]
end

#update_permission!(role, old_grant, new_grant) ⇒ Object



33
34
35
36
# File 'lib/mumukit/auth/permissions.rb', line 33

def update_permission!(role, old_grant, new_grant)
  remove_permission! role, old_grant
  add_permission! role, new_grant
end