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