Merge branch '1922-cache-discovery-python'
[arvados.git] / services / api / app / controllers / arvados / v1 / collections_controller.rb
1 class Arvados::V1::CollectionsController < ApplicationController
2   def create
3     # Collections are owned by system_user. Creating a collection has
4     # two effects: The collection is added if it doesn't already
5     # exist, and a "permission" Link is added (if one doesn't already
6     # exist) giving the current user (or specified owner_uuid)
7     # permission to read it.
8     owner_uuid = resource_attrs.delete(:owner_uuid) || current_user.uuid
9     owner_kind = if owner_uuid.match(/-(\w+)-/)[1] == User.uuid_prefix
10                    'arvados#user'
11                  else
12                    'arvados#group'
13                  end
14     unless current_user.can? write: owner_uuid
15       raise ArvadosModel::PermissionDeniedError
16     end
17     act_as_system_user do
18       @object = model_class.new resource_attrs.reject { |k,v| k == :owner_uuid }
19       begin
20         @object.save!
21       rescue ActiveRecord::RecordNotUnique
22         logger.debug resource_attrs.inspect
23         if resource_attrs[:manifest_text] and resource_attrs[:uuid]
24           @existing_object = model_class.
25             where('uuid=? and manifest_text=?',
26                   resource_attrs[:uuid],
27                   resource_attrs[:manifest_text]).
28             first
29           @object = @existing_object || @object
30         end
31       end
32
33       if @object
34         link_attrs = {
35           owner_uuid: owner_uuid,
36           link_class: 'permission',
37           name: 'can_read',
38           head_kind: 'arvados#collection',
39           head_uuid: @object.uuid,
40           tail_kind: owner_kind,
41           tail_uuid: owner_uuid
42         }
43         ActiveRecord::Base.transaction do
44           if Link.where(link_attrs).empty?
45             Link.create! link_attrs
46           end
47         end
48       end
49     end
50     show
51   end
52 end