Merge branch '1968-monitor-disk-usage'
[arvados.git] / services / api / app / models / link.rb
1 class Link < ArvadosModel
2   include AssignUuid
3   include KindAndEtag
4   include CommonApiTemplate
5   serialize :properties, Hash
6   before_create :permission_to_attach_to_objects
7   before_update :permission_to_attach_to_objects
8   after_update :maybe_invalidate_permissions_cache
9   after_create :maybe_invalidate_permissions_cache
10   after_destroy :maybe_invalidate_permissions_cache
11   attr_accessor :head_kind, :tail_kind
12   validate :name_link_has_valid_name
13
14   api_accessible :user, extend: :common do |t|
15     t.add :tail_uuid
16     t.add :link_class
17     t.add :name
18     t.add :head_uuid
19     t.add :head_kind
20     t.add :tail_kind
21     t.add :properties
22   end
23
24   def properties
25     @properties ||= Hash.new
26     super
27   end
28
29   def head_kind
30     if k = ArvadosModel::resource_class_for_uuid(head_uuid)
31       k.kind
32     end
33   end
34
35   def tail_kind
36     if k = ArvadosModel::resource_class_for_uuid(tail_uuid)
37       k.kind
38     end
39   end
40
41   protected
42
43   def permission_to_attach_to_objects
44     # Anonymous users cannot write links
45     return false if !current_user
46
47     # All users can write links that don't affect permissions
48     return true if self.link_class != 'permission'
49
50     # Administrators can grant permissions
51     return true if current_user.is_admin
52
53     # All users can grant permissions on objects they own
54     head_obj = self.class.
55       resource_class_for_uuid(self.head_uuid).
56       where('uuid=?',head_uuid).
57       first
58     if head_obj
59       return true if head_obj.owner_uuid == current_user.uuid
60     end
61
62     # Users with "can_grant" permission on an object can grant
63     # permissions on that object
64     has_grant_permission = self.class.
65       where('link_class=? AND name=? AND tail_uuid=? AND head_uuid=?',
66             'permission', 'can_grant', current_user.uuid, self.head_uuid).
67       count > 0
68     return true if has_grant_permission
69
70     # Default = deny.
71     false
72   end
73
74   def maybe_invalidate_permissions_cache
75     if self.link_class == 'permission'
76       # Clearing the entire permissions cache can generate many
77       # unnecessary queries if many active users are not affected by
78       # this change. In such cases it would be better to search cached
79       # permissions for head_uuid and tail_uuid, and invalidate the
80       # cache for only those users. (This would require a browseable
81       # cache.)
82       User.invalidate_permissions_cache
83     end
84   end
85
86   def name_link_has_valid_name
87     if link_class == 'name'
88       unless name.is_a? String and !name.empty?
89         errors.add('name', 'must be a non-empty string')
90       end
91     else
92       true
93     end
94   end
95 end