16007: Almost everything passes
[arvados.git] / services / api / app / models / user.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
7 class User < ArvadosModel
8   include HasUuid
9   include KindAndEtag
10   include CommonApiTemplate
11   include CanBeAnOwner
12   extend CurrentApiClient
13
14   serialize :prefs, Hash
15   has_many :api_client_authorizations
16   validates(:username,
17             format: {
18               with: /\A[A-Za-z][A-Za-z0-9]*\z/,
19               message: "must begin with a letter and contain only alphanumerics",
20             },
21             uniqueness: true,
22             allow_nil: true)
23   validate :must_unsetup_to_deactivate
24   before_update :prevent_privilege_escalation
25   before_update :prevent_inactive_admin
26   before_update :verify_repositories_empty, :if => Proc.new { |user|
27     user.username.nil? and user.username_changed?
28   }
29   before_update :setup_on_activate
30   before_create :check_auto_admin
31   before_create :set_initial_username, :if => Proc.new { |user|
32     user.username.nil? and user.email
33   }
34   after_create :update_permissions
35   after_create :setup_on_activate
36   after_create :add_system_group_permission_link
37   after_create :auto_setup_new_user, :if => Proc.new { |user|
38     Rails.configuration.Users.AutoSetupNewUsers and
39     (user.uuid != system_user_uuid) and
40     (user.uuid != anonymous_user_uuid)
41   }
42   after_create :send_admin_notifications
43   after_update :update_permissions, :if => :owner_uuid_changed?
44   after_update :send_profile_created_notification
45   after_update :sync_repository_names, :if => Proc.new { |user|
46     (user.uuid != system_user_uuid) and
47     user.username_changed? and
48     (not user.username_was.nil?)
49   }
50
51
52   has_many :authorized_keys, :foreign_key => :authorized_user_uuid, :primary_key => :uuid
53   has_many :repositories, foreign_key: :owner_uuid, primary_key: :uuid
54
55   default_scope { where('redirect_to_user_uuid is null') }
56
57   api_accessible :user, extend: :common do |t|
58     t.add :email
59     t.add :username
60     t.add :full_name
61     t.add :first_name
62     t.add :last_name
63     t.add :identity_url
64     t.add :is_active
65     t.add :is_admin
66     t.add :is_invited
67     t.add :prefs
68     t.add :writable_by
69   end
70
71   ALL_PERMISSIONS = {read: true, write: true, manage: true}
72
73   # Map numeric permission levels (see lib/create_permission_view.sql)
74   # back to read/write/manage flags.
75   PERMS_FOR_VAL =
76     [{},
77      {read: true},
78      {read: true, write: true},
79      {read: true, write: true, manage: true}]
80
81   def full_name
82     "#{first_name} #{last_name}".strip
83   end
84
85   def is_invited
86     !!(self.is_active ||
87        Rails.configuration.Users.NewUsersAreActive ||
88        self.groups_i_can(:read).select { |x| x.match(/-f+$/) }.first)
89   end
90
91   def groups_i_can(verb)
92     my_groups = self.group_permissions.select { |uuid, mask| mask[verb] }.keys
93     if verb == :read
94       my_groups << anonymous_group_uuid
95     end
96     my_groups
97   end
98
99   def can?(actions)
100     return true if is_admin
101     actions.each do |action, target|
102       unless target.nil?
103         if target.respond_to? :uuid
104           target_uuid = target.uuid
105         else
106           target_uuid = target
107           target = ArvadosModel.find_by_uuid(target_uuid)
108         end
109       end
110       next if target_uuid == self.uuid
111       next if (group_permissions[target_uuid] and
112                group_permissions[target_uuid][action])
113       if target.respond_to? :owner_uuid
114         next if target.owner_uuid == self.uuid
115         next if (group_permissions[target.owner_uuid] and
116                  group_permissions[target.owner_uuid][action])
117       end
118       sufficient_perms = case action
119                          when :manage
120                            ['can_manage']
121                          when :write
122                            ['can_manage', 'can_write']
123                          when :read
124                            ['can_manage', 'can_write', 'can_read']
125                          else
126                            # (Skip this kind of permission opportunity
127                            # if action is an unknown permission type)
128                          end
129       if sufficient_perms
130         # Check permission links with head_uuid pointing directly at
131         # the target object. If target is a Group, this is redundant
132         # and will fail except [a] if permission caching is broken or
133         # [b] during a race condition, where a permission link has
134         # *just* been added.
135         if Link.where(link_class: 'permission',
136                       name: sufficient_perms,
137                       tail_uuid: groups_i_can(action) + [self.uuid],
138                       head_uuid: target_uuid).any?
139           next
140         end
141       end
142       return false
143     end
144     true
145   end
146
147   def update_permissions
148
149 #       puts "Update permissions for #{uuid}"
150 #     User.printdump %{
151 # select * from materialized_permissions where user_uuid='#{uuid}'
152 # }
153 #     puts "---"
154     User.update_permissions self.owner_uuid, self.uuid, 3
155
156 #   puts "post-update"
157 #    User.printdump %{
158 # select * from materialized_permissions where user_uuid='#{uuid}'
159 # }
160 #    puts "<<<"
161   end
162
163   def self.printdump qr
164     q1 = ActiveRecord::Base.connection.exec_query qr
165     q1.each do |r|
166       puts r
167     end
168   end
169
170   def recompute_permissions
171     ActiveRecord::Base.connection.execute("DELETE FROM #{PERMISSION_VIEW} where user_uuid='#{uuid}'")
172     ActiveRecord::Base.connection.execute %{
173 INSERT INTO #{PERMISSION_VIEW}
174 select '#{uuid}', g.target_uuid, g.val, g.traverse_owned
175 from search_permission_graph('#{uuid}', 3) as g
176 }
177   end
178
179   def self.update_permissions perm_origin_uuid, starting_uuid, perm_level
180     # Update a subset of the permission graph
181     # perm_level is the inherited permission
182     # perm_level is a number from 0-3
183     #   can_read=1
184     #   can_write=2
185     #   can_manage=3
186     #   call with perm_level=0 to revoke permissions
187     #
188     # 1. Compute set (group, permission) implied by traversing
189     #    graph starting at this group
190     # 2. Find links from outside the graph that point inside
191     # 3. For each starting uuid, get the set of permissions from the
192     #    materialized permission table
193     # 3. Delete permissions from table not in our computed subset.
194     # 4. Upsert each permission in our subset (user, group, val)
195
196     ## testinging
197 #     puts "__ update_permissions __"
198 #     puts "What's in there now for #{starting_uuid}"
199 #     printdump %{
200 # select * from materialized_permissions where user_uuid='#{starting_uuid}'
201 # }
202
203 #     puts "search_permission_graph #{perm_origin_uuid} #{starting_uuid}, #{perm_level}"
204 #     printdump %{
205 # select '#{perm_origin_uuid}'::varchar as perm_origin_uuid, target_uuid, val, traverse_owned from search_permission_graph('#{starting_uuid}', #{perm_level})
206 # }
207
208 #     puts "other_links #{perm_origin_uuid} #{starting_uuid}, #{perm_level}"
209 #     printdump %{
210 # with
211 # perm_from_start(perm_origin_uuid, target_uuid, val, traverse_owned) as (
212 #   select '#{perm_origin_uuid}'::varchar, target_uuid, val, traverse_owned
213 #     from search_permission_graph('#{starting_uuid}'::varchar, #{perm_level}))
214
215 #     select links.tail_uuid as perm_origin_uuid, links.head_uuid, links.name
216 #       from links
217 #       where links.link_class='permission' and
218 #         links.tail_uuid not in (select target_uuid from perm_from_start where traverse_owned) and
219 #         links.tail_uuid != '#{perm_origin_uuid}' and
220 #         links.head_uuid in (select target_uuid from perm_from_start)
221 # }
222
223 #     puts "additional_perms #{perm_origin_uuid} #{starting_uuid}, #{perm_level}"
224 #     printdump %{
225 # with
226 # perm_from_start(perm_origin_uuid, target_uuid, val, traverse_owned) as (
227 #   select '#{perm_origin_uuid}'::varchar, target_uuid, val, traverse_owned
228 #     from search_permission_graph('#{starting_uuid}'::varchar, #{perm_level}))
229
230 #     select links.tail_uuid as perm_origin_uuid, ps.target_uuid, ps.val, true
231 #       from links, lateral search_permission_graph(links.head_uuid,
232 #                         CASE
233 #                           WHEN links.name = 'can_read'   THEN 1
234 #                           WHEN links.name = 'can_login'  THEN 1
235 #                           WHEN links.name = 'can_write'  THEN 2
236 #                           WHEN links.name = 'can_manage' THEN 3
237 #                         END) as ps
238 #       where links.link_class='permission' and
239 #         links.tail_uuid not in (select target_uuid from perm_from_start where traverse_owned) and
240 #         links.tail_uuid != '#{perm_origin_uuid}' and
241 #         links.head_uuid in (select target_uuid from perm_from_start)
242 # }
243
244 #     puts "Perms out"
245 #     printdump %{
246 # with
247 # perm_from_start(perm_origin_uuid, target_uuid, val, traverse_owned) as (
248 #   select  '#{perm_origin_uuid}'::varchar, target_uuid, val, traverse_owned
249 #     from search_permission_graph('#{starting_uuid}', #{perm_level}))
250
251 # (select materialized_permissions.user_uuid, u.target_uuid, max(least(materialized_permissions.perm_level, u.val)), bool_or(u.traverse_owned)
252 #   from perm_from_start as u
253 #   join materialized_permissions on (u.perm_origin_uuid = materialized_permissions.target_uuid)
254 #   where materialized_permissions.traverse_owned
255 #   group by materialized_permissions.user_uuid, u.target_uuid)
256 # union
257 #   select target_uuid as user_uuid, target_uuid, 3, true
258 #     from perm_from_start where target_uuid like '_____-tpzed-_______________'
259 # }
260     ## end
261
262     temptable_perms = "temp_perms_#{rand(2**64).to_s(10)}"
263     ActiveRecord::Base.connection.exec_query %{
264 create temporary table #{temptable_perms} on commit drop
265 as select * from compute_permission_subgraph($1, $2, $3)
266 },
267                                              'Group.search_permissions',
268                                              [[nil, perm_origin_uuid],
269                                               [nil, starting_uuid],
270                                               [nil, perm_level]]
271
272 #     q1 = ActiveRecord::Base.connection.exec_query %{
273 # select * from #{temptable_perms} order by user_uuid, target_uuid
274 # }
275 #     puts "recomputed perms was #{perm_origin_uuid} #{starting_uuid}, #{perm_level}"
276 #     q1.each do |r|
277 #       puts r
278 #     end
279 #     puts "<<<<"
280
281     ActiveRecord::Base.connection.exec_query %{
282 delete from materialized_permissions where
283   target_uuid in (select target_uuid from #{temptable_perms}) and
284   (user_uuid not in (select user_uuid from #{temptable_perms} where target_uuid=materialized_permissions.target_uuid)
285    or user_uuid in (select user_uuid from #{temptable_perms} where target_uuid=materialized_permissions.target_uuid and perm_level=0))
286 }
287
288     ActiveRecord::Base.connection.exec_query %{
289 insert into materialized_permissions (user_uuid, target_uuid, perm_level, traverse_owned)
290   select user_uuid, target_uuid, val as perm_level, traverse_owned from #{temptable_perms}
291 on conflict (user_uuid, target_uuid) do update set perm_level=EXCLUDED.perm_level, traverse_owned=EXCLUDED.traverse_owned;
292 }
293
294     # for testing only - make a copy of the table and compare it to the one generated
295     # using a full permission recompute
296 #     temptable_compare = "compare_perms_#{rand(2**64).to_s(10)}"
297 #     ActiveRecord::Base.connection.exec_query %{
298 # create temporary table #{temptable_compare} on commit drop as select * from materialized_permissions
299 # }
300
301     # Ensure a new group can be accessed by the appropriate users
302     # immediately after being created.
303     #User.invalidate_permissions_cache
304
305 #     q1 = ActiveRecord::Base.connection.exec_query %{
306 # select count(*) from materialized_permissions
307 # }
308 #     puts "correct version #{q1.first}"
309
310 #     q2 = ActiveRecord::Base.connection.exec_query %{
311 # select count(*) from #{temptable_compare}
312 # }
313 #     puts "incremental update #{q2.first}"
314   end
315
316   # Return a hash of {user_uuid: group_perms}
317   def self.all_group_permissions
318     all_perms = {}
319     ActiveRecord::Base.connection.
320       exec_query("SELECT user_uuid, target_uuid, perm_level
321                   FROM #{PERMISSION_VIEW}
322                   WHERE traverse_owned",
323                   # "name" arg is a query label that appears in logs:
324                   "all_group_permissions",
325                   ).rows.each do |user_uuid, group_uuid, max_p_val|
326       all_perms[user_uuid] ||= {}
327       all_perms[user_uuid][group_uuid] = PERMS_FOR_VAL[max_p_val.to_i]
328     end
329     all_perms
330   end
331
332   # Return a hash of {group_uuid: perm_hash} where perm_hash[:read]
333   # and perm_hash[:write] are true if this user can read and write
334   # objects owned by group_uuid.
335   def group_permissions
336     group_perms = {self.uuid => {:read => true, :write => true, :manage => true}}
337     ActiveRecord::Base.connection.
338       exec_query("SELECT target_uuid, perm_level
339                   FROM #{PERMISSION_VIEW}
340                   WHERE user_uuid = $1
341                   AND traverse_owned",
342                   # "name" arg is a query label that appears in logs:
343                   "group_permissions_for_user",
344                   # "binds" arg is an array of [col_id, value] for '$1' vars:
345                   [[nil, uuid]],
346                 ).rows.each do |group_uuid, max_p_val|
347       group_perms[group_uuid] = PERMS_FOR_VAL[max_p_val.to_i]
348     end
349     group_perms
350   end
351
352   # create links
353   def setup(repo_name: nil, vm_uuid: nil)
354     repo_perm = create_user_repo_link repo_name
355     vm_login_perm = create_vm_login_permission_link(vm_uuid, username) if vm_uuid
356     group_perm = create_user_group_link
357
358     return [repo_perm, vm_login_perm, group_perm, self].compact
359   end
360
361   # delete user signatures, login, repo, and vm perms, and mark as inactive
362   def unsetup
363     # delete oid_login_perms for this user
364     #
365     # note: these permission links are obsolete, they have no effect
366     # on anything and they are not created for new users.
367     Link.where(tail_uuid: self.email,
368                      link_class: 'permission',
369                      name: 'can_login').destroy_all
370
371     # delete repo_perms for this user
372     Link.where(tail_uuid: self.uuid,
373                      link_class: 'permission',
374                      name: 'can_manage').destroy_all
375
376     # delete vm_login_perms for this user
377     Link.where(tail_uuid: self.uuid,
378                      link_class: 'permission',
379                      name: 'can_login').destroy_all
380
381     # delete "All users" group read permissions for this user
382     group = Group.where(name: 'All users').select do |g|
383       g[:uuid].match(/-f+$/)
384     end.first
385     Link.where(tail_uuid: self.uuid,
386                      head_uuid: group[:uuid],
387                      link_class: 'permission',
388                      name: 'can_read').destroy_all
389
390     # delete any signatures by this user
391     Link.where(link_class: 'signature',
392                      tail_uuid: self.uuid).destroy_all
393
394     # delete user preferences (including profile)
395     self.prefs = {}
396
397     # mark the user as inactive
398     self.is_active = false
399     self.save!
400   end
401
402   def must_unsetup_to_deactivate
403     if self.is_active_changed? &&
404        self.is_active_was == true &&
405        !self.is_active
406
407       group = Group.where(name: 'All users').select do |g|
408         g[:uuid].match(/-f+$/)
409       end.first
410
411       # When a user is set up, they are added to the "All users"
412       # group.  A user that is part of the "All users" group is
413       # allowed to self-activate.
414       #
415       # It doesn't make sense to deactivate a user (set is_active =
416       # false) without first removing them from the "All users" group,
417       # because they would be able to immediately reactivate
418       # themselves.
419       #
420       # The 'unsetup' method removes the user from the "All users"
421       # group (and also sets is_active = false) so send a message
422       # explaining the correct way to deactivate a user.
423       #
424       if Link.where(tail_uuid: self.uuid,
425                     head_uuid: group[:uuid],
426                     link_class: 'permission',
427                     name: 'can_read').any?
428         errors.add :is_active, "cannot be set to false directly, use the 'Deactivate' button on Workbench, or the 'unsetup' API call"
429       end
430     end
431   end
432
433   def set_initial_username(requested: false)
434     if !requested.is_a?(String) || requested.empty?
435       email_parts = email.partition("@")
436       local_parts = email_parts.first.partition("+")
437       if email_parts.any?(&:empty?)
438         return
439       elsif not local_parts.first.empty?
440         requested = local_parts.first
441       else
442         requested = email_parts.first
443       end
444     end
445     requested.sub!(/^[^A-Za-z]+/, "")
446     requested.gsub!(/[^A-Za-z0-9]/, "")
447     unless requested.empty?
448       self.username = find_usable_username_from(requested)
449     end
450   end
451
452   def update_uuid(new_uuid:)
453     if !current_user.andand.is_admin
454       raise PermissionDeniedError
455     end
456     if uuid == system_user_uuid || uuid == anonymous_user_uuid
457       raise "update_uuid cannot update system accounts"
458     end
459     if self.class != self.class.resource_class_for_uuid(new_uuid)
460       raise "invalid new_uuid #{new_uuid.inspect}"
461     end
462     transaction(requires_new: true) do
463       reload
464       old_uuid = self.uuid
465       self.uuid = new_uuid
466       save!(validate: false)
467       change_all_uuid_refs(old_uuid: old_uuid, new_uuid: new_uuid)
468     end
469   end
470
471   # Move this user's (i.e., self's) owned items to new_owner_uuid and
472   # new_user_uuid (for things normally owned directly by the user).
473   #
474   # If redirect_auth is true, also reassign auth tokens and ssh keys,
475   # and redirect this account to redirect_to_user_uuid, i.e., when a
476   # caller authenticates to this account in the future, the account
477   # redirect_to_user_uuid account will be used instead.
478   #
479   # current_user must have admin privileges, i.e., the caller is
480   # responsible for checking permission to do this.
481   def merge(new_owner_uuid:, new_user_uuid:, redirect_to_new_user:)
482     raise PermissionDeniedError if !current_user.andand.is_admin
483     raise "Missing new_owner_uuid" if !new_owner_uuid
484     raise "Missing new_user_uuid" if !new_user_uuid
485     transaction(requires_new: true) do
486       reload
487       raise "cannot merge an already merged user" if self.redirect_to_user_uuid
488
489       new_user = User.where(uuid: new_user_uuid).first
490       raise "user does not exist" if !new_user
491       raise "cannot merge to an already merged user" if new_user.redirect_to_user_uuid
492
493       # If 'self' is a remote user, don't transfer authorizations
494       # (i.e. ability to access the account) to the new user, because
495       # that gives the remote site the ability to access the 'new'
496       # user account that takes over the 'self' account.
497       #
498       # If 'self' is a local user, it is okay to transfer
499       # authorizations, even if the 'new' user is a remote account,
500       # because the remote site does not gain the ability to access an
501       # account it could not before.
502
503       if redirect_to_new_user and self.uuid[0..4] == Rails.configuration.ClusterID
504         # Existing API tokens and ssh keys are updated to authenticate
505         # to the new user.
506         ApiClientAuthorization.
507           where(user_id: id).
508           update_all(user_id: new_user.id)
509
510         user_updates = [
511           [AuthorizedKey, :owner_uuid],
512           [AuthorizedKey, :authorized_user_uuid],
513           [Link, :owner_uuid],
514           [Link, :tail_uuid],
515           [Link, :head_uuid],
516         ]
517       else
518         # Destroy API tokens and ssh keys associated with the old
519         # user.
520         ApiClientAuthorization.where(user_id: id).destroy_all
521         AuthorizedKey.where(owner_uuid: uuid).destroy_all
522         AuthorizedKey.where(authorized_user_uuid: uuid).destroy_all
523         user_updates = [
524           [Link, :owner_uuid],
525           [Link, :tail_uuid]
526         ]
527       end
528
529       # References to the old user UUID in the context of a user ID
530       # (rather than a "home project" in the project hierarchy) are
531       # updated to point to the new user.
532       user_updates.each do |klass, column|
533         klass.where(column => uuid).update_all(column => new_user.uuid)
534       end
535
536       # Need to update repository names to new username
537       if username
538         old_repo_name_re = /^#{Regexp.escape(username)}\//
539         Repository.where(:owner_uuid => uuid).each do |repo|
540           repo.owner_uuid = new_user.uuid
541           repo_name_sub = "#{new_user.username}/"
542           name = repo.name.sub(old_repo_name_re, repo_name_sub)
543           while (conflict = Repository.where(:name => name).first) != nil
544             repo_name_sub += "migrated"
545             name = repo.name.sub(old_repo_name_re, repo_name_sub)
546           end
547           repo.name = name
548           repo.save!
549         end
550       end
551
552       # References to the merged user's "home project" are updated to
553       # point to new_owner_uuid.
554       ActiveRecord::Base.descendants.reject(&:abstract_class?).each do |klass|
555         next if [ApiClientAuthorization,
556                  AuthorizedKey,
557                  Link,
558                  Log,
559                  Repository].include?(klass)
560         next if !klass.columns.collect(&:name).include?('owner_uuid')
561         klass.where(owner_uuid: uuid).update_all(owner_uuid: new_owner_uuid)
562       end
563
564       if redirect_to_new_user
565         update_attributes!(redirect_to_user_uuid: new_user.uuid, username: nil)
566       end
567       self.recompute_permissions
568       new_user.recompute_permissions
569     end
570   end
571
572   def redirects_to
573     user = self
574     redirects = 0
575     while (uuid = user.redirect_to_user_uuid)
576       break if uuid.empty?
577       nextuser = User.unscoped.find_by_uuid(uuid)
578       if !nextuser
579         raise Exception.new("user uuid #{user.uuid} redirects to nonexistent uuid '#{uuid}'")
580       end
581       user = nextuser
582       redirects += 1
583       if redirects > 15
584         raise "Starting from #{self.uuid} redirect_to_user_uuid exceeded maximum number of redirects"
585       end
586     end
587     user
588   end
589
590   def self.register info
591     # login info expected fields, all can be optional but at minimum
592     # must supply either 'identity_url' or 'email'
593     #
594     #   email
595     #   first_name
596     #   last_name
597     #   username
598     #   alternate_emails
599     #   identity_url
600
601     primary_user = nil
602
603     # local database
604     identity_url = info['identity_url']
605
606     if identity_url && identity_url.length > 0
607       # Only local users can create sessions, hence uuid_like_pattern
608       # here.
609       user = User.unscoped.where('identity_url = ? and uuid like ?',
610                                  identity_url,
611                                  User.uuid_like_pattern).first
612       primary_user = user.redirects_to if user
613     end
614
615     if !primary_user
616       # identity url is unset or didn't find matching record.
617       emails = [info['email']] + (info['alternate_emails'] || [])
618       emails.select! {|em| !em.nil? && !em.empty?}
619
620       User.unscoped.where('email in (?) and uuid like ?',
621                           emails,
622                           User.uuid_like_pattern).each do |user|
623         if !primary_user
624           primary_user = user.redirects_to
625         elsif primary_user.uuid != user.redirects_to.uuid
626           raise "Ambiguous email address, directs to both #{primary_user.uuid} and #{user.redirects_to.uuid}"
627         end
628       end
629     end
630
631     if !primary_user
632       # New user registration
633       primary_user = User.new(:owner_uuid => system_user_uuid,
634                               :is_admin => false,
635                               :is_active => Rails.configuration.Users.NewUsersAreActive)
636
637       primary_user.set_initial_username(requested: info['username']) if info['username'] && !info['username'].blank?
638       primary_user.identity_url = info['identity_url'] if identity_url
639     end
640
641     primary_user.email = info['email'] if info['email']
642     primary_user.first_name = info['first_name'] if info['first_name']
643     primary_user.last_name = info['last_name'] if info['last_name']
644
645     if (!primary_user.email or primary_user.email.empty?) and (!primary_user.identity_url or primary_user.identity_url.empty?)
646       raise "Must have supply at least one of 'email' or 'identity_url' to User.register"
647     end
648
649     act_as_system_user do
650       primary_user.save!
651     end
652
653     primary_user
654   end
655
656   protected
657
658   def change_all_uuid_refs(old_uuid:, new_uuid:)
659     ActiveRecord::Base.descendants.reject(&:abstract_class?).each do |klass|
660       klass.columns.each do |col|
661         if col.name.end_with?('_uuid')
662           column = col.name.to_sym
663           klass.where(column => old_uuid).update_all(column => new_uuid)
664         end
665       end
666     end
667   end
668
669   def ensure_ownership_path_leads_to_user
670     true
671   end
672
673   def permission_to_update
674     if username_changed? || redirect_to_user_uuid_changed? || email_changed?
675       current_user.andand.is_admin
676     else
677       # users must be able to update themselves (even if they are
678       # inactive) in order to create sessions
679       self == current_user or super
680     end
681   end
682
683   def permission_to_create
684     current_user.andand.is_admin or
685       (self == current_user &&
686        self.redirect_to_user_uuid.nil? &&
687        self.is_active == Rails.configuration.Users.NewUsersAreActive)
688   end
689
690   def check_auto_admin
691     return if self.uuid.end_with?('anonymouspublic')
692     if (User.where("email = ?",self.email).where(:is_admin => true).count == 0 and
693         !Rails.configuration.Users.AutoAdminUserWithEmail.empty? and self.email == Rails.configuration.Users["AutoAdminUserWithEmail"]) or
694        (User.where("uuid not like '%-000000000000000'").where(:is_admin => true).count == 0 and
695         Rails.configuration.Users.AutoAdminFirstUser)
696       self.is_admin = true
697       self.is_active = true
698     end
699   end
700
701   def find_usable_username_from(basename)
702     # If "basename" is a usable username, return that.
703     # Otherwise, find a unique username "basenameN", where N is the
704     # smallest integer greater than 1, and return that.
705     # Return nil if a unique username can't be found after reasonable
706     # searching.
707     quoted_name = self.class.connection.quote_string(basename)
708     next_username = basename
709     next_suffix = 1
710     while Rails.configuration.Users.AutoSetupUsernameBlacklist[next_username]
711       next_suffix += 1
712       next_username = "%s%i" % [basename, next_suffix]
713     end
714     0.upto(6).each do |suffix_len|
715       pattern = "%s%s" % [quoted_name, "_" * suffix_len]
716       self.class.unscoped.
717           where("username like '#{pattern}'").
718           select(:username).
719           order('username asc').
720           each do |other_user|
721         if other_user.username > next_username
722           break
723         elsif other_user.username == next_username
724           next_suffix += 1
725           next_username = "%s%i" % [basename, next_suffix]
726         end
727       end
728       return next_username if (next_username.size <= pattern.size)
729     end
730     nil
731   end
732
733   def prevent_privilege_escalation
734     if current_user.andand.is_admin
735       return true
736     end
737     if self.is_active_changed?
738       if self.is_active != self.is_active_was
739         logger.warn "User #{current_user.uuid} tried to change is_active from #{self.is_active_was} to #{self.is_active} for #{self.uuid}"
740         self.is_active = self.is_active_was
741       end
742     end
743     if self.is_admin_changed?
744       if self.is_admin != self.is_admin_was
745         logger.warn "User #{current_user.uuid} tried to change is_admin from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
746         self.is_admin = self.is_admin_was
747       end
748     end
749     true
750   end
751
752   def prevent_inactive_admin
753     if self.is_admin and not self.is_active
754       # There is no known use case for the strange set of permissions
755       # that would result from this change. It's safest to assume it's
756       # a mistake and disallow it outright.
757       raise "Admin users cannot be inactive"
758     end
759     true
760   end
761
762   def search_permissions(start, graph, merged={}, upstream_mask=nil, upstream_path={})
763     nextpaths = graph[start]
764     return merged if !nextpaths
765     return merged if upstream_path.has_key? start
766     upstream_path[start] = true
767     upstream_mask ||= ALL_PERMISSIONS
768     nextpaths.each do |head, mask|
769       merged[head] ||= {}
770       mask.each do |k,v|
771         merged[head][k] ||= v if upstream_mask[k]
772       end
773       search_permissions(head, graph, merged, upstream_mask.select { |k,v| v && merged[head][k] }, upstream_path)
774     end
775     upstream_path.delete start
776     merged
777   end
778
779   def create_user_repo_link(repo_name)
780     # repo_name is optional
781     if not repo_name
782       logger.warn ("Repository name not given for #{self.uuid}.")
783       return
784     end
785
786     repo = Repository.where(owner_uuid: uuid, name: repo_name).first_or_create!
787     logger.info { "repo uuid: " + repo[:uuid] }
788     repo_perm = Link.where(tail_uuid: uuid, head_uuid: repo.uuid,
789                            link_class: "permission",
790                            name: "can_manage").first_or_create!
791     logger.info { "repo permission: " + repo_perm[:uuid] }
792     return repo_perm
793   end
794
795   # create login permission for the given vm_uuid, if it does not already exist
796   def create_vm_login_permission_link(vm_uuid, repo_name)
797     # vm uuid is optional
798     return if vm_uuid == ""
799
800     vm = VirtualMachine.where(uuid: vm_uuid).first
801     if !vm
802       logger.warn "Could not find virtual machine for #{vm_uuid.inspect}"
803       raise "No vm found for #{vm_uuid}"
804     end
805
806     logger.info { "vm uuid: " + vm[:uuid] }
807     login_attrs = {
808       tail_uuid: uuid, head_uuid: vm.uuid,
809       link_class: "permission", name: "can_login",
810     }
811
812     login_perm = Link.
813       where(login_attrs).
814       select { |link| link.properties["username"] == repo_name }.
815       first
816
817     login_perm ||= Link.
818       create(login_attrs.merge(properties: {"username" => repo_name}))
819
820     logger.info { "login permission: " + login_perm[:uuid] }
821     login_perm
822   end
823
824   # add the user to the 'All users' group
825   def create_user_group_link
826     #puts "In create_user_group_link"
827     return (Link.where(tail_uuid: self.uuid,
828                        head_uuid: all_users_group[:uuid],
829                        link_class: 'permission',
830                        name: 'can_read').first or
831             Link.create(tail_uuid: self.uuid,
832                         head_uuid: all_users_group[:uuid],
833                         link_class: 'permission',
834                         name: 'can_read'))
835   end
836
837   # Give the special "System group" permission to manage this user and
838   # all of this user's stuff.
839   def add_system_group_permission_link
840     return true if uuid == system_user_uuid
841     act_as_system_user do
842       Link.create(link_class: 'permission',
843                   name: 'can_manage',
844                   tail_uuid: system_group_uuid,
845                   head_uuid: self.uuid)
846     end
847   end
848
849   # Send admin notifications
850   def send_admin_notifications
851     AdminNotifier.new_user(self).deliver_now
852     if not self.is_active then
853       AdminNotifier.new_inactive_user(self).deliver_now
854     end
855   end
856
857   # Automatically setup if is_active flag turns on
858   def setup_on_activate
859     return if [system_user_uuid, anonymous_user_uuid].include?(self.uuid)
860     if is_active && (new_record? || is_active_changed?)
861       setup
862     end
863   end
864
865   # Automatically setup new user during creation
866   def auto_setup_new_user
867     setup
868     if username
869       create_vm_login_permission_link(Rails.configuration.Users.AutoSetupNewUsersWithVmUUID,
870                                       username)
871       repo_name = "#{username}/#{username}"
872       if Rails.configuration.Users.AutoSetupNewUsersWithRepository and
873           Repository.where(name: repo_name).first.nil?
874         repo = Repository.create!(name: repo_name, owner_uuid: uuid)
875         Link.create!(tail_uuid: uuid, head_uuid: repo.uuid,
876                      link_class: "permission", name: "can_manage")
877       end
878     end
879   end
880
881   # Send notification if the user saved profile for the first time
882   def send_profile_created_notification
883     if self.prefs_changed?
884       if self.prefs_was.andand.empty? || !self.prefs_was.andand['profile']
885         profile_notification_address = Rails.configuration.Users.UserProfileNotificationAddress
886         ProfileNotifier.profile_created(self, profile_notification_address).deliver_now if profile_notification_address and !profile_notification_address.empty?
887       end
888     end
889   end
890
891   def verify_repositories_empty
892     unless repositories.first.nil?
893       errors.add(:username, "can't be unset when the user owns repositories")
894       throw(:abort)
895     end
896   end
897
898   def sync_repository_names
899     old_name_re = /^#{Regexp.escape(username_was)}\//
900     name_sub = "#{username}/"
901     repositories.find_each do |repo|
902       repo.name = repo.name.sub(old_name_re, name_sub)
903       repo.save!
904     end
905   end
906 end