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