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