Prevent admin from creating an object with empty string as UUID.
[arvados.git] / services / api / lib / has_uuid.rb
1 module HasUuid
2
3   def self.included(base)
4     base.extend(ClassMethods)
5     base.before_create :assign_uuid
6     base.before_destroy :destroy_permission_links
7     base.has_many :links_via_head, class_name: 'Link', foreign_key: :head_uuid, primary_key: :uuid, conditions: "not (link_class = 'permission')", dependent: :restrict
8     base.has_many :links_via_tail, class_name: 'Link', foreign_key: :tail_uuid, primary_key: :uuid, conditions: "not (link_class = 'permission')", dependent: :restrict
9   end
10
11   module ClassMethods
12     def uuid_prefix
13       Digest::MD5.hexdigest(self.to_s).to_i(16).to_s(36)[-5..-1]
14     end
15     def generate_uuid
16       [Server::Application.config.uuid_prefix,
17        self.uuid_prefix,
18        rand(2**256).to_s(36)[-15..-1]].
19         join '-'
20     end
21   end
22
23   protected
24
25   def respond_to_uuid?
26     self.respond_to? :uuid
27   end
28
29   def assign_uuid
30     return true if !self.respond_to_uuid?
31     if (uuid.is_a?(String) and uuid.length>0 and
32         current_user and current_user.is_admin)
33       return true
34     end
35     self.uuid = self.class.generate_uuid
36   end
37
38   def destroy_permission_links
39     Link.destroy_all(['link_class=? and (head_uuid=? or tail_uuid=?)',
40                       'permission', uuid, uuid])
41   end
42 end