21030: Use a CTE instead of temporary table for trash and frozen
[arvados.git] / services / api / app / models / link.rb
index 83043a56d19026d32a8c3fa65dc839908f74ee86..4d4c2832bbd62e3d8cb5c731f5fcb65895ca9b7a 100644 (file)
@@ -14,9 +14,13 @@ class Link < ArvadosModel
   validate :name_links_are_obsolete
   validate :permission_to_attach_to_objects
   before_update :restrict_alter_permissions
+  before_update :apply_max_overlapping_permissions
+  before_create :apply_max_overlapping_permissions
+  after_update :delete_overlapping_permissions
   after_update :call_update_permissions
   after_create :call_update_permissions
   before_destroy :clear_permissions
+  after_destroy :delete_overlapping_permissions
   after_destroy :check_permissions
 
   api_accessible :user, extend: :common do |t|
@@ -29,6 +33,58 @@ class Link < ArvadosModel
     t.add :properties
   end
 
+  PermLevel = {
+    'can_read' => 0,
+    'can_write' => 1,
+    'can_manage' => 2,
+  }
+
+  def apply_max_overlapping_permissions
+    return if self.link_class != 'permission' || !PermLevel[self.name]
+    Link.
+      lock. # select ... for update
+      where(link_class: 'permission',
+            tail_uuid: self.tail_uuid,
+            head_uuid: self.head_uuid,
+            name: PermLevel.keys).
+      where('uuid <> ?', self.uuid).each do |other|
+      if PermLevel[other.name] > PermLevel[self.name]
+        self.name = other.name
+      end
+    end
+  end
+
+  def delete_overlapping_permissions
+    return if self.link_class != 'permission'
+    redundant = nil
+    if PermLevel[self.name]
+      redundant = Link.
+                    lock. # select ... for update
+                    where(link_class: 'permission',
+                          tail_uuid: self.tail_uuid,
+                          head_uuid: self.head_uuid,
+                          name: PermLevel.keys).
+                    where('uuid <> ?', self.uuid)
+    elsif self.name == 'can_login' &&
+          self.properties.respond_to?(:has_key?) &&
+          self.properties.has_key?('username')
+      redundant = Link.
+                    lock. # select ... for update
+                    where(link_class: 'permission',
+                          tail_uuid: self.tail_uuid,
+                          head_uuid: self.head_uuid,
+                          name: 'can_login').
+                    where('properties @> ?', SafeJSON.dump({'username' => self.properties['username']})).
+                    where('uuid <> ?', self.uuid)
+    end
+    if redundant
+      redundant.each do |link|
+        link.clear_permissions
+      end
+      redundant.delete_all
+    end
+  end
+
   def head_kind
     if k = ArvadosModel::resource_class_for_uuid(head_uuid)
       k.kind