1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: AGPL-3.0
5 require 'can_be_an_owner'
7 class User < ArvadosModel
10 include CommonApiTemplate
12 extend CurrentApiClient
14 serialize :prefs, Hash
15 has_many :api_client_authorizations
18 with: /\A[A-Za-z][A-Za-z0-9]*\z/,
19 message: "must begin with a letter and contain only alphanumerics",
23 validate :must_unsetup_to_deactivate
24 before_update :prevent_privilege_escalation
25 before_update :prevent_inactive_admin
26 before_update :verify_repositories_empty, :if => Proc.new { |user|
27 user.username.nil? and user.username_changed?
29 before_update :setup_on_activate
30 before_create :check_auto_admin
31 before_create :set_initial_username, :if => Proc.new { |user|
32 user.username.nil? and user.email
34 after_create :update_permissions
35 after_create :setup_on_activate
36 after_create :add_system_group_permission_link
37 after_create :auto_setup_new_user, :if => Proc.new { |user|
38 Rails.configuration.Users.AutoSetupNewUsers and
39 (user.uuid != system_user_uuid) and
40 (user.uuid != anonymous_user_uuid)
42 after_create :send_admin_notifications
43 after_update :update_permissions, :if => :owner_uuid_changed?
44 after_update :send_profile_created_notification
45 after_update :sync_repository_names, :if => Proc.new { |user|
46 (user.uuid != system_user_uuid) and
47 user.username_changed? and
48 (not user.username_was.nil?)
52 has_many :authorized_keys, :foreign_key => :authorized_user_uuid, :primary_key => :uuid
53 has_many :repositories, foreign_key: :owner_uuid, primary_key: :uuid
55 default_scope { where('redirect_to_user_uuid is null') }
57 api_accessible :user, extend: :common do |t|
71 ALL_PERMISSIONS = {read: true, write: true, manage: true}
73 # Map numeric permission levels (see lib/create_permission_view.sql)
74 # back to read/write/manage flags.
78 {read: true, write: true},
79 {read: true, write: true, manage: true}]
88 "#{first_name} #{last_name}".strip
93 Rails.configuration.Users.NewUsersAreActive ||
94 self.groups_i_can(:read).select { |x| x.match(/-f+$/) }.first)
97 def groups_i_can(verb)
98 my_groups = self.group_permissions(VAL_FOR_PERM[verb]).keys
100 my_groups << anonymous_group_uuid
106 return true if is_admin
107 actions.each do |action, target|
109 if target.respond_to? :uuid
110 target_uuid = target.uuid
113 target = ArvadosModel.find_by_uuid(target_uuid)
116 next if target_uuid == self.uuid
118 target_owner_uuid = target.owner_uuid if target.respond_to? :owner_uuid
120 unless ActiveRecord::Base.connection.
122 SELECT 1 FROM #{PERMISSION_VIEW}
123 WHERE user_uuid = $1 and
124 ((target_uuid = $2 and perm_level >= $3)
125 or (target_uuid = $4 and perm_level >= $3 and traverse_owned))
127 # "name" arg is a query label that appears in logs:
131 [nil, VAL_FOR_PERM[action]],
132 [nil, target_owner_uuid]]
140 def update_permissions
142 # puts "Update permissions for #{uuid}"
144 # select * from materialized_permissions where user_uuid='#{uuid}'
147 User.update_permissions self.owner_uuid, self.uuid, 3
151 # select * from materialized_permissions where user_uuid='#{uuid}'
156 def self.printdump qr
157 q1 = ActiveRecord::Base.connection.exec_query qr
163 def recompute_permissions
164 ActiveRecord::Base.connection.execute("DELETE FROM #{PERMISSION_VIEW} where user_uuid='#{uuid}'")
165 ActiveRecord::Base.connection.execute %{
166 INSERT INTO #{PERMISSION_VIEW}
167 select '#{uuid}', g.target_uuid, g.val, g.traverse_owned
168 from search_permission_graph('#{uuid}', 3) as g
172 def self.update_permissions perm_origin_uuid, starting_uuid, perm_level
173 # Update a subset of the permission graph
174 # perm_level is the inherited permission
175 # perm_level is a number from 0-3
179 # call with perm_level=0 to revoke permissions
181 # 1. Compute set (group, permission) implied by traversing
182 # graph starting at this group
183 # 2. Find links from outside the graph that point inside
184 # 3. For each starting uuid, get the set of permissions from the
185 # materialized permission table
186 # 3. Delete permissions from table not in our computed subset.
187 # 4. Upsert each permission in our subset (user, group, val)
190 puts "\n__ update_permissions __"
191 # puts "What's in there now for #{starting_uuid}"
193 # select * from materialized_permissions where user_uuid='#{starting_uuid}'
196 puts "search_permission_graph #{perm_origin_uuid} #{starting_uuid}, #{perm_level}"
198 select '#{perm_origin_uuid}'::varchar as perm_origin_uuid, target_uuid, val, traverse_owned from search_permission_graph('#{starting_uuid}', #{perm_level})
201 # puts "other_links #{perm_origin_uuid} #{starting_uuid}, #{perm_level}"
204 # perm_from_start(perm_origin_uuid, target_uuid, val, traverse_owned) as (
205 # select '#{perm_origin_uuid}'::varchar, target_uuid, val, traverse_owned
206 # from search_permission_graph('#{starting_uuid}'::varchar, #{perm_level}))
208 # select links.tail_uuid as perm_origin_uuid, links.head_uuid, links.name
210 # where links.link_class='permission' and
211 # links.tail_uuid not in (select target_uuid from perm_from_start where traverse_owned) and
212 # links.tail_uuid != '#{perm_origin_uuid}' and
213 # links.head_uuid in (select target_uuid from perm_from_start)
216 puts "additional_perms #{perm_origin_uuid} #{starting_uuid}, #{perm_level}"
219 perm_from_start(perm_origin_uuid, target_uuid, val, traverse_owned) as (
220 select '#{perm_origin_uuid}'::varchar, target_uuid, val, traverse_owned
221 from search_permission_graph('#{starting_uuid}'::varchar, #{perm_level})),
223 edges(tail_uuid, head_uuid, val) as (
224 select * from permission_graph_edges()),
226 additional_perms(perm_origin_uuid, target_uuid, val, traverse_owned) as (
227 select edges.tail_uuid as perm_origin_uuid, ps.target_uuid, ps.val,
228 should_traverse_owned(ps.target_uuid, ps.val)
229 from edges, lateral search_permission_graph(edges.head_uuid, edges.val) as ps
230 where (not (edges.tail_uuid = '#{perm_origin_uuid}' and
231 edges.head_uuid = '#{starting_uuid}' and
232 edges.val = #{perm_level})) and
233 edges.tail_uuid not in (select target_uuid from perm_from_start) and
234 edges.head_uuid in (select target_uuid from perm_from_start)),
236 partial_perms(perm_origin_uuid, target_uuid, val, traverse_owned) as (
237 select * from perm_from_start
239 select * from additional_perms
242 user_identity_perms(perm_origin_uuid, target_uuid, val, traverse_owned) as (
243 select users.uuid as perm_origin_uuid, ps.target_uuid, ps.val, ps.traverse_owned
244 from users, lateral search_permission_graph(users.uuid, 3) as ps
245 where users.owner_uuid not in (select target_uuid from partial_perms where traverse_owned) and
246 users.uuid in (select target_uuid from partial_perms)
249 all_perms(perm_origin_uuid, target_uuid, val, traverse_owned) as (
250 select * from additional_perms
252 select * from user_identity_perms
255 select * from all_perms order by perm_origin_uuid, target_uuid
260 select * from compute_permission_subgraph('#{perm_origin_uuid}', '#{starting_uuid}', '#{perm_level}')
261 order by user_uuid, target_uuid
265 temptable_perms = "temp_perms_#{rand(2**64).to_s(10)}"
266 ActiveRecord::Base.connection.exec_query %{
267 create temporary table #{temptable_perms} on commit drop
268 as select * from compute_permission_subgraph($1, $2, $3)
270 'Group.search_permissions',
271 [[nil, perm_origin_uuid],
272 [nil, starting_uuid],
275 # q1 = ActiveRecord::Base.connection.exec_query %{
276 # select * from #{temptable_perms} order by user_uuid, target_uuid
278 # puts "recomputed perms was #{perm_origin_uuid} #{starting_uuid}, #{perm_level}"
284 ActiveRecord::Base.connection.exec_query %{
285 delete from materialized_permissions where
286 target_uuid in (select target_uuid from #{temptable_perms}) and
287 (user_uuid not in (select user_uuid from #{temptable_perms} where target_uuid=materialized_permissions.target_uuid)
288 or user_uuid in (select user_uuid from #{temptable_perms} where target_uuid=materialized_permissions.target_uuid and perm_level=0))
291 ActiveRecord::Base.connection.exec_query %{
292 insert into materialized_permissions (user_uuid, target_uuid, perm_level, traverse_owned)
293 select user_uuid, target_uuid, val as perm_level, traverse_owned from #{temptable_perms}
294 on conflict (user_uuid, target_uuid) do update set perm_level=EXCLUDED.perm_level, traverse_owned=EXCLUDED.traverse_owned;
297 # for testing only - make a copy of the table and compare it to the one generated
298 # using a full permission recompute
302 # select * from users
305 # select * from groups
308 # select * from search_permission_graph('zzzzz-tpzed-000000000000000', 3)
313 q1 = ActiveRecord::Base.connection.exec_query %{
314 select user_uuid, target_uuid, perm_level, traverse_owned from materialized_permissions
315 order by user_uuid, target_uuid
318 q2 = ActiveRecord::Base.connection.exec_query %{
319 select users.uuid as user_uuid, g.target_uuid, g.val as perm_level, g.traverse_owned
320 from users, lateral search_permission_graph(users.uuid, 3) as g where g.val > 0
321 order by users.uuid, target_uuid
324 if q1.count != q2.count
325 puts "Didn't match incremental+: #{q1.count} != full refresh-: #{q2.count}"
328 if q1.count > q2.count
329 q1.each_with_index do |r, i|
331 puts "+#{r}\n-#{q2[i]}"
336 q2.each_with_index do |r, i|
338 puts "+#{q1[i]}\n-#{r}"
345 # Return a hash of {user_uuid: group_perms}
346 def self.all_group_permissions
348 ActiveRecord::Base.connection.
349 exec_query("SELECT user_uuid, target_uuid, perm_level
350 FROM #{PERMISSION_VIEW}
351 WHERE traverse_owned",
352 # "name" arg is a query label that appears in logs:
353 "all_group_permissions").
354 rows.each do |user_uuid, group_uuid, max_p_val|
355 all_perms[user_uuid] ||= {}
356 all_perms[user_uuid][group_uuid] = PERMS_FOR_VAL[max_p_val.to_i]
361 # Return a hash of {group_uuid: perm_hash} where perm_hash[:read]
362 # and perm_hash[:write] are true if this user can read and write
363 # objects owned by group_uuid.
364 def group_permissions(level=1)
366 ActiveRecord::Base.connection.
368 SELECT target_uuid, perm_level
369 FROM #{PERMISSION_VIEW}
370 WHERE user_uuid = $1 and perm_level >= $2
372 # "name" arg is a query label that appears in logs:
373 "group_permissions_for_user",
374 # "binds" arg is an array of [col_id, value] for '$1' vars:
377 rows.each do |group_uuid, max_p_val|
378 group_perms[group_uuid] = PERMS_FOR_VAL[max_p_val.to_i]
384 def setup(repo_name: nil, vm_uuid: nil)
385 repo_perm = create_user_repo_link repo_name
386 vm_login_perm = create_vm_login_permission_link(vm_uuid, username) if vm_uuid
387 group_perm = create_user_group_link
389 return [repo_perm, vm_login_perm, group_perm, self].compact
392 # delete user signatures, login, repo, and vm perms, and mark as inactive
394 # delete oid_login_perms for this user
396 # note: these permission links are obsolete, they have no effect
397 # on anything and they are not created for new users.
398 Link.where(tail_uuid: self.email,
399 link_class: 'permission',
400 name: 'can_login').destroy_all
402 # delete repo_perms for this user
403 Link.where(tail_uuid: self.uuid,
404 link_class: 'permission',
405 name: 'can_manage').destroy_all
407 # delete vm_login_perms for this user
408 Link.where(tail_uuid: self.uuid,
409 link_class: 'permission',
410 name: 'can_login').destroy_all
412 # delete "All users" group read permissions for this user
413 group = Group.where(name: 'All users').select do |g|
414 g[:uuid].match(/-f+$/)
416 Link.where(tail_uuid: self.uuid,
417 head_uuid: group[:uuid],
418 link_class: 'permission',
419 name: 'can_read').destroy_all
421 # delete any signatures by this user
422 Link.where(link_class: 'signature',
423 tail_uuid: self.uuid).destroy_all
425 # delete user preferences (including profile)
428 # mark the user as inactive
429 self.is_active = false
433 def must_unsetup_to_deactivate
434 if self.is_active_changed? &&
435 self.is_active_was == true &&
438 group = Group.where(name: 'All users').select do |g|
439 g[:uuid].match(/-f+$/)
442 # When a user is set up, they are added to the "All users"
443 # group. A user that is part of the "All users" group is
444 # allowed to self-activate.
446 # It doesn't make sense to deactivate a user (set is_active =
447 # false) without first removing them from the "All users" group,
448 # because they would be able to immediately reactivate
451 # The 'unsetup' method removes the user from the "All users"
452 # group (and also sets is_active = false) so send a message
453 # explaining the correct way to deactivate a user.
455 if Link.where(tail_uuid: self.uuid,
456 head_uuid: group[:uuid],
457 link_class: 'permission',
458 name: 'can_read').any?
459 errors.add :is_active, "cannot be set to false directly, use the 'Deactivate' button on Workbench, or the 'unsetup' API call"
464 def set_initial_username(requested: false)
465 if !requested.is_a?(String) || requested.empty?
466 email_parts = email.partition("@")
467 local_parts = email_parts.first.partition("+")
468 if email_parts.any?(&:empty?)
470 elsif not local_parts.first.empty?
471 requested = local_parts.first
473 requested = email_parts.first
476 requested.sub!(/^[^A-Za-z]+/, "")
477 requested.gsub!(/[^A-Za-z0-9]/, "")
478 unless requested.empty?
479 self.username = find_usable_username_from(requested)
483 def update_uuid(new_uuid:)
484 if !current_user.andand.is_admin
485 raise PermissionDeniedError
487 if uuid == system_user_uuid || uuid == anonymous_user_uuid
488 raise "update_uuid cannot update system accounts"
490 if self.class != self.class.resource_class_for_uuid(new_uuid)
491 raise "invalid new_uuid #{new_uuid.inspect}"
493 transaction(requires_new: true) do
497 save!(validate: false)
498 change_all_uuid_refs(old_uuid: old_uuid, new_uuid: new_uuid)
502 # Move this user's (i.e., self's) owned items to new_owner_uuid and
503 # new_user_uuid (for things normally owned directly by the user).
505 # If redirect_auth is true, also reassign auth tokens and ssh keys,
506 # and redirect this account to redirect_to_user_uuid, i.e., when a
507 # caller authenticates to this account in the future, the account
508 # redirect_to_user_uuid account will be used instead.
510 # current_user must have admin privileges, i.e., the caller is
511 # responsible for checking permission to do this.
512 def merge(new_owner_uuid:, new_user_uuid:, redirect_to_new_user:)
513 raise PermissionDeniedError if !current_user.andand.is_admin
514 raise "Missing new_owner_uuid" if !new_owner_uuid
515 raise "Missing new_user_uuid" if !new_user_uuid
516 transaction(requires_new: true) do
518 raise "cannot merge an already merged user" if self.redirect_to_user_uuid
520 new_user = User.where(uuid: new_user_uuid).first
521 raise "user does not exist" if !new_user
522 raise "cannot merge to an already merged user" if new_user.redirect_to_user_uuid
524 # If 'self' is a remote user, don't transfer authorizations
525 # (i.e. ability to access the account) to the new user, because
526 # that gives the remote site the ability to access the 'new'
527 # user account that takes over the 'self' account.
529 # If 'self' is a local user, it is okay to transfer
530 # authorizations, even if the 'new' user is a remote account,
531 # because the remote site does not gain the ability to access an
532 # account it could not before.
534 if redirect_to_new_user and self.uuid[0..4] == Rails.configuration.ClusterID
535 # Existing API tokens and ssh keys are updated to authenticate
537 ApiClientAuthorization.
539 update_all(user_id: new_user.id)
542 [AuthorizedKey, :owner_uuid],
543 [AuthorizedKey, :authorized_user_uuid],
549 # Destroy API tokens and ssh keys associated with the old
551 ApiClientAuthorization.where(user_id: id).destroy_all
552 AuthorizedKey.where(owner_uuid: uuid).destroy_all
553 AuthorizedKey.where(authorized_user_uuid: uuid).destroy_all
560 # References to the old user UUID in the context of a user ID
561 # (rather than a "home project" in the project hierarchy) are
562 # updated to point to the new user.
563 user_updates.each do |klass, column|
564 klass.where(column => uuid).update_all(column => new_user.uuid)
567 # Need to update repository names to new username
569 old_repo_name_re = /^#{Regexp.escape(username)}\//
570 Repository.where(:owner_uuid => uuid).each do |repo|
571 repo.owner_uuid = new_user.uuid
572 repo_name_sub = "#{new_user.username}/"
573 name = repo.name.sub(old_repo_name_re, repo_name_sub)
574 while (conflict = Repository.where(:name => name).first) != nil
575 repo_name_sub += "migrated"
576 name = repo.name.sub(old_repo_name_re, repo_name_sub)
583 # References to the merged user's "home project" are updated to
584 # point to new_owner_uuid.
585 ActiveRecord::Base.descendants.reject(&:abstract_class?).each do |klass|
586 next if [ApiClientAuthorization,
590 Repository].include?(klass)
591 next if !klass.columns.collect(&:name).include?('owner_uuid')
592 klass.where(owner_uuid: uuid).update_all(owner_uuid: new_owner_uuid)
595 if redirect_to_new_user
596 update_attributes!(redirect_to_user_uuid: new_user.uuid, username: nil)
598 self.recompute_permissions
599 new_user.recompute_permissions
606 while (uuid = user.redirect_to_user_uuid)
608 nextuser = User.unscoped.find_by_uuid(uuid)
610 raise Exception.new("user uuid #{user.uuid} redirects to nonexistent uuid '#{uuid}'")
615 raise "Starting from #{self.uuid} redirect_to_user_uuid exceeded maximum number of redirects"
621 def self.register info
622 # login info expected fields, all can be optional but at minimum
623 # must supply either 'identity_url' or 'email'
635 identity_url = info['identity_url']
637 if identity_url && identity_url.length > 0
638 # Only local users can create sessions, hence uuid_like_pattern
640 user = User.unscoped.where('identity_url = ? and uuid like ?',
642 User.uuid_like_pattern).first
643 primary_user = user.redirects_to if user
647 # identity url is unset or didn't find matching record.
648 emails = [info['email']] + (info['alternate_emails'] || [])
649 emails.select! {|em| !em.nil? && !em.empty?}
651 User.unscoped.where('email in (?) and uuid like ?',
653 User.uuid_like_pattern).each do |user|
655 primary_user = user.redirects_to
656 elsif primary_user.uuid != user.redirects_to.uuid
657 raise "Ambiguous email address, directs to both #{primary_user.uuid} and #{user.redirects_to.uuid}"
663 # New user registration
664 primary_user = User.new(:owner_uuid => system_user_uuid,
666 :is_active => Rails.configuration.Users.NewUsersAreActive)
668 primary_user.set_initial_username(requested: info['username']) if info['username'] && !info['username'].blank?
669 primary_user.identity_url = info['identity_url'] if identity_url
672 primary_user.email = info['email'] if info['email']
673 primary_user.first_name = info['first_name'] if info['first_name']
674 primary_user.last_name = info['last_name'] if info['last_name']
676 if (!primary_user.email or primary_user.email.empty?) and (!primary_user.identity_url or primary_user.identity_url.empty?)
677 raise "Must have supply at least one of 'email' or 'identity_url' to User.register"
680 act_as_system_user do
689 def change_all_uuid_refs(old_uuid:, new_uuid:)
690 ActiveRecord::Base.descendants.reject(&:abstract_class?).each do |klass|
691 klass.columns.each do |col|
692 if col.name.end_with?('_uuid')
693 column = col.name.to_sym
694 klass.where(column => old_uuid).update_all(column => new_uuid)
700 def ensure_ownership_path_leads_to_user
704 def permission_to_update
705 if username_changed? || redirect_to_user_uuid_changed? || email_changed?
706 current_user.andand.is_admin
708 # users must be able to update themselves (even if they are
709 # inactive) in order to create sessions
710 self == current_user or super
714 def permission_to_create
715 current_user.andand.is_admin or
716 (self == current_user &&
717 self.redirect_to_user_uuid.nil? &&
718 self.is_active == Rails.configuration.Users.NewUsersAreActive)
722 return if self.uuid.end_with?('anonymouspublic')
723 if (User.where("email = ?",self.email).where(:is_admin => true).count == 0 and
724 !Rails.configuration.Users.AutoAdminUserWithEmail.empty? and self.email == Rails.configuration.Users["AutoAdminUserWithEmail"]) or
725 (User.where("uuid not like '%-000000000000000'").where(:is_admin => true).count == 0 and
726 Rails.configuration.Users.AutoAdminFirstUser)
728 self.is_active = true
732 def find_usable_username_from(basename)
733 # If "basename" is a usable username, return that.
734 # Otherwise, find a unique username "basenameN", where N is the
735 # smallest integer greater than 1, and return that.
736 # Return nil if a unique username can't be found after reasonable
738 quoted_name = self.class.connection.quote_string(basename)
739 next_username = basename
741 while Rails.configuration.Users.AutoSetupUsernameBlacklist[next_username]
743 next_username = "%s%i" % [basename, next_suffix]
745 0.upto(6).each do |suffix_len|
746 pattern = "%s%s" % [quoted_name, "_" * suffix_len]
748 where("username like '#{pattern}'").
750 order('username asc').
752 if other_user.username > next_username
754 elsif other_user.username == next_username
756 next_username = "%s%i" % [basename, next_suffix]
759 return next_username if (next_username.size <= pattern.size)
764 def prevent_privilege_escalation
765 if current_user.andand.is_admin
768 if self.is_active_changed?
769 if self.is_active != self.is_active_was
770 logger.warn "User #{current_user.uuid} tried to change is_active from #{self.is_active_was} to #{self.is_active} for #{self.uuid}"
771 self.is_active = self.is_active_was
774 if self.is_admin_changed?
775 if self.is_admin != self.is_admin_was
776 logger.warn "User #{current_user.uuid} tried to change is_admin from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
777 self.is_admin = self.is_admin_was
783 def prevent_inactive_admin
784 if self.is_admin and not self.is_active
785 # There is no known use case for the strange set of permissions
786 # that would result from this change. It's safest to assume it's
787 # a mistake and disallow it outright.
788 raise "Admin users cannot be inactive"
793 def search_permissions(start, graph, merged={}, upstream_mask=nil, upstream_path={})
794 nextpaths = graph[start]
795 return merged if !nextpaths
796 return merged if upstream_path.has_key? start
797 upstream_path[start] = true
798 upstream_mask ||= ALL_PERMISSIONS
799 nextpaths.each do |head, mask|
802 merged[head][k] ||= v if upstream_mask[k]
804 search_permissions(head, graph, merged, upstream_mask.select { |k,v| v && merged[head][k] }, upstream_path)
806 upstream_path.delete start
810 def create_user_repo_link(repo_name)
811 # repo_name is optional
813 logger.warn ("Repository name not given for #{self.uuid}.")
817 repo = Repository.where(owner_uuid: uuid, name: repo_name).first_or_create!
818 logger.info { "repo uuid: " + repo[:uuid] }
819 repo_perm = Link.where(tail_uuid: uuid, head_uuid: repo.uuid,
820 link_class: "permission",
821 name: "can_manage").first_or_create!
822 logger.info { "repo permission: " + repo_perm[:uuid] }
826 # create login permission for the given vm_uuid, if it does not already exist
827 def create_vm_login_permission_link(vm_uuid, repo_name)
828 # vm uuid is optional
829 return if vm_uuid == ""
831 vm = VirtualMachine.where(uuid: vm_uuid).first
833 logger.warn "Could not find virtual machine for #{vm_uuid.inspect}"
834 raise "No vm found for #{vm_uuid}"
837 logger.info { "vm uuid: " + vm[:uuid] }
839 tail_uuid: uuid, head_uuid: vm.uuid,
840 link_class: "permission", name: "can_login",
845 select { |link| link.properties["username"] == repo_name }.
849 create(login_attrs.merge(properties: {"username" => repo_name}))
851 logger.info { "login permission: " + login_perm[:uuid] }
855 # add the user to the 'All users' group
856 def create_user_group_link
857 #puts "In create_user_group_link"
858 return (Link.where(tail_uuid: self.uuid,
859 head_uuid: all_users_group[:uuid],
860 link_class: 'permission',
861 name: 'can_read').first or
862 Link.create(tail_uuid: self.uuid,
863 head_uuid: all_users_group[:uuid],
864 link_class: 'permission',
868 # Give the special "System group" permission to manage this user and
869 # all of this user's stuff.
870 def add_system_group_permission_link
871 return true if uuid == system_user_uuid
872 act_as_system_user do
873 Link.create(link_class: 'permission',
875 tail_uuid: system_group_uuid,
876 head_uuid: self.uuid)
880 # Send admin notifications
881 def send_admin_notifications
882 AdminNotifier.new_user(self).deliver_now
883 if not self.is_active then
884 AdminNotifier.new_inactive_user(self).deliver_now
888 # Automatically setup if is_active flag turns on
889 def setup_on_activate
890 return if [system_user_uuid, anonymous_user_uuid].include?(self.uuid)
891 if is_active && (new_record? || is_active_changed?)
896 # Automatically setup new user during creation
897 def auto_setup_new_user
900 create_vm_login_permission_link(Rails.configuration.Users.AutoSetupNewUsersWithVmUUID,
902 repo_name = "#{username}/#{username}"
903 if Rails.configuration.Users.AutoSetupNewUsersWithRepository and
904 Repository.where(name: repo_name).first.nil?
905 repo = Repository.create!(name: repo_name, owner_uuid: uuid)
906 Link.create!(tail_uuid: uuid, head_uuid: repo.uuid,
907 link_class: "permission", name: "can_manage")
912 # Send notification if the user saved profile for the first time
913 def send_profile_created_notification
914 if self.prefs_changed?
915 if self.prefs_was.andand.empty? || !self.prefs_was.andand['profile']
916 profile_notification_address = Rails.configuration.Users.UserProfileNotificationAddress
917 ProfileNotifier.profile_created(self, profile_notification_address).deliver_now if profile_notification_address and !profile_notification_address.empty?
922 def verify_repositories_empty
923 unless repositories.first.nil?
924 errors.add(:username, "can't be unset when the user owns repositories")
929 def sync_repository_names
930 old_name_re = /^#{Regexp.escape(username_was)}\//
931 name_sub = "#{username}/"
932 repositories.find_each do |repo|
933 repo.name = repo.name.sub(old_name_re, name_sub)