fix ownership-change permission check
[arvados.git] / app / models / metadatum.rb
index bfb58f258590b7aa5544831d1cd9a3e5f84c2afa..3ce96f656906774590c88fa1a8306ea67e6c8e66 100644 (file)
@@ -3,6 +3,8 @@ class Metadatum < OrvosModel
   include KindAndEtag
   include CommonApiTemplate
   serialize :info, Hash
+  before_create :permission_to_attach_to_objects
+  before_update :permission_to_attach_to_objects
 
   api_accessible :superuser, :extend => :common do |t|
     t.add :tail_kind
@@ -18,4 +20,37 @@ class Metadatum < OrvosModel
     @info ||= Hash.new
     super
   end
+
+  protected
+
+  def permission_to_attach_to_objects
+    # Anonymous users cannot write metadata
+    return false if !current_user
+
+    # All users can write metadata that doesn't affect permissions
+    return true if self.metadata_class != 'permission'
+
+    # Administrators can grant permissions
+    return true if current_user.is_admin
+
+    # All users can grant permissions on objects they own
+    head_obj = self.class.
+      kind_class(self.head_kind).
+      where('uuid=?',head_uuid).
+      first
+    if head_obj
+      return true if head_obj.owner == current_user.uuid
+    end
+
+    # Users with "can_grant" permission on an object can grant
+    # permissions on that object
+    has_grant_permission = self.class.
+      where('metadata_class=? AND name=? AND tail=? AND head=?',
+            'permission', 'can_grant', current_user.uuid, self.head).
+      count > 0
+    return true if has_grant_permission
+
+    # Default = deny.
+    false
+  end
 end