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