f64a5b259084b608dd5f74c31b719ca39b53f044
[arvados.git] / services / api / app / models / group.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 require 'can_be_an_owner'
6 require 'trashable'
7
8 class Group < ArvadosModel
9   include HasUuid
10   include KindAndEtag
11   include CommonApiTemplate
12   include CanBeAnOwner
13   include Trashable
14
15   # Posgresql JSONB columns should NOT be declared as serialized, Rails 5
16   # already know how to properly treat them.
17   attribute :properties, :jsonbHash, default: {}
18
19   validate :ensure_filesystem_compatible_name
20   after_create :invalidate_permissions_cache
21   after_update :maybe_invalidate_permissions_cache
22   before_create :assign_name
23
24   api_accessible :user, extend: :common do |t|
25     t.add :name
26     t.add :group_class
27     t.add :description
28     t.add :writable_by
29     t.add :delete_at
30     t.add :trash_at
31     t.add :is_trashed
32     t.add :properties
33   end
34
35   def ensure_filesystem_compatible_name
36     # project groups need filesystem-compatible names, but others
37     # don't.
38     super if group_class == 'project'
39   end
40
41   def maybe_invalidate_permissions_cache
42     if is_trashed_changed? or owner_uuid_changed?
43       if is_trashed == true
44         ActiveRecord::Base.connection.exec_query %{
45 insert into trashed_groups (group_uuid) select * from project_subtree($1);
46 },
47                                                  'Group.trash_subtree',
48                                                  [[nil, self.uuid]]
49       elsif is_trashed == false && TrashedGroup.find_by_group_uuid(self.owner_uuid).nil?
50         ActiveRecord::Base.connection.exec_query %{
51 delete from trashed_groups where group_uuid in (select * from project_subtree_notrash($1));
52 },
53                               'Group.untrash_subtree',
54                               [[nil, self.uuid]]
55       end
56     end
57     if uuid_changed? or owner_uuid_changed? or is_trashed_changed?
58       # This can change users' permissions on other groups as well as
59       # this one.
60       invalidate_permissions_cache
61     end
62   end
63
64   def invalidate_permissions_cache
65     # Ensure a new group can be accessed by the appropriate users
66     # immediately after being created.
67     User.invalidate_permissions_cache self.async_permissions_update
68   end
69
70   def assign_name
71     if self.new_record? and (self.name.nil? or self.name.empty?)
72       self.name = self.uuid
73     end
74     true
75   end
76 end