52b96f9c512699c8cc7f7f71b6bdd31804fd5902
[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 change_all_uuid_refs(old_uuid:, new_uuid:)
588     ActiveRecord::Base.descendants.reject(&:abstract_class?).each do |klass|
589       klass.columns.each do |col|
590         if col.name.end_with?('_uuid')
591           column = col.name.to_sym
592           klass.where(column => old_uuid).update_all(column => new_uuid)
593         end
594       end
595     end
596   end
597
598   def ensure_ownership_path_leads_to_user
599     true
600   end
601
602   def permission_to_update
603     if username_changed? || redirect_to_user_uuid_changed? || email_changed?
604       current_user.andand.is_admin
605     else
606       # users must be able to update themselves (even if they are
607       # inactive) in order to create sessions
608       self == current_user or super
609     end
610   end
611
612   def permission_to_create
613     current_user.andand.is_admin or
614       (self == current_user &&
615        self.redirect_to_user_uuid.nil? &&
616        self.is_active == Rails.configuration.Users.NewUsersAreActive)
617   end
618
619   def check_auto_admin
620     return if self.uuid.end_with?('anonymouspublic')
621     if (User.where("email = ?",self.email).where(:is_admin => true).count == 0 and
622         !Rails.configuration.Users.AutoAdminUserWithEmail.empty? and self.email == Rails.configuration.Users["AutoAdminUserWithEmail"]) or
623        (User.where("uuid not like '%-000000000000000'").where(:is_admin => true).count == 0 and
624         Rails.configuration.Users.AutoAdminFirstUser)
625       self.is_admin = true
626       self.is_active = true
627     end
628   end
629
630   def find_usable_username_from(basename)
631     # If "basename" is a usable username, return that.
632     # Otherwise, find a unique username "basenameN", where N is the
633     # smallest integer greater than 1, and return that.
634     # Return nil if a unique username can't be found after reasonable
635     # searching.
636     quoted_name = self.class.connection.quote_string(basename)
637     next_username = basename
638     next_suffix = 1
639     while Rails.configuration.Users.AutoSetupUsernameBlacklist[next_username]
640       next_suffix += 1
641       next_username = "%s%i" % [basename, next_suffix]
642     end
643     0.upto(6).each do |suffix_len|
644       pattern = "%s%s" % [quoted_name, "_" * suffix_len]
645       self.class.unscoped.
646           where("username like '#{pattern}'").
647           select(:username).
648           order('username asc').
649           each do |other_user|
650         if other_user.username > next_username
651           break
652         elsif other_user.username == next_username
653           next_suffix += 1
654           next_username = "%s%i" % [basename, next_suffix]
655         end
656       end
657       return next_username if (next_username.size <= pattern.size)
658     end
659     nil
660   end
661
662   def prevent_privilege_escalation
663     if current_user.andand.is_admin
664       return true
665     end
666     if self.is_active_changed?
667       if self.is_active != self.is_active_was
668         logger.warn "User #{current_user.uuid} tried to change is_active from #{self.is_active_was} to #{self.is_active} for #{self.uuid}"
669         self.is_active = self.is_active_was
670       end
671     end
672     if self.is_admin_changed?
673       if self.is_admin != self.is_admin_was
674         logger.warn "User #{current_user.uuid} tried to change is_admin from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
675         self.is_admin = self.is_admin_was
676       end
677     end
678     true
679   end
680
681   def prevent_inactive_admin
682     if self.is_admin and not self.is_active
683       # There is no known use case for the strange set of permissions
684       # that would result from this change. It's safest to assume it's
685       # a mistake and disallow it outright.
686       raise "Admin users cannot be inactive"
687     end
688     true
689   end
690
691   def search_permissions(start, graph, merged={}, upstream_mask=nil, upstream_path={})
692     nextpaths = graph[start]
693     return merged if !nextpaths
694     return merged if upstream_path.has_key? start
695     upstream_path[start] = true
696     upstream_mask ||= ALL_PERMISSIONS
697     nextpaths.each do |head, mask|
698       merged[head] ||= {}
699       mask.each do |k,v|
700         merged[head][k] ||= v if upstream_mask[k]
701       end
702       search_permissions(head, graph, merged, upstream_mask.select { |k,v| v && merged[head][k] }, upstream_path)
703     end
704     upstream_path.delete start
705     merged
706   end
707
708   def create_user_repo_link(repo_name)
709     # repo_name is optional
710     if not repo_name
711       logger.warn ("Repository name not given for #{self.uuid}.")
712       return
713     end
714
715     repo = Repository.where(owner_uuid: uuid, name: repo_name).first_or_create!
716     logger.info { "repo uuid: " + repo[:uuid] }
717     repo_perm = Link.where(tail_uuid: uuid, head_uuid: repo.uuid,
718                            link_class: "permission",
719                            name: "can_manage").first_or_create!
720     logger.info { "repo permission: " + repo_perm[:uuid] }
721     return repo_perm
722   end
723
724   # create login permission for the given vm_uuid, if it does not already exist
725   def create_vm_login_permission_link(vm_uuid, repo_name)
726     # vm uuid is optional
727     return if vm_uuid == ""
728
729     vm = VirtualMachine.where(uuid: vm_uuid).first
730     if !vm
731       logger.warn "Could not find virtual machine for #{vm_uuid.inspect}"
732       raise "No vm found for #{vm_uuid}"
733     end
734
735     logger.info { "vm uuid: " + vm[:uuid] }
736     login_attrs = {
737       tail_uuid: uuid, head_uuid: vm.uuid,
738       link_class: "permission", name: "can_login",
739     }
740
741     login_perm = Link.
742       where(login_attrs).
743       select { |link| link.properties["username"] == repo_name }.
744       first
745
746     login_perm ||= Link.
747       create(login_attrs.merge(properties: {"username" => repo_name}))
748
749     logger.info { "login permission: " + login_perm[:uuid] }
750     login_perm
751   end
752
753   def add_to_all_users_group
754     resp = [Link.where(tail_uuid: self.uuid,
755                        head_uuid: all_users_group_uuid,
756                        link_class: 'permission',
757                        name: 'can_read').first ||
758             Link.create(tail_uuid: self.uuid,
759                         head_uuid: all_users_group_uuid,
760                         link_class: 'permission',
761                         name: 'can_read')]
762     if Rails.configuration.Users.ActivatedUsersAreVisibleToOthers
763       resp += [Link.where(tail_uuid: all_users_group_uuid,
764                           head_uuid: self.uuid,
765                           link_class: 'permission',
766                           name: 'can_read').first ||
767                Link.create(tail_uuid: all_users_group_uuid,
768                            head_uuid: self.uuid,
769                            link_class: 'permission',
770                            name: 'can_read')]
771     end
772     return resp
773   end
774
775   # Give the special "System group" permission to manage this user and
776   # all of this user's stuff.
777   def add_system_group_permission_link
778     return true if uuid == system_user_uuid
779     act_as_system_user do
780       Link.create(link_class: 'permission',
781                   name: 'can_manage',
782                   tail_uuid: system_group_uuid,
783                   head_uuid: self.uuid)
784     end
785   end
786
787   # Send admin notifications
788   def send_admin_notifications
789     AdminNotifier.new_user(self).deliver_now
790     if not self.is_active then
791       AdminNotifier.new_inactive_user(self).deliver_now
792     end
793   end
794
795   # Automatically setup if is_active flag turns on
796   def setup_on_activate
797     return if [system_user_uuid, anonymous_user_uuid].include?(self.uuid)
798     if is_active &&
799       (new_record? || saved_change_to_is_active? || will_save_change_to_is_active?)
800       setup
801     end
802   end
803
804   # Automatically setup new user during creation
805   def auto_setup_new_user
806     setup
807   end
808
809   # Send notification if the user saved profile for the first time
810   def send_profile_created_notification
811     if saved_change_to_prefs?
812       if prefs_before_last_save.andand.empty? || !prefs_before_last_save.andand['profile']
813         profile_notification_address = Rails.configuration.Users.UserProfileNotificationAddress
814         ProfileNotifier.profile_created(self, profile_notification_address).deliver_now if profile_notification_address and !profile_notification_address.empty?
815       end
816     end
817   end
818
819   def verify_repositories_empty
820     unless repositories.first.nil?
821       errors.add(:username, "can't be unset when the user owns repositories")
822       throw(:abort)
823     end
824   end
825
826   def sync_repository_names
827     old_name_re = /^#{Regexp.escape(username_before_last_save)}\//
828     name_sub = "#{username}/"
829     repositories.find_each do |repo|
830       repo.name = repo.name.sub(old_name_re, name_sub)
831       repo.save!
832     end
833   end
834
835   def identity_url_nil_if_empty
836     if identity_url == ""
837       self.identity_url = nil
838     end
839   end
840 end