Update user model to return a List instead of HashList
[arvados.git] / services / api / app / models / user.rb
1 class User < ArvadosModel
2   include AssignUuid
3   include KindAndEtag
4   include CommonApiTemplate
5   serialize :prefs, Hash
6   has_many :api_client_authorizations
7   before_update :prevent_privilege_escalation
8   before_update :prevent_inactive_admin
9   before_create :check_auto_admin
10   after_create AdminNotifier
11
12   has_many :authorized_keys, :foreign_key => :authorized_user_uuid, :primary_key => :uuid
13
14   api_accessible :user, extend: :common do |t|
15     t.add :email
16     t.add :full_name
17     t.add :first_name
18     t.add :last_name
19     t.add :identity_url
20     t.add :is_active
21     t.add :is_admin
22     t.add :is_invited
23     t.add :prefs
24   end
25
26   ALL_PERMISSIONS = {read: true, write: true, manage: true}
27
28   def full_name
29     "#{first_name} #{last_name}"
30   end
31
32   def is_invited
33     !!(self.is_active ||
34        Rails.configuration.new_users_are_active ||
35        self.groups_i_can(:read).select { |x| x.match /-f+$/ }.first)
36   end
37
38   def groups_i_can(verb)
39     self.group_permissions.select { |uuid, mask| mask[verb] }.keys
40   end
41
42   def can?(actions)
43     return true if is_admin
44     actions.each do |action, target|
45       target_uuid = target
46       if target.respond_to? :uuid
47         target_uuid = target.uuid
48       end
49       next if target_uuid == self.uuid
50       next if (group_permissions[target_uuid] and
51                group_permissions[target_uuid][action])
52       if target.respond_to? :owner_uuid
53         next if target.owner_uuid == self.uuid
54         next if (group_permissions[target.owner_uuid] and
55                  group_permissions[target.owner_uuid][action])
56       end
57       return false
58     end
59     true
60   end
61
62   def self.invalidate_permissions_cache
63     Rails.cache.delete_matched(/^groups_for_user_/)
64   end
65
66   # Return a hash of {group_uuid: perm_hash} where perm_hash[:read]
67   # and perm_hash[:write] are true if this user can read and write
68   # objects owned by group_uuid.
69   def group_permissions
70     Rails.cache.fetch "groups_for_user_#{self.uuid}" do
71       permissions_from = {}
72       todo = {self.uuid => true}
73       done = {}
74       while !todo.empty?
75         lookup_uuids = todo.keys
76         lookup_uuids.each do |uuid| done[uuid] = true end
77         todo = {}
78         newgroups = []
79         Group.where('owner_uuid in (?)', lookup_uuids).each do |group|
80           newgroups << [group.owner_uuid, group.uuid, 'can_manage']
81         end
82         Link.where('tail_uuid in (?) and link_class = ? and head_kind = ?',
83                    lookup_uuids,
84                    'permission',
85                    'arvados#group').each do |link|
86           newgroups << [link.tail_uuid, link.head_uuid, link.name]
87         end
88         newgroups.each do |tail_uuid, head_uuid, perm_name|
89           unless done.has_key? head_uuid
90             todo[head_uuid] = true
91           end
92           link_permissions = {}
93           case perm_name
94           when 'can_read'
95             link_permissions = {read:true}
96           when 'can_write'
97             link_permissions = {read:true,write:true}
98           when 'can_manage'
99             link_permissions = ALL_PERMISSIONS
100           end
101           permissions_from[tail_uuid] ||= {}
102           permissions_from[tail_uuid][head_uuid] ||= {}
103           link_permissions.each do |k,v|
104             permissions_from[tail_uuid][head_uuid][k] ||= v
105           end
106         end
107       end
108       search_permissions(self.uuid, permissions_from)
109     end
110   end
111
112   def self.setup(user, openid_prefix, repo_name=nil, vm_uuid=nil)
113     login_perm_props = {identity_url_prefix: openid_prefix}
114
115     if user.uuid
116       found = User.find_by_uuid user.uuid
117       if found
118         user = found
119       end
120     end
121
122     if !found
123       if !user.email
124         raise "No email found in the input. Aborting user creation."
125       end
126
127       user.save!
128     
129       # Check oid_login_perm
130       oid_login_perms = Link.where(tail_uuid: user.email,
131                                    head_kind: 'arvados#user',
132                                    link_class: 'permission',
133                                    name: 'can_login')
134
135       if !oid_login_perms.any?
136         # create openid login permission
137         oid_login_perm = Link.create(link_class: 'permission',
138                                    name: 'can_login',
139                                    tail_kind: 'email',
140                                    tail_uuid: user.email,
141                                    head_kind: 'arvados#user',
142                                    head_uuid: user.uuid,
143                                    properties: login_perm_props
144                                   )
145         logger.info { "openid login permission: " + oid_login_perm[:uuid] }
146       else
147         oid_login_perm = oid_login_perms.first
148       end
149     end
150
151     return [user, oid_login_perm] + user.setup_repo_vm_links(repo_name, vm_uuid)
152   end 
153
154   # create links
155   def setup_repo_vm_links(repo_name, vm_uuid)
156     repo_perm = create_user_repo_link repo_name
157     vm_login_perm = create_vm_login_permission_link vm_uuid, repo_name
158     group_perm = create_user_group_link
159
160     return [repo_perm, vm_login_perm, group_perm].compact
161   end 
162
163   protected
164
165   def permission_to_update
166     # users must be able to update themselves (even if they are
167     # inactive) in order to create sessions
168     self == current_user or super
169   end
170
171   def permission_to_create
172     current_user.andand.is_admin or
173       (self == current_user and
174        self.is_active == Rails.configuration.new_users_are_active)
175   end
176
177   def check_auto_admin
178     if User.where("uuid not like '%-000000000000000'").where(:is_admin => true).count == 0 and Rails.configuration.auto_admin_user
179       if current_user.email == Rails.configuration.auto_admin_user
180         self.is_admin = true
181         self.is_active = true
182       end
183     end
184   end
185
186   def prevent_privilege_escalation
187     if current_user.andand.is_admin
188       return true
189     end
190     if self.is_active_changed?
191       if self.is_active != self.is_active_was
192         logger.warn "User #{current_user.uuid} tried to change is_active from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
193         self.is_active = self.is_active_was
194       end
195     end
196     if self.is_admin_changed?
197       if self.is_admin != self.is_admin_was
198         logger.warn "User #{current_user.uuid} tried to change is_admin from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
199         self.is_admin = self.is_admin_was
200       end
201     end
202     true
203   end
204
205   def prevent_inactive_admin
206     if self.is_admin and not self.is_active
207       # There is no known use case for the strange set of permissions
208       # that would result from this change. It's safest to assume it's
209       # a mistake and disallow it outright.
210       raise "Admin users cannot be inactive"
211     end
212     true
213   end
214
215   def search_permissions(start, graph, merged={}, upstream_mask=nil, upstream_path={})
216     nextpaths = graph[start]
217     return merged if !nextpaths
218     return merged if upstream_path.has_key? start
219     upstream_path[start] = true
220     upstream_mask ||= ALL_PERMISSIONS
221     nextpaths.each do |head, mask|
222       merged[head] ||= {}
223       mask.each do |k,v|
224         merged[head][k] ||= v if upstream_mask[k]
225       end
226       search_permissions(head, graph, merged, upstream_mask.select { |k,v| v && merged[head][k] }, upstream_path)
227     end
228     upstream_path.delete start
229     merged
230   end
231
232   def create_user_repo_link(repo_name)
233     # repo_name is optional
234     if not repo_name
235       logger.warn ("Repository name not given for #{self.uuid}.")
236       return
237     end
238
239     # Check for an existing repository with the same name we're about to use.
240     repo = Repository.where(name: repo_name).first
241
242     if repo
243       logger.warn "Repository exists for #{repo_name}: #{repo[:uuid]}."
244
245       # Look for existing repository access for this repo
246       repo_perms = Link.where(tail_uuid: self.uuid,
247                               head_kind: 'arvados#repository',
248                               head_uuid: repo[:uuid],
249                               link_class: 'permission',
250                               name: 'can_write')
251       if repo_perms.any?
252         logger.warn "User already has repository access " + 
253             repo_perms.collect { |p| p[:uuid] }.inspect
254         return repo_perms.first
255       end
256     end
257
258     # create repo, if does not already exist
259     repo ||= Repository.create(name: repo_name)
260     logger.info { "repo uuid: " + repo[:uuid] }
261
262     repo_perm = Link.create(tail_kind: 'arvados#user',
263                             tail_uuid: self.uuid,
264                             head_kind: 'arvados#repository',
265                             head_uuid: repo[:uuid],
266                             link_class: 'permission',
267                             name: 'can_write')
268     logger.info { "repo permission: " + repo_perm[:uuid] }
269     return repo_perm
270   end
271
272   # create login permission for the given vm_uuid, if it does not already exist
273   def create_vm_login_permission_link(vm_uuid, repo_name)
274     begin
275               
276       # vm uuid is optional
277       if vm_uuid 
278         vm = VirtualMachine.where(uuid: vm_uuid).first
279
280         if not vm
281           logger.warn "Could not find virtual machine for #{vm_uuid.inspect}"
282           raise "No vm found for #{vm_uuid}"
283         end
284       else
285         return 
286       end
287
288       logger.info { "vm uuid: " + vm[:uuid] }
289
290       login_perms = Link.where(tail_uuid: self.uuid,
291                               head_uuid: vm[:uuid],
292                               head_kind: 'arvados#virtualMachine',
293                               link_class: 'permission',
294                               name: 'can_login')
295       if !login_perms.any?
296         login_perm = Link.create(tail_kind: 'arvados#user',
297                                  tail_uuid: self.uuid,
298                                  head_kind: 'arvados#virtualMachine',
299                                  head_uuid: vm[:uuid],
300                                  link_class: 'permission',
301                                  name: 'can_login',
302                                  properties: {username: repo_name})
303         logger.info { "login permission: " + login_perm[:uuid] }
304       else
305         login_perm = login_perms.first
306       end
307
308       return login_perm
309     end
310   end
311
312   # add the user to the 'All users' group
313   def create_user_group_link
314     # Look up the "All users" group (we expect uuid *-*-fffffffffffffff).
315     group = Group.where(name: 'All users').select do |g|
316       g[:uuid].match /-f+$/
317     end.first
318
319     if not group
320       logger.warn "No 'All users' group with uuid '*-*-fffffffffffffff'."
321       raise "No 'All users' group with uuid '*-*-fffffffffffffff' is found"
322     else
323       logger.info { "\"All users\" group uuid: " + group[:uuid] }
324
325       group_perms = Link.where(tail_uuid: self.uuid,
326                               head_uuid: group[:uuid],
327                               head_kind: 'arvados#group',
328                               link_class: 'permission',
329                               name: 'can_read')
330
331       if !group_perms.any?
332         group_perm = Link.create(tail_kind: 'arvados#user',
333                                  tail_uuid: self.uuid,
334                                  head_kind: 'arvados#group',
335                                  head_uuid: group[:uuid],
336                                  link_class: 'permission',
337                                  name: 'can_read')
338         logger.info { "group permission: " + group_perm[:uuid] }
339       else 
340         group_perm = group_perms.first
341       end
342
343       return group_perm
344     end
345   end
346
347 end