ba451eb1846b321598435aac82ca241d1fccbe59
[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(repo_name: nil, vm_uuid: nil)
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 [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     #
203     # note: these permission links are obsolete, they have no effect
204     # on anything and they are not created for new users.
205     Link.where(tail_uuid: self.email,
206                      link_class: 'permission',
207                      name: 'can_login').destroy_all
208
209     # delete repo_perms for this user
210     Link.where(tail_uuid: self.uuid,
211                      link_class: 'permission',
212                      name: 'can_manage').destroy_all
213
214     # delete vm_login_perms for this user
215     Link.where(tail_uuid: self.uuid,
216                      link_class: 'permission',
217                      name: 'can_login').destroy_all
218
219     # delete "All users" group read permissions for this user
220     group = Group.where(name: 'All users').select do |g|
221       g[:uuid].match(/-f+$/)
222     end.first
223     Link.where(tail_uuid: self.uuid,
224                      head_uuid: group[:uuid],
225                      link_class: 'permission',
226                      name: 'can_read').destroy_all
227
228     # delete any signatures by this user
229     Link.where(link_class: 'signature',
230                      tail_uuid: self.uuid).destroy_all
231
232     # delete user preferences (including profile)
233     self.prefs = {}
234
235     # mark the user as inactive
236     self.is_active = false
237     self.save!
238   end
239
240   def must_unsetup_to_deactivate
241     if self.is_active_changed? &&
242        self.is_active_was &&
243        !self.is_active &&
244        self.uuid[0..4] == Rails.configuration.ClusterID
245
246       group = Group.where(name: 'All users').select do |g|
247         g[:uuid].match(/-f+$/)
248       end.first
249
250       # When a user is set up, they are added to the "All users"
251       # group.  A user that is part of the "All users" group is
252       # allowed to self-activate.
253       #
254       # It doesn't make sense to deactivate a user (set is_active =
255       # false) without first removing them from the "All users" group,
256       # because they would be able to immediately reactivate
257       # themselves.
258       #
259       # The 'unsetup' method removes the user from the "All users"
260       # group (and also sets is_active = false) so send a message
261       # explaining the correct way to deactivate a user.
262       #
263       if Link.where(tail_uuid: self.uuid,
264                     head_uuid: group[:uuid],
265                     link_class: 'permission',
266                     name: 'can_read').any?
267         errors.add :is_active, "cannot be set to false directly, use the 'Deactivate' button on Workbench, or the 'unsetup' API call"
268       end
269     end
270   end
271
272   def set_initial_username(requested: false)
273     if !requested.is_a?(String) || requested.empty?
274       email_parts = email.partition("@")
275       local_parts = email_parts.first.partition("+")
276       if email_parts.any?(&:empty?)
277         return
278       elsif not local_parts.first.empty?
279         requested = local_parts.first
280       else
281         requested = email_parts.first
282       end
283     end
284     requested.sub!(/^[^A-Za-z]+/, "")
285     requested.gsub!(/[^A-Za-z0-9]/, "")
286     unless requested.empty?
287       self.username = find_usable_username_from(requested)
288     end
289   end
290
291   def update_uuid(new_uuid:)
292     if !current_user.andand.is_admin
293       raise PermissionDeniedError
294     end
295     if uuid == system_user_uuid || uuid == anonymous_user_uuid
296       raise "update_uuid cannot update system accounts"
297     end
298     if self.class != self.class.resource_class_for_uuid(new_uuid)
299       raise "invalid new_uuid #{new_uuid.inspect}"
300     end
301     transaction(requires_new: true) do
302       reload
303       old_uuid = self.uuid
304       self.uuid = new_uuid
305       save!(validate: false)
306       change_all_uuid_refs(old_uuid: old_uuid, new_uuid: new_uuid)
307     end
308   end
309
310   # Move this user's (i.e., self's) owned items to new_owner_uuid and
311   # new_user_uuid (for things normally owned directly by the user).
312   #
313   # If redirect_auth is true, also reassign auth tokens and ssh keys,
314   # and redirect this account to redirect_to_user_uuid, i.e., when a
315   # caller authenticates to this account in the future, the account
316   # redirect_to_user_uuid account will be used instead.
317   #
318   # current_user must have admin privileges, i.e., the caller is
319   # responsible for checking permission to do this.
320   def merge(new_owner_uuid:, new_user_uuid:, redirect_to_new_user:)
321     raise PermissionDeniedError if !current_user.andand.is_admin
322     raise "Missing new_owner_uuid" if !new_owner_uuid
323     raise "Missing new_user_uuid" if !new_user_uuid
324     transaction(requires_new: true) do
325       reload
326       raise "cannot merge an already merged user" if self.redirect_to_user_uuid
327
328       new_user = User.where(uuid: new_user_uuid).first
329       raise "user does not exist" if !new_user
330       raise "cannot merge to an already merged user" if new_user.redirect_to_user_uuid
331
332       # If 'self' is a remote user, don't transfer authorizations
333       # (i.e. ability to access the account) to the new user, because
334       # that gives the remote site the ability to access the 'new'
335       # user account that takes over the 'self' account.
336       #
337       # If 'self' is a local user, it is okay to transfer
338       # authorizations, even if the 'new' user is a remote account,
339       # because the remote site does not gain the ability to access an
340       # account it could not before.
341
342       if redirect_to_new_user and self.uuid[0..4] == Rails.configuration.ClusterID
343         # Existing API tokens and ssh keys are updated to authenticate
344         # to the new user.
345         ApiClientAuthorization.
346           where(user_id: id).
347           update_all(user_id: new_user.id)
348
349         user_updates = [
350           [AuthorizedKey, :owner_uuid],
351           [AuthorizedKey, :authorized_user_uuid],
352           [Link, :owner_uuid],
353           [Link, :tail_uuid],
354           [Link, :head_uuid],
355         ]
356       else
357         # Destroy API tokens and ssh keys associated with the old
358         # user.
359         ApiClientAuthorization.where(user_id: id).destroy_all
360         AuthorizedKey.where(owner_uuid: uuid).destroy_all
361         AuthorizedKey.where(authorized_user_uuid: uuid).destroy_all
362         user_updates = [
363           [Link, :owner_uuid],
364           [Link, :tail_uuid]
365         ]
366       end
367
368       # References to the old user UUID in the context of a user ID
369       # (rather than a "home project" in the project hierarchy) are
370       # updated to point to the new user.
371       user_updates.each do |klass, column|
372         klass.where(column => uuid).update_all(column => new_user.uuid)
373       end
374
375       # Need to update repository names to new username
376       if username
377         old_repo_name_re = /^#{Regexp.escape(username)}\//
378         Repository.where(:owner_uuid => uuid).each do |repo|
379           repo.owner_uuid = new_user.uuid
380           repo_name_sub = "#{new_user.username}/"
381           name = repo.name.sub(old_repo_name_re, repo_name_sub)
382           while (conflict = Repository.where(:name => name).first) != nil
383             repo_name_sub += "migrated"
384             name = repo.name.sub(old_repo_name_re, repo_name_sub)
385           end
386           repo.name = name
387           repo.save!
388         end
389       end
390
391       # References to the merged user's "home project" are updated to
392       # point to new_owner_uuid.
393       ActiveRecord::Base.descendants.reject(&:abstract_class?).each do |klass|
394         next if [ApiClientAuthorization,
395                  AuthorizedKey,
396                  Link,
397                  Log,
398                  Repository].include?(klass)
399         next if !klass.columns.collect(&:name).include?('owner_uuid')
400         klass.where(owner_uuid: uuid).update_all(owner_uuid: new_owner_uuid)
401       end
402
403       if redirect_to_new_user
404         update_attributes!(redirect_to_user_uuid: new_user.uuid, username: nil)
405       end
406       invalidate_permissions_cache
407     end
408   end
409
410   def redirects_to
411     user = self
412     redirects = 0
413     while (uuid = user.redirect_to_user_uuid)
414       break if uuid.empty?
415       nextuser = User.unscoped.find_by_uuid(uuid)
416       if !nextuser
417         raise Exception.new("user uuid #{user.uuid} redirects to nonexistent uuid '#{uuid}'")
418       end
419       user = nextuser
420       redirects += 1
421       if redirects > 15
422         raise "Starting from #{self.uuid} redirect_to_user_uuid exceeded maximum number of redirects"
423       end
424     end
425     user
426   end
427
428   def self.register info
429     # login info expected fields, all can be optional but at minimum
430     # must supply either 'identity_url' or 'email'
431     #
432     #   email
433     #   first_name
434     #   last_name
435     #   username
436     #   alternate_emails
437     #   identity_url
438
439     primary_user = nil
440
441     # local database
442     identity_url = info['identity_url']
443
444     if identity_url && identity_url.length > 0
445       # Only local users can create sessions, hence uuid_like_pattern
446       # here.
447       user = User.unscoped.where('identity_url = ? and uuid like ?',
448                                  identity_url,
449                                  User.uuid_like_pattern).first
450       primary_user = user.redirects_to if user
451     end
452
453     if !primary_user
454       # identity url is unset or didn't find matching record.
455       emails = [info['email']] + (info['alternate_emails'] || [])
456       emails.select! {|em| !em.nil? && !em.empty?}
457
458       User.unscoped.where('email in (?) and uuid like ?',
459                           emails,
460                           User.uuid_like_pattern).each do |user|
461         if !primary_user
462           primary_user = user.redirects_to
463         elsif primary_user.uuid != user.redirects_to.uuid
464           raise "Ambiguous email address, directs to both #{primary_user.uuid} and #{user.redirects_to.uuid}"
465         end
466       end
467     end
468
469     if !primary_user
470       # New user registration
471       primary_user = User.new(:owner_uuid => system_user_uuid,
472                               :is_admin => false,
473                               :is_active => Rails.configuration.Users.NewUsersAreActive)
474
475       primary_user.set_initial_username(requested: info['username']) if info['username'] && !info['username'].blank?
476       primary_user.identity_url = info['identity_url'] if identity_url
477     end
478
479     primary_user.email = info['email'] if info['email']
480     primary_user.first_name = info['first_name'] if info['first_name']
481     primary_user.last_name = info['last_name'] if info['last_name']
482
483     if (!primary_user.email or primary_user.email.empty?) and (!primary_user.identity_url or primary_user.identity_url.empty?)
484       raise "Must have supply at least one of 'email' or 'identity_url' to User.register"
485     end
486
487     act_as_system_user do
488       primary_user.save!
489     end
490
491     primary_user
492   end
493
494   protected
495
496   def change_all_uuid_refs(old_uuid:, new_uuid:)
497     ActiveRecord::Base.descendants.reject(&:abstract_class?).each do |klass|
498       klass.columns.each do |col|
499         if col.name.end_with?('_uuid')
500           column = col.name.to_sym
501           klass.where(column => old_uuid).update_all(column => new_uuid)
502         end
503       end
504     end
505   end
506
507   def ensure_ownership_path_leads_to_user
508     true
509   end
510
511   def permission_to_update
512     if username_changed? || redirect_to_user_uuid_changed? || email_changed?
513       current_user.andand.is_admin
514     else
515       # users must be able to update themselves (even if they are
516       # inactive) in order to create sessions
517       self == current_user or super
518     end
519   end
520
521   def permission_to_create
522     current_user.andand.is_admin or
523       (self == current_user &&
524        self.redirect_to_user_uuid.nil? &&
525        self.is_active == Rails.configuration.Users.NewUsersAreActive)
526   end
527
528   def check_auto_admin
529     return if self.uuid.end_with?('anonymouspublic')
530     if (User.where("email = ?",self.email).where(:is_admin => true).count == 0 and
531         !Rails.configuration.Users.AutoAdminUserWithEmail.empty? and self.email == Rails.configuration.Users["AutoAdminUserWithEmail"]) or
532        (User.where("uuid not like '%-000000000000000'").where(:is_admin => true).count == 0 and
533         Rails.configuration.Users.AutoAdminFirstUser)
534       self.is_admin = true
535       self.is_active = true
536     end
537   end
538
539   def find_usable_username_from(basename)
540     # If "basename" is a usable username, return that.
541     # Otherwise, find a unique username "basenameN", where N is the
542     # smallest integer greater than 1, and return that.
543     # Return nil if a unique username can't be found after reasonable
544     # searching.
545     quoted_name = self.class.connection.quote_string(basename)
546     next_username = basename
547     next_suffix = 1
548     while Rails.configuration.Users.AutoSetupUsernameBlacklist[next_username]
549       next_suffix += 1
550       next_username = "%s%i" % [basename, next_suffix]
551     end
552     0.upto(6).each do |suffix_len|
553       pattern = "%s%s" % [quoted_name, "_" * suffix_len]
554       self.class.unscoped.
555           where("username like '#{pattern}'").
556           select(:username).
557           order('username asc').
558           each do |other_user|
559         if other_user.username > next_username
560           break
561         elsif other_user.username == next_username
562           next_suffix += 1
563           next_username = "%s%i" % [basename, next_suffix]
564         end
565       end
566       return next_username if (next_username.size <= pattern.size)
567     end
568     nil
569   end
570
571   def prevent_privilege_escalation
572     if current_user.andand.is_admin
573       return true
574     end
575     if self.is_active_changed?
576       if self.is_active != self.is_active_was
577         logger.warn "User #{current_user.uuid} tried to change is_active from #{self.is_active_was} to #{self.is_active} for #{self.uuid}"
578         self.is_active = self.is_active_was
579       end
580     end
581     if self.is_admin_changed?
582       if self.is_admin != self.is_admin_was
583         logger.warn "User #{current_user.uuid} tried to change is_admin from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
584         self.is_admin = self.is_admin_was
585       end
586     end
587     true
588   end
589
590   def prevent_inactive_admin
591     if self.is_admin and not self.is_active
592       # There is no known use case for the strange set of permissions
593       # that would result from this change. It's safest to assume it's
594       # a mistake and disallow it outright.
595       raise "Admin users cannot be inactive"
596     end
597     true
598   end
599
600   def search_permissions(start, graph, merged={}, upstream_mask=nil, upstream_path={})
601     nextpaths = graph[start]
602     return merged if !nextpaths
603     return merged if upstream_path.has_key? start
604     upstream_path[start] = true
605     upstream_mask ||= ALL_PERMISSIONS
606     nextpaths.each do |head, mask|
607       merged[head] ||= {}
608       mask.each do |k,v|
609         merged[head][k] ||= v if upstream_mask[k]
610       end
611       search_permissions(head, graph, merged, upstream_mask.select { |k,v| v && merged[head][k] }, upstream_path)
612     end
613     upstream_path.delete start
614     merged
615   end
616
617   def create_user_repo_link(repo_name)
618     # repo_name is optional
619     if not repo_name
620       logger.warn ("Repository name not given for #{self.uuid}.")
621       return
622     end
623
624     repo = Repository.where(owner_uuid: uuid, name: repo_name).first_or_create!
625     logger.info { "repo uuid: " + repo[:uuid] }
626     repo_perm = Link.where(tail_uuid: uuid, head_uuid: repo.uuid,
627                            link_class: "permission",
628                            name: "can_manage").first_or_create!
629     logger.info { "repo permission: " + repo_perm[:uuid] }
630     return repo_perm
631   end
632
633   # create login permission for the given vm_uuid, if it does not already exist
634   def create_vm_login_permission_link(vm_uuid, repo_name)
635     # vm uuid is optional
636     return if vm_uuid == ""
637
638     vm = VirtualMachine.where(uuid: vm_uuid).first
639     if !vm
640       logger.warn "Could not find virtual machine for #{vm_uuid.inspect}"
641       raise "No vm found for #{vm_uuid}"
642     end
643
644     logger.info { "vm uuid: " + vm[:uuid] }
645     login_attrs = {
646       tail_uuid: uuid, head_uuid: vm.uuid,
647       link_class: "permission", name: "can_login",
648     }
649
650     login_perm = Link.
651       where(login_attrs).
652       select { |link| link.properties["username"] == repo_name }.
653       first
654
655     login_perm ||= Link.
656       create(login_attrs.merge(properties: {"username" => repo_name}))
657
658     logger.info { "login permission: " + login_perm[:uuid] }
659     login_perm
660   end
661
662   # add the user to the 'All users' group
663   def create_user_group_link
664     return (Link.where(tail_uuid: self.uuid,
665                        head_uuid: all_users_group[:uuid],
666                        link_class: 'permission',
667                        name: 'can_read').first or
668             Link.create(tail_uuid: self.uuid,
669                         head_uuid: all_users_group[:uuid],
670                         link_class: 'permission',
671                         name: 'can_read'))
672   end
673
674   # Give the special "System group" permission to manage this user and
675   # all of this user's stuff.
676   def add_system_group_permission_link
677     return true if uuid == system_user_uuid
678     act_as_system_user do
679       Link.create(link_class: 'permission',
680                   name: 'can_manage',
681                   tail_uuid: system_group_uuid,
682                   head_uuid: self.uuid)
683     end
684   end
685
686   # Send admin notifications
687   def send_admin_notifications
688     AdminNotifier.new_user(self).deliver_now
689     if not self.is_active then
690       AdminNotifier.new_inactive_user(self).deliver_now
691     end
692   end
693
694   # Automatically setup if is_active flag turns on
695   def setup_on_activate
696     return if [system_user_uuid, anonymous_user_uuid].include?(self.uuid)
697     if is_active && (new_record? || is_active_changed?)
698       setup
699     end
700   end
701
702   # Automatically setup new user during creation
703   def auto_setup_new_user
704     setup
705     if username
706       create_vm_login_permission_link(Rails.configuration.Users.AutoSetupNewUsersWithVmUUID,
707                                       username)
708       repo_name = "#{username}/#{username}"
709       if Rails.configuration.Users.AutoSetupNewUsersWithRepository and
710           Repository.where(name: repo_name).first.nil?
711         repo = Repository.create!(name: repo_name, owner_uuid: uuid)
712         Link.create!(tail_uuid: uuid, head_uuid: repo.uuid,
713                      link_class: "permission", name: "can_manage")
714       end
715     end
716   end
717
718   # Send notification if the user saved profile for the first time
719   def send_profile_created_notification
720     if self.prefs_changed?
721       if self.prefs_was.andand.empty? || !self.prefs_was.andand['profile']
722         profile_notification_address = Rails.configuration.Users.UserProfileNotificationAddress
723         ProfileNotifier.profile_created(self, profile_notification_address).deliver_now if profile_notification_address and !profile_notification_address.empty?
724       end
725     end
726   end
727
728   def verify_repositories_empty
729     unless repositories.first.nil?
730       errors.add(:username, "can't be unset when the user owns repositories")
731       throw(:abort)
732     end
733   end
734
735   def sync_repository_names
736     old_name_re = /^#{Regexp.escape(username_was)}\//
737     name_sub = "#{username}/"
738     repositories.find_each do |repo|
739       repo.name = repo.name.sub(old_name_re, name_sub)
740       repo.save!
741     end
742   end
743 end