16007: Account for all the edges. still wip.
[arvados.git] / services / api / app / models / user.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 require 'can_be_an_owner'
6
7 class User < ArvadosModel
8   include HasUuid
9   include KindAndEtag
10   include CommonApiTemplate
11   include CanBeAnOwner
12   extend CurrentApiClient
13
14   serialize :prefs, Hash
15   has_many :api_client_authorizations
16   validates(:username,
17             format: {
18               with: /\A[A-Za-z][A-Za-z0-9]*\z/,
19               message: "must begin with a letter and contain only alphanumerics",
20             },
21             uniqueness: true,
22             allow_nil: true)
23   validate :must_unsetup_to_deactivate
24   before_update :prevent_privilege_escalation
25   before_update :prevent_inactive_admin
26   before_update :verify_repositories_empty, :if => Proc.new { |user|
27     user.username.nil? and user.username_changed?
28   }
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
33   }
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)
41   }
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?)
49   }
50
51
52   has_many :authorized_keys, :foreign_key => :authorized_user_uuid, :primary_key => :uuid
53   has_many :repositories, foreign_key: :owner_uuid, primary_key: :uuid
54
55   default_scope { where('redirect_to_user_uuid is null') }
56
57   api_accessible :user, extend: :common do |t|
58     t.add :email
59     t.add :username
60     t.add :full_name
61     t.add :first_name
62     t.add :last_name
63     t.add :identity_url
64     t.add :is_active
65     t.add :is_admin
66     t.add :is_invited
67     t.add :prefs
68     t.add :writable_by
69   end
70
71   ALL_PERMISSIONS = {read: true, write: true, manage: true}
72
73   # Map numeric permission levels (see lib/create_permission_view.sql)
74   # back to read/write/manage flags.
75   PERMS_FOR_VAL =
76     [{},
77      {read: true},
78      {read: true, write: true},
79      {read: true, write: true, manage: true}]
80
81   VAL_FOR_PERM =
82     {:read => 1,
83      :write => 2,
84      :manage => 3}
85
86
87   def full_name
88     "#{first_name} #{last_name}".strip
89   end
90
91   def is_invited
92     !!(self.is_active ||
93        Rails.configuration.Users.NewUsersAreActive ||
94        self.groups_i_can(:read).select { |x| x.match(/-f+$/) }.first)
95   end
96
97   def groups_i_can(verb)
98     my_groups = self.group_permissions(VAL_FOR_PERM[verb]).keys
99     if verb == :read
100       my_groups << anonymous_group_uuid
101     end
102     my_groups
103   end
104
105   def can?(actions)
106     return true if is_admin
107     actions.each do |action, target|
108       unless target.nil?
109         if target.respond_to? :uuid
110           target_uuid = target.uuid
111         else
112           target_uuid = target
113           target = ArvadosModel.find_by_uuid(target_uuid)
114         end
115       end
116       next if target_uuid == self.uuid
117
118       target_owner_uuid = target.owner_uuid if target.respond_to? :owner_uuid
119
120       unless ActiveRecord::Base.connection.
121         exec_query(%{
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))
126 },
127                   # "name" arg is a query label that appears in logs:
128                    "user_can_query",
129                    [[nil, self.uuid],
130                     [nil, target_uuid],
131                     [nil, VAL_FOR_PERM[action]],
132                     [nil, target_owner_uuid]]
133                   ).any?
134         return false
135       end
136     end
137     true
138   end
139
140   def update_permissions
141
142 #       puts "Update permissions for #{uuid}"
143 #     User.printdump %{
144 # select * from materialized_permissions where user_uuid='#{uuid}'
145 # }
146 #     puts "---"
147     User.update_permissions self.owner_uuid, self.uuid, 3
148
149 #   puts "post-update"
150 #    User.printdump %{
151 # select * from materialized_permissions where user_uuid='#{uuid}'
152 # }
153 #    puts "<<<"
154   end
155
156   def self.printdump qr
157     q1 = ActiveRecord::Base.connection.exec_query qr
158     q1.each do |r|
159       puts r
160     end
161   end
162
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
169 }
170   end
171
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
176     #   can_read=1
177     #   can_write=2
178     #   can_manage=3
179     #   call with perm_level=0 to revoke permissions
180     #
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)
188
189     ## testinging
190     puts "\n__ update_permissions __"
191 #     puts "What's in there now for #{starting_uuid}"
192 #     printdump %{
193 # select * from materialized_permissions where user_uuid='#{starting_uuid}'
194 # }
195
196     puts "search_permission_graph #{perm_origin_uuid} #{starting_uuid}, #{perm_level}"
197     printdump %{
198 select '#{perm_origin_uuid}'::varchar as perm_origin_uuid, target_uuid, val, traverse_owned from search_permission_graph('#{starting_uuid}', #{perm_level})
199 }
200
201 #     puts "other_links #{perm_origin_uuid} #{starting_uuid}, #{perm_level}"
202 #     printdump %{
203 # with
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}))
207
208 #     select links.tail_uuid as perm_origin_uuid, links.head_uuid, links.name
209 #       from links
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)
214 # }
215
216     puts "additional_perms #{perm_origin_uuid} #{starting_uuid}, #{perm_level}"
217     printdump %{
218 with
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})),
222
223   edges(tail_uuid, head_uuid, val) as (
224         select * from permission_graph_edges()),
225
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)),
235
236   partial_perms(perm_origin_uuid, target_uuid, val, traverse_owned) as (
237       select * from perm_from_start
238     union
239       select * from additional_perms
240   ),
241
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)
247   ),
248
249   all_perms(perm_origin_uuid, target_uuid, val, traverse_owned) as (
250       select * from additional_perms
251     union
252       select * from user_identity_perms
253   )
254
255   select * from all_perms order by perm_origin_uuid, target_uuid
256 }
257
258     puts "Perms out"
259     printdump %{
260 select * from compute_permission_subgraph('#{perm_origin_uuid}', '#{starting_uuid}', '#{perm_level}')
261 order by user_uuid, target_uuid
262 }
263     ## end
264
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)
269 },
270                                              'Group.search_permissions',
271                                              [[nil, perm_origin_uuid],
272                                               [nil, starting_uuid],
273                                               [nil, perm_level]]
274
275 #     q1 = ActiveRecord::Base.connection.exec_query %{
276 # select * from #{temptable_perms} order by user_uuid, target_uuid
277 # }
278 #     puts "recomputed perms was #{perm_origin_uuid} #{starting_uuid}, #{perm_level}"
279 #     q1.each do |r|
280 #       puts r
281 #     end
282 #     puts "<<<<"
283
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))
289 }
290
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;
295 }
296
297     # for testing only - make a copy of the table and compare it to the one generated
298     # using a full permission recompute
299
300 #      puts "dump--"
301 #      User.printdump %{
302 #  select * from users
303 #      }
304 #      User.printdump %{
305 #  select * from groups
306 #      }
307 #      User.printdump %{
308 # select * from search_permission_graph('zzzzz-tpzed-000000000000000', 3)
309 #      }
310 #      puts "--"
311
312
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
316 }
317
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
322 }
323
324     if q1.count != q2.count
325       puts "Didn't match incremental+: #{q1.count} != full refresh-: #{q2.count}"
326     end
327
328     if q1.count > q2.count
329       q1.each_with_index do |r, i|
330         if r != q2[i]
331           puts "+#{r}\n-#{q2[i]}"
332           raise "Didn't match"
333         end
334       end
335     else
336       q2.each_with_index do |r, i|
337         if r != q1[i]
338           puts "+#{q1[i]}\n-#{r}"
339           raise "Didn't match"
340         end
341       end
342     end
343   end
344
345   # Return a hash of {user_uuid: group_perms}
346   def self.all_group_permissions
347     all_perms = {}
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]
357     end
358     all_perms
359   end
360
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)
365     group_perms = {}
366     ActiveRecord::Base.connection.
367       exec_query(%{
368 SELECT target_uuid, perm_level
369   FROM #{PERMISSION_VIEW}
370   WHERE user_uuid = $1 and perm_level >= $2
371 },
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:
375                   [[nil, uuid],
376                    [nil, level]]).
377       rows.each do |group_uuid, max_p_val|
378       group_perms[group_uuid] = PERMS_FOR_VAL[max_p_val.to_i]
379     end
380     group_perms
381   end
382
383   # create links
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
388
389     return [repo_perm, vm_login_perm, group_perm, self].compact
390   end
391
392   # delete user signatures, login, repo, and vm perms, and mark as inactive
393   def unsetup
394     # delete oid_login_perms for this user
395     #
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
401
402     # delete repo_perms for this user
403     Link.where(tail_uuid: self.uuid,
404                      link_class: 'permission',
405                      name: 'can_manage').destroy_all
406
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
411
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+$/)
415     end.first
416     Link.where(tail_uuid: self.uuid,
417                      head_uuid: group[:uuid],
418                      link_class: 'permission',
419                      name: 'can_read').destroy_all
420
421     # delete any signatures by this user
422     Link.where(link_class: 'signature',
423                      tail_uuid: self.uuid).destroy_all
424
425     # delete user preferences (including profile)
426     self.prefs = {}
427
428     # mark the user as inactive
429     self.is_active = false
430     self.save!
431   end
432
433   def must_unsetup_to_deactivate
434     if self.is_active_changed? &&
435        self.is_active_was == true &&
436        !self.is_active
437
438       group = Group.where(name: 'All users').select do |g|
439         g[:uuid].match(/-f+$/)
440       end.first
441
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.
445       #
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
449       # themselves.
450       #
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.
454       #
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"
460       end
461     end
462   end
463
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?)
469         return
470       elsif not local_parts.first.empty?
471         requested = local_parts.first
472       else
473         requested = email_parts.first
474       end
475     end
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)
480     end
481   end
482
483   def update_uuid(new_uuid:)
484     if !current_user.andand.is_admin
485       raise PermissionDeniedError
486     end
487     if uuid == system_user_uuid || uuid == anonymous_user_uuid
488       raise "update_uuid cannot update system accounts"
489     end
490     if self.class != self.class.resource_class_for_uuid(new_uuid)
491       raise "invalid new_uuid #{new_uuid.inspect}"
492     end
493     transaction(requires_new: true) do
494       reload
495       old_uuid = self.uuid
496       self.uuid = new_uuid
497       save!(validate: false)
498       change_all_uuid_refs(old_uuid: old_uuid, new_uuid: new_uuid)
499     end
500   end
501
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).
504   #
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.
509   #
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
517       reload
518       raise "cannot merge an already merged user" if self.redirect_to_user_uuid
519
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
523
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.
528       #
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.
533
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
536         # to the new user.
537         ApiClientAuthorization.
538           where(user_id: id).
539           update_all(user_id: new_user.id)
540
541         user_updates = [
542           [AuthorizedKey, :owner_uuid],
543           [AuthorizedKey, :authorized_user_uuid],
544           [Link, :owner_uuid],
545           [Link, :tail_uuid],
546           [Link, :head_uuid],
547         ]
548       else
549         # Destroy API tokens and ssh keys associated with the old
550         # user.
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
554         user_updates = [
555           [Link, :owner_uuid],
556           [Link, :tail_uuid]
557         ]
558       end
559
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)
565       end
566
567       # Need to update repository names to new username
568       if 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)
577           end
578           repo.name = name
579           repo.save!
580         end
581       end
582
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,
587                  AuthorizedKey,
588                  Link,
589                  Log,
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)
593       end
594
595       if redirect_to_new_user
596         update_attributes!(redirect_to_user_uuid: new_user.uuid, username: nil)
597       end
598       self.recompute_permissions
599       new_user.recompute_permissions
600     end
601   end
602
603   def redirects_to
604     user = self
605     redirects = 0
606     while (uuid = user.redirect_to_user_uuid)
607       break if uuid.empty?
608       nextuser = User.unscoped.find_by_uuid(uuid)
609       if !nextuser
610         raise Exception.new("user uuid #{user.uuid} redirects to nonexistent uuid '#{uuid}'")
611       end
612       user = nextuser
613       redirects += 1
614       if redirects > 15
615         raise "Starting from #{self.uuid} redirect_to_user_uuid exceeded maximum number of redirects"
616       end
617     end
618     user
619   end
620
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'
624     #
625     #   email
626     #   first_name
627     #   last_name
628     #   username
629     #   alternate_emails
630     #   identity_url
631
632     primary_user = nil
633
634     # local database
635     identity_url = info['identity_url']
636
637     if identity_url && identity_url.length > 0
638       # Only local users can create sessions, hence uuid_like_pattern
639       # here.
640       user = User.unscoped.where('identity_url = ? and uuid like ?',
641                                  identity_url,
642                                  User.uuid_like_pattern).first
643       primary_user = user.redirects_to if user
644     end
645
646     if !primary_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?}
650
651       User.unscoped.where('email in (?) and uuid like ?',
652                           emails,
653                           User.uuid_like_pattern).each do |user|
654         if !primary_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}"
658         end
659       end
660     end
661
662     if !primary_user
663       # New user registration
664       primary_user = User.new(:owner_uuid => system_user_uuid,
665                               :is_admin => false,
666                               :is_active => Rails.configuration.Users.NewUsersAreActive)
667
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
670     end
671
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']
675
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"
678     end
679
680     act_as_system_user do
681       primary_user.save!
682     end
683
684     primary_user
685   end
686
687   protected
688
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)
695         end
696       end
697     end
698   end
699
700   def ensure_ownership_path_leads_to_user
701     true
702   end
703
704   def permission_to_update
705     if username_changed? || redirect_to_user_uuid_changed? || email_changed?
706       current_user.andand.is_admin
707     else
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
711     end
712   end
713
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)
719   end
720
721   def check_auto_admin
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)
727       self.is_admin = true
728       self.is_active = true
729     end
730   end
731
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
737     # searching.
738     quoted_name = self.class.connection.quote_string(basename)
739     next_username = basename
740     next_suffix = 1
741     while Rails.configuration.Users.AutoSetupUsernameBlacklist[next_username]
742       next_suffix += 1
743       next_username = "%s%i" % [basename, next_suffix]
744     end
745     0.upto(6).each do |suffix_len|
746       pattern = "%s%s" % [quoted_name, "_" * suffix_len]
747       self.class.unscoped.
748           where("username like '#{pattern}'").
749           select(:username).
750           order('username asc').
751           each do |other_user|
752         if other_user.username > next_username
753           break
754         elsif other_user.username == next_username
755           next_suffix += 1
756           next_username = "%s%i" % [basename, next_suffix]
757         end
758       end
759       return next_username if (next_username.size <= pattern.size)
760     end
761     nil
762   end
763
764   def prevent_privilege_escalation
765     if current_user.andand.is_admin
766       return true
767     end
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
772       end
773     end
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
778       end
779     end
780     true
781   end
782
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"
789     end
790     true
791   end
792
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|
800       merged[head] ||= {}
801       mask.each do |k,v|
802         merged[head][k] ||= v if upstream_mask[k]
803       end
804       search_permissions(head, graph, merged, upstream_mask.select { |k,v| v && merged[head][k] }, upstream_path)
805     end
806     upstream_path.delete start
807     merged
808   end
809
810   def create_user_repo_link(repo_name)
811     # repo_name is optional
812     if not repo_name
813       logger.warn ("Repository name not given for #{self.uuid}.")
814       return
815     end
816
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] }
823     return repo_perm
824   end
825
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 == ""
830
831     vm = VirtualMachine.where(uuid: vm_uuid).first
832     if !vm
833       logger.warn "Could not find virtual machine for #{vm_uuid.inspect}"
834       raise "No vm found for #{vm_uuid}"
835     end
836
837     logger.info { "vm uuid: " + vm[:uuid] }
838     login_attrs = {
839       tail_uuid: uuid, head_uuid: vm.uuid,
840       link_class: "permission", name: "can_login",
841     }
842
843     login_perm = Link.
844       where(login_attrs).
845       select { |link| link.properties["username"] == repo_name }.
846       first
847
848     login_perm ||= Link.
849       create(login_attrs.merge(properties: {"username" => repo_name}))
850
851     logger.info { "login permission: " + login_perm[:uuid] }
852     login_perm
853   end
854
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',
865                         name: 'can_read'))
866   end
867
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',
874                   name: 'can_manage',
875                   tail_uuid: system_group_uuid,
876                   head_uuid: self.uuid)
877     end
878   end
879
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
885     end
886   end
887
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?)
892       setup
893     end
894   end
895
896   # Automatically setup new user during creation
897   def auto_setup_new_user
898     setup
899     if username
900       create_vm_login_permission_link(Rails.configuration.Users.AutoSetupNewUsersWithVmUUID,
901                                       username)
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")
908       end
909     end
910   end
911
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?
918       end
919     end
920   end
921
922   def verify_repositories_empty
923     unless repositories.first.nil?
924       errors.add(:username, "can't be unset when the user owns repositories")
925       throw(:abort)
926     end
927   end
928
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)
934       repo.save!
935     end
936   end
937 end