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