Merge branch '21059-signup-email' refs #21059
[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   validate :identity_url_nil_if_empty
25   before_update :prevent_privilege_escalation
26   before_update :prevent_inactive_admin
27   before_update :prevent_nonadmin_system_root
28   before_update :verify_repositories_empty, :if => Proc.new {
29     username.nil? and username_changed?
30   }
31   after_update :setup_on_activate
32
33   before_create :check_auto_admin
34   before_validation :set_initial_username, :if => Proc.new {
35     new_record? && email
36   }
37   before_create :active_is_not_nil
38   after_create :after_ownership_change
39   after_create :setup_on_activate
40   after_create :add_system_group_permission_link
41   after_create :auto_setup_new_user, :if => Proc.new {
42     Rails.configuration.Users.AutoSetupNewUsers and
43     (uuid != system_user_uuid) and
44     (uuid != anonymous_user_uuid) and
45     (uuid[0..4] == Rails.configuration.ClusterID)
46   }
47   after_create :send_admin_notifications
48
49   before_update :before_ownership_change
50   after_update :after_ownership_change
51   after_update :send_profile_created_notification
52   after_update :sync_repository_names, :if => Proc.new {
53     (uuid != system_user_uuid) and
54     saved_change_to_username? and
55     (not username_before_last_save.nil?)
56   }
57   before_destroy :clear_permissions
58   after_destroy :remove_self_from_permissions
59
60   has_many :authorized_keys, foreign_key: 'authorized_user_uuid', primary_key: 'uuid'
61   has_many :repositories, foreign_key: 'owner_uuid', primary_key: 'uuid'
62
63   default_scope { where('redirect_to_user_uuid is null') }
64
65   api_accessible :user, extend: :common do |t|
66     t.add :email
67     t.add :username
68     t.add :full_name
69     t.add :first_name
70     t.add :last_name
71     t.add :identity_url
72     t.add :is_active
73     t.add :is_admin
74     t.add :is_invited
75     t.add :prefs
76     t.add :writable_by
77     t.add :can_write
78     t.add :can_manage
79   end
80
81   ALL_PERMISSIONS = {read: true, write: true, manage: true}
82
83   # Map numeric permission levels (see lib/create_permission_view.sql)
84   # back to read/write/manage flags.
85   PERMS_FOR_VAL =
86     [{},
87      {read: true},
88      {read: true, write: true},
89      {read: true, write: true, manage: true}]
90
91   VAL_FOR_PERM =
92     {:read => 1,
93      :write => 2,
94      :unfreeze => 3,
95      :manage => 3}
96
97
98   def full_name
99     "#{first_name} #{last_name}".strip
100   end
101
102   def is_invited
103     !!(self.is_active ||
104        Rails.configuration.Users.NewUsersAreActive ||
105        self.groups_i_can(:read).select { |x| x.match(/-f+$/) }.first)
106   end
107
108   def self.ignored_select_attributes
109     super + ["full_name", "is_invited"]
110   end
111
112   def groups_i_can(verb)
113     my_groups = self.group_permissions(VAL_FOR_PERM[verb]).keys
114     if verb == :read
115       my_groups << anonymous_group_uuid
116     end
117     my_groups
118   end
119
120   def can?(actions)
121     actions.each do |action, target|
122       unless target.nil?
123         if target.respond_to? :uuid
124           target_uuid = target.uuid
125         else
126           target_uuid = target
127           target = ArvadosModel.find_by_uuid(target_uuid)
128         end
129       end
130       next if target_uuid == self.uuid
131
132       if action == :write && target && !target.new_record? &&
133          target.respond_to?(:frozen_by_uuid) &&
134          target.frozen_by_uuid_was
135         # Just an optimization to skip the PERMISSION_VIEW and
136         # FrozenGroup queries below
137         return false
138       end
139
140       target_owner_uuid = target.owner_uuid if target.respond_to? :owner_uuid
141
142       user_uuids_subquery = USER_UUIDS_SUBQUERY_TEMPLATE % {user: "$1", perm_level: "$3"}
143
144       if !is_admin && !ActiveRecord::Base.connection.
145         exec_query(%{
146 SELECT 1 FROM #{PERMISSION_VIEW}
147   WHERE user_uuid in (#{user_uuids_subquery}) and
148         ((target_uuid = $2 and perm_level >= $3)
149          or (target_uuid = $4 and perm_level >= $3 and traverse_owned))
150 },
151                   # "name" arg is a query label that appears in logs:
152                    "user_can_query",
153                    [self.uuid,
154                     target_uuid,
155                     VAL_FOR_PERM[action],
156                     target_owner_uuid]
157                   ).any?
158         return false
159       end
160
161       if action == :write
162         if FrozenGroup.where(uuid: [target_uuid, target_owner_uuid]).any?
163           # self or parent is frozen
164           return false
165         end
166       elsif action == :unfreeze
167         # "unfreeze" permission means "can write, but only if
168         # explicitly un-freezing at the same time" (see
169         # ArvadosModel#ensure_owner_uuid_is_permitted). If the
170         # permission query above passed the permission level of
171         # :unfreeze (which is the same as :manage), and the parent
172         # isn't also frozen, then un-freeze is allowed.
173         if FrozenGroup.where(uuid: target_owner_uuid).any?
174           return false
175         end
176       end
177     end
178     true
179   end
180
181   def before_ownership_change
182     if owner_uuid_changed? and !self.owner_uuid_was.nil?
183       MaterializedPermission.where(user_uuid: owner_uuid_was, target_uuid: uuid).delete_all
184       update_permissions self.owner_uuid_was, self.uuid, REVOKE_PERM
185     end
186   end
187
188   def after_ownership_change
189     if saved_change_to_owner_uuid?
190       update_permissions self.owner_uuid, self.uuid, CAN_MANAGE_PERM
191     end
192   end
193
194   def clear_permissions
195     MaterializedPermission.where("user_uuid = ? and target_uuid != ?", uuid, uuid).delete_all
196   end
197
198   def forget_cached_group_perms
199     @group_perms = nil
200   end
201
202   def remove_self_from_permissions
203     MaterializedPermission.where("target_uuid = ?", uuid).delete_all
204     check_permissions_against_full_refresh
205   end
206
207   # Return a hash of {user_uuid: group_perms}
208   #
209   # note: this does not account for permissions that a user gains by
210   # having can_manage on another user.
211   def self.all_group_permissions
212     all_perms = {}
213     ActiveRecord::Base.connection.
214       exec_query(%{
215 SELECT user_uuid, target_uuid, perm_level
216                   FROM #{PERMISSION_VIEW}
217                   WHERE traverse_owned
218 },
219                   # "name" arg is a query label that appears in logs:
220                  "all_group_permissions").
221       rows.each do |user_uuid, group_uuid, max_p_val|
222       all_perms[user_uuid] ||= {}
223       all_perms[user_uuid][group_uuid] = PERMS_FOR_VAL[max_p_val.to_i]
224     end
225     all_perms
226   end
227
228   # Return a hash of {group_uuid: perm_hash} where perm_hash[:read]
229   # and perm_hash[:write] are true if this user can read and write
230   # objects owned by group_uuid.
231   def group_permissions(level=1)
232     @group_perms ||= {}
233     if @group_perms.empty?
234       user_uuids_subquery = USER_UUIDS_SUBQUERY_TEMPLATE % {user: "$1", perm_level: 1}
235
236       ActiveRecord::Base.connection.
237         exec_query(%{
238 SELECT target_uuid, perm_level
239   FROM #{PERMISSION_VIEW}
240   WHERE user_uuid in (#{user_uuids_subquery}) and perm_level >= 1
241 },
242                    # "name" arg is a query label that appears in logs:
243                    "User.group_permissions",
244                    # "binds" arg is an array of [col_id, value] for '$1' vars:
245                    [uuid]).
246         rows.each do |group_uuid, max_p_val|
247         @group_perms[group_uuid] = PERMS_FOR_VAL[max_p_val.to_i]
248       end
249     end
250
251     case level
252     when 1
253       @group_perms
254     when 2
255       @group_perms.select {|k,v| v[:write] }
256     when 3
257       @group_perms.select {|k,v| v[:manage] }
258     else
259       raise "level must be 1, 2 or 3"
260     end
261   end
262
263   # create links
264   def setup(repo_name: nil, vm_uuid: nil, send_notification_email: nil)
265     newly_invited = Link.where(tail_uuid: self.uuid,
266                               head_uuid: all_users_group_uuid,
267                               link_class: 'permission').empty?
268
269     # Add can_read link from this user to "all users" which makes this
270     # user "invited", and (depending on config) a link in the opposite
271     # direction which makes this user visible to other users.
272     group_perms = add_to_all_users_group
273
274     # Add git repo
275     repo_perm = if (!repo_name.nil? || Rails.configuration.Users.AutoSetupNewUsersWithRepository) and !username.nil?
276                   repo_name ||= "#{username}/#{username}"
277                   create_user_repo_link repo_name
278                 end
279
280     # Add virtual machine
281     if vm_uuid.nil? and !Rails.configuration.Users.AutoSetupNewUsersWithVmUUID.empty?
282       vm_uuid = Rails.configuration.Users.AutoSetupNewUsersWithVmUUID
283     end
284
285     vm_login_perm = if vm_uuid && username
286                       create_vm_login_permission_link(vm_uuid, username)
287                     end
288
289     # Send welcome email
290     if send_notification_email.nil?
291       send_notification_email = Rails.configuration.Mail.SendUserSetupNotificationEmail
292     end
293
294     if newly_invited and send_notification_email and !Rails.configuration.Users.UserSetupMailText.empty?
295       begin
296         UserNotifier.account_is_setup(self).deliver_now
297       rescue => e
298         logger.warn "Failed to send email to #{self.email}: #{e}"
299       end
300     end
301
302     forget_cached_group_perms
303
304     return [repo_perm, vm_login_perm, *group_perms, self].compact
305   end
306
307   # delete user signatures, login, repo, and vm perms, and mark as inactive
308   def unsetup
309     if self.uuid == system_user_uuid
310       raise "System root user cannot be deactivated"
311     end
312
313     # delete oid_login_perms for this user
314     #
315     # note: these permission links are obsolete anyway: they have no
316     # effect on anything and they are not created for new users.
317     Link.where(tail_uuid: self.email,
318                link_class: 'permission',
319                name: 'can_login').destroy_all
320
321     # Delete all sharing permissions so (a) the user doesn't
322     # automatically regain access to anything if re-setup in future,
323     # (b) the user doesn't appear in "currently shared with" lists
324     # shown to other users.
325     #
326     # Notably this includes the can_read -> "all users" group
327     # permission.
328     Link.where(tail_uuid: self.uuid,
329                link_class: 'permission').destroy_all
330
331     # delete any signatures by this user
332     Link.where(link_class: 'signature',
333                tail_uuid: self.uuid).destroy_all
334
335     # delete tokens for this user
336     ApiClientAuthorization.where(user_id: self.id).destroy_all
337     # delete ssh keys for this user
338     AuthorizedKey.where(owner_uuid: self.uuid).destroy_all
339     AuthorizedKey.where(authorized_user_uuid: self.uuid).destroy_all
340
341     # delete user preferences (including profile)
342     self.prefs = {}
343
344     # mark the user as inactive
345     self.is_admin = false  # can't be admin and inactive
346     self.is_active = false
347     forget_cached_group_perms
348     self.save!
349   end
350
351   # Called from ArvadosModel
352   def set_default_owner
353     self.owner_uuid = system_user_uuid
354   end
355
356   def must_unsetup_to_deactivate
357     if !self.new_record? &&
358        self.uuid[0..4] == Rails.configuration.Login.LoginCluster &&
359        self.uuid[0..4] != Rails.configuration.ClusterID
360       # OK to update our local record to whatever the LoginCluster
361       # reports, because self-activate is not allowed.
362       return
363     elsif self.is_active_changed? &&
364        self.is_active_was &&
365        !self.is_active
366
367       # When a user is set up, they are added to the "All users"
368       # group.  A user that is part of the "All users" group is
369       # allowed to self-activate.
370       #
371       # It doesn't make sense to deactivate a user (set is_active =
372       # false) without first removing them from the "All users" group,
373       # because they would be able to immediately reactivate
374       # themselves.
375       #
376       # The 'unsetup' method removes the user from the "All users"
377       # group (and also sets is_active = false) so send a message
378       # explaining the correct way to deactivate a user.
379       #
380       if Link.where(tail_uuid: self.uuid,
381                     head_uuid: all_users_group_uuid,
382                     link_class: 'permission').any?
383         errors.add :is_active, "cannot be set to false directly, use the 'Deactivate' button on Workbench, or the 'unsetup' API call"
384       end
385     end
386   end
387
388   def set_initial_username(requested: false)
389     if new_record? and requested == false and self.username != nil and self.username != ""
390       requested = self.username
391     end
392
393     if (!requested.is_a?(String) || requested.empty?) and email
394       email_parts = email.partition("@")
395       local_parts = email_parts.first.partition("+")
396       if email_parts.any?(&:empty?)
397         return
398       elsif not local_parts.first.empty?
399         requested = local_parts.first
400       else
401         requested = email_parts.first
402       end
403     end
404     if requested
405       requested.sub!(/^[^A-Za-z]+/, "")
406       requested.gsub!(/[^A-Za-z0-9]/, "")
407     end
408     unless !requested || requested.empty?
409       self.username = find_usable_username_from(requested)
410     end
411   end
412
413   def active_is_not_nil
414     self.is_active = false if self.is_active.nil?
415     self.is_admin = false if self.is_admin.nil?
416   end
417
418   # Move this user's (i.e., self's) owned items to new_owner_uuid and
419   # new_user_uuid (for things normally owned directly by the user).
420   #
421   # If redirect_auth is true, also reassign auth tokens and ssh keys,
422   # and redirect this account to redirect_to_user_uuid, i.e., when a
423   # caller authenticates to this account in the future, the account
424   # redirect_to_user_uuid account will be used instead.
425   #
426   # current_user must have admin privileges, i.e., the caller is
427   # responsible for checking permission to do this.
428   def merge(new_owner_uuid:, new_user_uuid:, redirect_to_new_user:)
429     raise PermissionDeniedError if !current_user.andand.is_admin
430     raise "Missing new_owner_uuid" if !new_owner_uuid
431     raise "Missing new_user_uuid" if !new_user_uuid
432     transaction(requires_new: true) do
433       reload
434       raise "cannot merge an already merged user" if self.redirect_to_user_uuid
435
436       new_user = User.where(uuid: new_user_uuid).first
437       raise "user does not exist" if !new_user
438       raise "cannot merge to an already merged user" if new_user.redirect_to_user_uuid
439
440       self.clear_permissions
441       new_user.clear_permissions
442
443       # If 'self' is a remote user, don't transfer authorizations
444       # (i.e. ability to access the account) to the new user, because
445       # that gives the remote site the ability to access the 'new'
446       # user account that takes over the 'self' account.
447       #
448       # If 'self' is a local user, it is okay to transfer
449       # authorizations, even if the 'new' user is a remote account,
450       # because the remote site does not gain the ability to access an
451       # account it could not before.
452
453       if redirect_to_new_user and self.uuid[0..4] == Rails.configuration.ClusterID
454         # Existing API tokens and ssh keys are updated to authenticate
455         # to the new user.
456         ApiClientAuthorization.
457           where(user_id: id).
458           update_all(user_id: new_user.id)
459
460         user_updates = [
461           [AuthorizedKey, :owner_uuid],
462           [AuthorizedKey, :authorized_user_uuid],
463           [Link, :owner_uuid],
464           [Link, :tail_uuid],
465           [Link, :head_uuid],
466         ]
467       else
468         # Destroy API tokens and ssh keys associated with the old
469         # user.
470         ApiClientAuthorization.where(user_id: id).destroy_all
471         AuthorizedKey.where(owner_uuid: uuid).destroy_all
472         AuthorizedKey.where(authorized_user_uuid: uuid).destroy_all
473         user_updates = [
474           [Link, :owner_uuid],
475           [Link, :tail_uuid]
476         ]
477       end
478
479       # References to the old user UUID in the context of a user ID
480       # (rather than a "home project" in the project hierarchy) are
481       # updated to point to the new user.
482       user_updates.each do |klass, column|
483         klass.where(column => uuid).update_all(column => new_user.uuid)
484       end
485
486       # Need to update repository names to new username
487       if username
488         old_repo_name_re = /^#{Regexp.escape(username)}\//
489         Repository.where(:owner_uuid => uuid).each do |repo|
490           repo.owner_uuid = new_user.uuid
491           repo_name_sub = "#{new_user.username}/"
492           name = repo.name.sub(old_repo_name_re, repo_name_sub)
493           while (conflict = Repository.where(:name => name).first) != nil
494             repo_name_sub += "migrated"
495             name = repo.name.sub(old_repo_name_re, repo_name_sub)
496           end
497           repo.name = name
498           repo.save!
499         end
500       end
501
502       # References to the merged user's "home project" are updated to
503       # point to new_owner_uuid.
504       ActiveRecord::Base.descendants.reject(&:abstract_class?).each do |klass|
505         next if [ApiClientAuthorization,
506                  AuthorizedKey,
507                  Link,
508                  Log,
509                  Repository].include?(klass)
510         next if !klass.columns.collect(&:name).include?('owner_uuid')
511         klass.where(owner_uuid: uuid).update_all(owner_uuid: new_owner_uuid)
512       end
513
514       if redirect_to_new_user
515         update!(redirect_to_user_uuid: new_user.uuid, username: nil)
516       end
517       skip_check_permissions_against_full_refresh do
518         update_permissions self.uuid, self.uuid, CAN_MANAGE_PERM, nil, true
519         update_permissions new_user.uuid, new_user.uuid, CAN_MANAGE_PERM, nil, true
520         update_permissions new_user.owner_uuid, new_user.uuid, CAN_MANAGE_PERM, nil, true
521       end
522       update_permissions self.owner_uuid, self.uuid, CAN_MANAGE_PERM, nil, true
523     end
524   end
525
526   def redirects_to
527     user = self
528     redirects = 0
529     while (uuid = user.redirect_to_user_uuid)
530       break if uuid.empty?
531       nextuser = User.unscoped.find_by_uuid(uuid)
532       if !nextuser
533         raise Exception.new("user uuid #{user.uuid} redirects to nonexistent uuid '#{uuid}'")
534       end
535       user = nextuser
536       redirects += 1
537       if redirects > 15
538         raise "Starting from #{self.uuid} redirect_to_user_uuid exceeded maximum number of redirects"
539       end
540     end
541     user
542   end
543
544   def self.register info
545     # login info expected fields, all can be optional but at minimum
546     # must supply either 'identity_url' or 'email'
547     #
548     #   email
549     #   first_name
550     #   last_name
551     #   username
552     #   alternate_emails
553     #   identity_url
554
555     primary_user = nil
556
557     # local database
558     identity_url = info['identity_url']
559
560     if identity_url && identity_url.length > 0
561       # Only local users can create sessions, hence uuid_like_pattern
562       # here.
563       user = User.unscoped.where('identity_url = ? and uuid like ?',
564                                  identity_url,
565                                  User.uuid_like_pattern).first
566       primary_user = user.redirects_to if user
567     end
568
569     if !primary_user
570       # identity url is unset or didn't find matching record.
571       emails = [info['email']] + (info['alternate_emails'] || [])
572       emails.select! {|em| !em.nil? && !em.empty?}
573
574       User.unscoped.where('email in (?) and uuid like ?',
575                           emails,
576                           User.uuid_like_pattern).each do |user|
577         if !primary_user
578           primary_user = user.redirects_to
579         elsif primary_user.uuid != user.redirects_to.uuid
580           raise "Ambiguous email address, directs to both #{primary_user.uuid} and #{user.redirects_to.uuid}"
581         end
582       end
583     end
584
585     if !primary_user
586       # New user registration
587       primary_user = User.new(:owner_uuid => system_user_uuid,
588                               :is_admin => false,
589                               :is_active => Rails.configuration.Users.NewUsersAreActive)
590
591       primary_user.set_initial_username(requested: info['username']) if info['username'] && !info['username'].blank?
592       primary_user.identity_url = info['identity_url'] if identity_url
593     end
594
595     primary_user.email = info['email'] if info['email']
596     primary_user.first_name = info['first_name'] if info['first_name']
597     primary_user.last_name = info['last_name'] if info['last_name']
598
599     if (!primary_user.email or primary_user.email.empty?) and (!primary_user.identity_url or primary_user.identity_url.empty?)
600       raise "Must have supply at least one of 'email' or 'identity_url' to User.register"
601     end
602
603     act_as_system_user do
604       primary_user.save!
605     end
606
607     primary_user
608   end
609
610   def self.update_remote_user remote_user
611     remote_user = remote_user.symbolize_keys
612     remote_user_prefix = remote_user[:uuid][0..4]
613
614     # interaction between is_invited and is_active
615     #
616     # either can flag can be nil, true or false
617     #
618     # in all cases, we create the user if they don't exist.
619     #
620     # invited nil, active nil: don't call setup or unsetup.
621     #
622     # invited nil, active false: call unsetup
623     #
624     # invited nil, active true: call setup and activate them.
625     #
626     #
627     # invited false, active nil: call unsetup
628     #
629     # invited false, active false: call unsetup
630     #
631     # invited false, active true: call unsetup
632     #
633     #
634     # invited true, active nil: call setup but don't change is_active
635     #
636     # invited true, active false: call setup but don't change is_active
637     #
638     # invited true, active true: call setup and activate them.
639
640     should_setup = (remote_user_prefix == Rails.configuration.Login.LoginCluster or
641                     Rails.configuration.Users.AutoSetupNewUsers or
642                     Rails.configuration.Users.NewUsersAreActive or
643                     Rails.configuration.RemoteClusters[remote_user_prefix].andand["ActivateUsers"])
644
645     should_activate = (remote_user_prefix == Rails.configuration.Login.LoginCluster or
646                        Rails.configuration.Users.NewUsersAreActive or
647                        Rails.configuration.RemoteClusters[remote_user_prefix].andand["ActivateUsers"])
648
649     remote_should_be_unsetup = (remote_user[:is_invited] == nil && remote_user[:is_active] == false) ||
650                                (remote_user[:is_invited] == false)
651
652     remote_should_be_setup = should_setup && (
653       (remote_user[:is_invited] == nil && remote_user[:is_active] == true) ||
654       (remote_user[:is_invited] == false && remote_user[:is_active] == true) ||
655       (remote_user[:is_invited] == true))
656
657     remote_should_be_active = should_activate && remote_user[:is_invited] != false && remote_user[:is_active] == true
658
659     begin
660       user = User.create_with(email: remote_user[:email],
661                               username: remote_user[:username],
662                               first_name: remote_user[:first_name],
663                               last_name: remote_user[:last_name],
664                               is_active: remote_should_be_active
665       ).find_or_create_by(uuid: remote_user[:uuid])
666     rescue ActiveRecord::RecordNotUnique
667       retry
668     end
669
670     user.with_lock do
671       needupdate = {}
672       [:email, :username, :first_name, :last_name, :prefs].each do |k|
673         v = remote_user[k]
674         if !v.nil? && user.send(k) != v
675           needupdate[k] = v
676         end
677       end
678
679       user.email = needupdate[:email] if needupdate[:email]
680
681       loginCluster = Rails.configuration.Login.LoginCluster
682       if user.username.nil? || user.username == ""
683         # Don't have a username yet, set one
684         needupdate[:username] = user.set_initial_username(requested: remote_user[:username])
685       elsif remote_user_prefix != loginCluster
686         # Upstream is not login cluster, don't try to change the
687         # username once set.
688         needupdate.delete :username
689       end
690
691       if needupdate.length > 0
692         begin
693           user.update!(needupdate)
694         rescue ActiveRecord::RecordInvalid
695           if remote_user_prefix == loginCluster && !needupdate[:username].nil?
696             local_user = User.find_by_username(needupdate[:username])
697             # The username of this record conflicts with an existing,
698             # different user record.  This can happen because the
699             # username changed upstream on the login cluster, or
700             # because we're federated with another cluster with a user
701             # by the same username.  The login cluster is the source
702             # of truth, so change the username on the conflicting
703             # record and retry the update operation.
704             if local_user.uuid != user.uuid
705               new_username = "#{needupdate[:username]}#{rand(99999999)}"
706               Rails.logger.warn("cached username '#{needupdate[:username]}' collision with user '#{local_user.uuid}' - renaming to '#{new_username}' before retrying")
707               local_user.update!({username: new_username})
708               retry
709             end
710           end
711           raise # Not the issue we're handling above
712         end
713       end
714
715       if remote_should_be_unsetup
716         # Remote user is not "invited" or "active" state on their home
717         # cluster, so they should be unsetup, which also makes them
718         # inactive.
719         user.unsetup
720       else
721         if !user.is_invited && remote_should_be_setup
722           user.setup
723         end
724
725         if !user.is_active && remote_should_be_active
726           # remote user is active and invited, we need to activate them
727           user.update!(is_active: true)
728         end
729
730         if remote_user_prefix == Rails.configuration.Login.LoginCluster and
731           user.is_active and
732           !remote_user[:is_admin].nil? and
733           user.is_admin != remote_user[:is_admin]
734           # Remote cluster controls our user database, including the
735           # admin flag.
736           user.update!(is_admin: remote_user[:is_admin])
737         end
738       end
739     end
740     user
741   end
742
743   protected
744
745   def self.attributes_required_columns
746     super.merge(
747                 'can_write' => ['owner_uuid', 'uuid'],
748                 'can_manage' => ['owner_uuid', 'uuid'],
749                 )
750   end
751
752   def change_all_uuid_refs(old_uuid:, new_uuid:)
753     ActiveRecord::Base.descendants.reject(&:abstract_class?).each do |klass|
754       klass.columns.each do |col|
755         if col.name.end_with?('_uuid')
756           column = col.name.to_sym
757           klass.where(column => old_uuid).update_all(column => new_uuid)
758         end
759       end
760     end
761   end
762
763   def ensure_ownership_path_leads_to_user
764     true
765   end
766
767   def permission_to_update
768     if username_changed? || redirect_to_user_uuid_changed? || email_changed?
769       current_user.andand.is_admin
770     else
771       # users must be able to update themselves (even if they are
772       # inactive) in order to create sessions
773       self == current_user or super
774     end
775   end
776
777   def permission_to_create
778     current_user.andand.is_admin or
779       (self == current_user &&
780        self.redirect_to_user_uuid.nil? &&
781        self.is_active == Rails.configuration.Users.NewUsersAreActive)
782   end
783
784   def check_auto_admin
785     return if self.uuid.end_with?('anonymouspublic')
786     if (User.where("email = ?",self.email).where(:is_admin => true).count == 0 and
787         !Rails.configuration.Users.AutoAdminUserWithEmail.empty? and self.email == Rails.configuration.Users["AutoAdminUserWithEmail"]) or
788        (User.where("uuid not like '%-000000000000000'").where(:is_admin => true).count == 0 and
789         Rails.configuration.Users.AutoAdminFirstUser)
790       self.is_admin = true
791       self.is_active = true
792     end
793   end
794
795   def find_usable_username_from(basename)
796     # If "basename" is a usable username, return that.
797     # Otherwise, find a unique username "basenameN", where N is the
798     # smallest integer greater than 1, and return that.
799     # Return nil if a unique username can't be found after reasonable
800     # searching.
801     quoted_name = self.class.connection.quote_string(basename)
802     next_username = basename
803     next_suffix = 1
804     while Rails.configuration.Users.AutoSetupUsernameBlacklist[next_username]
805       next_suffix += 1
806       next_username = "%s%i" % [basename, next_suffix]
807     end
808     0.upto(6).each do |suffix_len|
809       pattern = "%s%s" % [quoted_name, "_" * suffix_len]
810       self.class.unscoped.
811           where("username like '#{pattern}'").
812           select(:username).
813           order('username asc').
814           each do |other_user|
815         if other_user.username > next_username
816           break
817         elsif other_user.username == next_username
818           next_suffix += 1
819           next_username = "%s%i" % [basename, next_suffix]
820         end
821       end
822       return next_username if (next_username.size <= pattern.size)
823     end
824     nil
825   end
826
827   def prevent_privilege_escalation
828     if current_user.andand.is_admin
829       return true
830     end
831     if self.is_active_changed?
832       if self.is_active != self.is_active_was
833         logger.warn "User #{current_user.uuid} tried to change is_active from #{self.is_active_was} to #{self.is_active} for #{self.uuid}"
834         self.is_active = self.is_active_was
835       end
836     end
837     if self.is_admin_changed?
838       if self.is_admin != self.is_admin_was
839         logger.warn "User #{current_user.uuid} tried to change is_admin from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
840         self.is_admin = self.is_admin_was
841       end
842     end
843     true
844   end
845
846   def prevent_inactive_admin
847     if self.is_admin and not self.is_active
848       # There is no known use case for the strange set of permissions
849       # that would result from this change. It's safest to assume it's
850       # a mistake and disallow it outright.
851       raise "Admin users cannot be inactive"
852     end
853     true
854   end
855
856   def prevent_nonadmin_system_root
857     if self.uuid == system_user_uuid and self.is_admin_changed? and !self.is_admin
858       raise "System root user cannot be non-admin"
859     end
860     true
861   end
862
863   def search_permissions(start, graph, merged={}, upstream_mask=nil, upstream_path={})
864     nextpaths = graph[start]
865     return merged if !nextpaths
866     return merged if upstream_path.has_key? start
867     upstream_path[start] = true
868     upstream_mask ||= ALL_PERMISSIONS
869     nextpaths.each do |head, mask|
870       merged[head] ||= {}
871       mask.each do |k,v|
872         merged[head][k] ||= v if upstream_mask[k]
873       end
874       search_permissions(head, graph, merged, upstream_mask.select { |k,v| v && merged[head][k] }, upstream_path)
875     end
876     upstream_path.delete start
877     merged
878   end
879
880   def create_user_repo_link(repo_name)
881     # repo_name is optional
882     if not repo_name
883       logger.warn ("Repository name not given for #{self.uuid}.")
884       return
885     end
886
887     repo = Repository.where(owner_uuid: uuid, name: repo_name).first_or_create!
888     logger.info { "repo uuid: " + repo[:uuid] }
889     repo_perm = Link.where(tail_uuid: uuid, head_uuid: repo.uuid,
890                            link_class: "permission",
891                            name: "can_manage").first_or_create!
892     logger.info { "repo permission: " + repo_perm[:uuid] }
893     return repo_perm
894   end
895
896   # create login permission for the given vm_uuid, if it does not already exist
897   def create_vm_login_permission_link(vm_uuid, repo_name)
898     # vm uuid is optional
899     return if vm_uuid == ""
900
901     vm = VirtualMachine.where(uuid: vm_uuid).first
902     if !vm
903       logger.warn "Could not find virtual machine for #{vm_uuid.inspect}"
904       raise "No vm found for #{vm_uuid}"
905     end
906
907     logger.info { "vm uuid: " + vm[:uuid] }
908     login_attrs = {
909       tail_uuid: uuid, head_uuid: vm.uuid,
910       link_class: "permission", name: "can_login",
911     }
912
913     login_perm = Link.
914       where(login_attrs).
915       select { |link| link.properties["username"] == repo_name }.
916       first
917
918     login_perm ||= Link.
919       create(login_attrs.merge(properties: {"username" => repo_name}))
920
921     logger.info { "login permission: " + login_perm[:uuid] }
922     login_perm
923   end
924
925   def add_to_all_users_group
926     resp = [Link.where(tail_uuid: self.uuid,
927                        head_uuid: all_users_group_uuid,
928                        link_class: 'permission',
929                        name: 'can_write').first ||
930             Link.create(tail_uuid: self.uuid,
931                         head_uuid: all_users_group_uuid,
932                         link_class: 'permission',
933                         name: 'can_write')]
934     if Rails.configuration.Users.ActivatedUsersAreVisibleToOthers
935       resp += [Link.where(tail_uuid: all_users_group_uuid,
936                           head_uuid: self.uuid,
937                           link_class: 'permission',
938                           name: 'can_read').first ||
939                Link.create(tail_uuid: all_users_group_uuid,
940                            head_uuid: self.uuid,
941                            link_class: 'permission',
942                            name: 'can_read')]
943     end
944     return resp
945   end
946
947   # Give the special "System group" permission to manage this user and
948   # all of this user's stuff.
949   def add_system_group_permission_link
950     return true if uuid == system_user_uuid
951     act_as_system_user do
952       Link.create(link_class: 'permission',
953                   name: 'can_manage',
954                   tail_uuid: system_group_uuid,
955                   head_uuid: self.uuid)
956     end
957   end
958
959   # Send admin notifications
960   def send_admin_notifications
961     if self.is_invited then
962       AdminNotifier.new_user(self).deliver_now
963     else
964       AdminNotifier.new_inactive_user(self).deliver_now
965     end
966   end
967
968   # Automatically setup if is_active flag turns on
969   def setup_on_activate
970     return if [system_user_uuid, anonymous_user_uuid].include?(self.uuid)
971     if is_active &&
972       (new_record? || saved_change_to_is_active? || will_save_change_to_is_active?)
973       setup
974     end
975   end
976
977   # Automatically setup new user during creation
978   def auto_setup_new_user
979     setup
980   end
981
982   # Send notification if the user saved profile for the first time
983   def send_profile_created_notification
984     if saved_change_to_prefs?
985       if prefs_before_last_save.andand.empty? || !prefs_before_last_save.andand['profile']
986         profile_notification_address = Rails.configuration.Users.UserProfileNotificationAddress
987         ProfileNotifier.profile_created(self, profile_notification_address).deliver_now if profile_notification_address and !profile_notification_address.empty?
988       end
989     end
990   end
991
992   def verify_repositories_empty
993     unless repositories.first.nil?
994       errors.add(:username, "can't be unset when the user owns repositories")
995       throw(:abort)
996     end
997   end
998
999   def sync_repository_names
1000     old_name_re = /^#{Regexp.escape(username_before_last_save)}\//
1001     name_sub = "#{username}/"
1002     repositories.find_each do |repo|
1003       repo.name = repo.name.sub(old_name_re, name_sub)
1004       repo.save!
1005     end
1006   end
1007
1008   def identity_url_nil_if_empty
1009     if identity_url == ""
1010       self.identity_url = nil
1011     end
1012   end
1013 end