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