1 require 'can_be_an_owner'
3 class User < ArvadosModel
6 include CommonApiTemplate
10 has_many :api_client_authorizations
13 with: /^[A-Za-z][A-Za-z0-9]*$/,
14 message: "must begin with a letter and contain only alphanumerics",
18 before_update :prevent_privilege_escalation
19 before_update :prevent_inactive_admin
20 before_create :check_auto_admin
21 before_create :set_initial_username, :if => Proc.new { |user|
22 user.username.nil? and user.email
24 after_create :add_system_group_permission_link
25 after_create :auto_setup_new_user, :if => Proc.new { |user|
26 Rails.configuration.auto_setup_new_users and
27 (user.uuid != system_user_uuid) and
28 (user.uuid != anonymous_user_uuid)
30 after_create :send_admin_notifications
31 after_update :send_profile_created_notification
33 has_many :authorized_keys, :foreign_key => :authorized_user_uuid, :primary_key => :uuid
35 api_accessible :user, extend: :common do |t|
49 ALL_PERMISSIONS = {read: true, write: true, manage: true}
52 "#{first_name} #{last_name}".strip
57 Rails.configuration.new_users_are_active ||
58 self.groups_i_can(:read).select { |x| x.match /-f+$/ }.first)
61 def groups_i_can(verb)
62 my_groups = self.group_permissions.select { |uuid, mask| mask[verb] }.keys
64 my_groups << anonymous_group_uuid
70 return true if is_admin
71 actions.each do |action, target|
73 if target.respond_to? :uuid
74 target_uuid = target.uuid
77 target = ArvadosModel.find_by_uuid(target_uuid)
80 next if target_uuid == self.uuid
81 next if (group_permissions[target_uuid] and
82 group_permissions[target_uuid][action])
83 if target.respond_to? :owner_uuid
84 next if target.owner_uuid == self.uuid
85 next if (group_permissions[target.owner_uuid] and
86 group_permissions[target.owner_uuid][action])
88 sufficient_perms = case action
92 ['can_manage', 'can_write']
94 ['can_manage', 'can_write', 'can_read']
96 # (Skip this kind of permission opportunity
97 # if action is an unknown permission type)
100 # Check permission links with head_uuid pointing directly at
101 # the target object. If target is a Group, this is redundant
102 # and will fail except [a] if permission caching is broken or
103 # [b] during a race condition, where a permission link has
105 if Link.where(link_class: 'permission',
106 name: sufficient_perms,
107 tail_uuid: groups_i_can(action) + [self.uuid],
108 head_uuid: target_uuid).any?
117 def self.invalidate_permissions_cache
118 Rails.cache.delete_matched(/^groups_for_user_/)
121 # Return a hash of {group_uuid: perm_hash} where perm_hash[:read]
122 # and perm_hash[:write] are true if this user can read and write
123 # objects owned by group_uuid.
125 # The permission graph is built by repeatedly enumerating all
126 # permission links reachable from self.uuid, and then calling
128 def group_permissions
129 Rails.cache.fetch "groups_for_user_#{self.uuid}" do
130 permissions_from = {}
131 todo = {self.uuid => true}
133 # Build the equivalence class of permissions starting with
134 # self.uuid. On each iteration of this loop, todo contains
135 # the next set of uuids in the permission equivalence class
138 lookup_uuids = todo.keys
139 lookup_uuids.each do |uuid| done[uuid] = true end
142 # include all groups owned by the current set of uuids.
143 Group.where('owner_uuid in (?)', lookup_uuids).each do |group|
144 newgroups << [group.owner_uuid, group.uuid, 'can_manage']
146 # add any permission links from the current lookup_uuids to a Group.
147 Link.where('link_class = ? and tail_uuid in (?) and ' \
148 '(head_uuid like ? or (name = ? and head_uuid like ?))',
151 Group.uuid_like_pattern,
153 User.uuid_like_pattern).each do |link|
154 newgroups << [link.tail_uuid, link.head_uuid, link.name]
156 newgroups.each do |tail_uuid, head_uuid, perm_name|
157 unless done.has_key? head_uuid
158 todo[head_uuid] = true
160 link_permissions = {}
163 link_permissions = {read:true}
165 link_permissions = {read:true,write:true}
167 link_permissions = ALL_PERMISSIONS
169 permissions_from[tail_uuid] ||= {}
170 permissions_from[tail_uuid][head_uuid] ||= {}
171 link_permissions.each do |k,v|
172 permissions_from[tail_uuid][head_uuid][k] ||= v
176 search_permissions(self.uuid, permissions_from)
180 def self.setup(user, openid_prefix, repo_name=nil, vm_uuid=nil)
181 return user.setup_repo_vm_links(repo_name, vm_uuid, openid_prefix)
185 def setup_repo_vm_links(repo_name, vm_uuid, openid_prefix)
186 oid_login_perm = create_oid_login_perm openid_prefix
187 repo_perm = create_user_repo_link repo_name
188 vm_login_perm = create_vm_login_permission_link vm_uuid, repo_name
189 group_perm = create_user_group_link
191 return [oid_login_perm, repo_perm, vm_login_perm, group_perm, self].compact
194 # delete user signatures, login, repo, and vm perms, and mark as inactive
196 # delete oid_login_perms for this user
197 Link.destroy_all(tail_uuid: self.email,
198 link_class: 'permission',
201 # delete repo_perms for this user
202 Link.destroy_all(tail_uuid: self.uuid,
203 link_class: 'permission',
206 # delete vm_login_perms for this user
207 Link.destroy_all(tail_uuid: self.uuid,
208 link_class: 'permission',
211 # delete "All users" group read permissions for this user
212 group = Group.where(name: 'All users').select do |g|
213 g[:uuid].match /-f+$/
215 Link.destroy_all(tail_uuid: self.uuid,
216 head_uuid: group[:uuid],
217 link_class: 'permission',
220 # delete any signatures by this user
221 Link.destroy_all(link_class: 'signature',
222 tail_uuid: self.uuid)
224 # delete user preferences (including profile)
227 # mark the user as inactive
228 self.is_active = false
234 def ensure_ownership_path_leads_to_user
238 def permission_to_update
240 current_user.andand.is_admin
242 # users must be able to update themselves (even if they are
243 # inactive) in order to create sessions
244 self == current_user or super
248 def permission_to_create
249 current_user.andand.is_admin or
250 (self == current_user and
251 self.is_active == Rails.configuration.new_users_are_active)
255 return if self.uuid.end_with?('anonymouspublic')
256 if (User.where("email = ?",self.email).where(:is_admin => true).count == 0 and
257 Rails.configuration.auto_admin_user and self.email == Rails.configuration.auto_admin_user) or
258 (User.where("uuid not like '%-000000000000000'").where(:is_admin => true).count == 0 and
259 Rails.configuration.auto_admin_first_user)
261 self.is_active = true
265 def find_usable_username_from(basename)
266 # If "basename" is a usable username, return that.
267 # Otherwise, find a unique username "basenameN", where N is the
268 # smallest integer greater than 1, and return that.
269 # Return nil if a unique username can't be found after reasonable
271 quoted_name = self.class.connection.quote_string(basename)
272 next_username = basename
274 while Rails.configuration.auto_setup_name_blacklist.include?(next_username)
276 next_username = "%s%i" % [basename, next_suffix]
278 0.upto(6).each do |suffix_len|
279 pattern = "%s%s" % [quoted_name, "_" * suffix_len]
281 where("username like '#{pattern}'").
283 order(username: :asc).
284 find_each do |other_user|
285 if other_user.username > next_username
287 elsif other_user.username == next_username
289 next_username = "%s%i" % [basename, next_suffix]
292 return next_username if (next_username.size <= pattern.size)
297 def set_initial_username
298 email_parts = email.partition("@")
299 local_parts = email_parts.first.partition("+")
300 if email_parts.any?(&:empty?)
302 elsif not local_parts.first.empty?
303 base_username = local_parts.first
305 base_username = email_parts.first
307 base_username.sub!(/^[^A-Za-z]+/, "")
308 base_username.gsub!(/[^A-Za-z0-9]/, "")
309 unless base_username.empty?
310 self.username = find_usable_username_from(base_username)
314 def prevent_privilege_escalation
315 if current_user.andand.is_admin
318 if self.is_active_changed?
319 if self.is_active != self.is_active_was
320 logger.warn "User #{current_user.uuid} tried to change is_active from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
321 self.is_active = self.is_active_was
324 if self.is_admin_changed?
325 if self.is_admin != self.is_admin_was
326 logger.warn "User #{current_user.uuid} tried to change is_admin from #{self.is_admin_was} to #{self.is_admin} for #{self.uuid}"
327 self.is_admin = self.is_admin_was
333 def prevent_inactive_admin
334 if self.is_admin and not self.is_active
335 # There is no known use case for the strange set of permissions
336 # that would result from this change. It's safest to assume it's
337 # a mistake and disallow it outright.
338 raise "Admin users cannot be inactive"
343 def search_permissions(start, graph, merged={}, upstream_mask=nil, upstream_path={})
344 nextpaths = graph[start]
345 return merged if !nextpaths
346 return merged if upstream_path.has_key? start
347 upstream_path[start] = true
348 upstream_mask ||= ALL_PERMISSIONS
349 nextpaths.each do |head, mask|
352 merged[head][k] ||= v if upstream_mask[k]
354 search_permissions(head, graph, merged, upstream_mask.select { |k,v| v && merged[head][k] }, upstream_path)
356 upstream_path.delete start
360 def create_oid_login_perm (openid_prefix)
361 login_perm_props = { "identity_url_prefix" => openid_prefix}
363 # Check oid_login_perm
364 oid_login_perms = Link.where(tail_uuid: self.email,
365 link_class: 'permission',
366 name: 'can_login').where("head_uuid = ?", self.uuid)
368 if !oid_login_perms.any?
369 # create openid login permission
370 oid_login_perm = Link.create(link_class: 'permission',
372 tail_uuid: self.email,
373 head_uuid: self.uuid,
374 properties: login_perm_props
376 logger.info { "openid login permission: " + oid_login_perm[:uuid] }
378 oid_login_perm = oid_login_perms.first
381 return oid_login_perm
384 def create_user_repo_link(repo_name)
385 # repo_name is optional
387 logger.warn ("Repository name not given for #{self.uuid}.")
391 repo = Repository.where(name: repo_name).first_or_create!
392 logger.info { "repo uuid: " + repo[:uuid] }
393 repo_perm = Link.where(tail_uuid: uuid, head_uuid: repo.uuid,
394 link_class: "permission",
395 name: "can_manage").first_or_create!
396 logger.info { "repo permission: " + repo_perm[:uuid] }
400 # create login permission for the given vm_uuid, if it does not already exist
401 def create_vm_login_permission_link(vm_uuid, repo_name)
402 # vm uuid is optional
404 vm = VirtualMachine.where(uuid: vm_uuid).first
407 logger.warn "Could not find virtual machine for #{vm_uuid.inspect}"
408 raise "No vm found for #{vm_uuid}"
414 logger.info { "vm uuid: " + vm[:uuid] }
416 tail_uuid: uuid, head_uuid: vm.uuid,
417 link_class: "permission", name: "can_login",
422 select { |link| link.properties["username"] == repo_name }.
426 create(login_attrs.merge(properties: {"username" => repo_name}))
428 logger.info { "login permission: " + login_perm[:uuid] }
432 # add the user to the 'All users' group
433 def create_user_group_link
434 return (Link.where(tail_uuid: self.uuid,
435 head_uuid: all_users_group[:uuid],
436 link_class: 'permission',
437 name: 'can_read').first or
438 Link.create(tail_uuid: self.uuid,
439 head_uuid: all_users_group[:uuid],
440 link_class: 'permission',
444 # Give the special "System group" permission to manage this user and
445 # all of this user's stuff.
446 def add_system_group_permission_link
447 return true if uuid == system_user_uuid
448 act_as_system_user do
449 Link.create(link_class: 'permission',
451 tail_uuid: system_group_uuid,
452 head_uuid: self.uuid)
456 # Send admin notifications
457 def send_admin_notifications
458 AdminNotifier.new_user(self).deliver
459 if not self.is_active then
460 AdminNotifier.new_inactive_user(self).deliver
464 # Automatically setup new user during creation
465 def auto_setup_new_user
466 setup_repo_vm_links(nil, nil, Rails.configuration.default_openid_prefix)
468 create_vm_login_permission_link(Rails.configuration.auto_setup_new_users_with_vm_uuid,
470 if Rails.configuration.auto_setup_new_users_with_repository and
471 Repository.where(name: username).first.nil?
472 repo = Repository.create!(name: username)
473 Link.create!(tail_uuid: uuid, head_uuid: repo.uuid,
474 link_class: "permission", name: "can_manage")
479 # Send notification if the user saved profile for the first time
480 def send_profile_created_notification
481 if self.prefs_changed?
482 if self.prefs_was.andand.empty? || !self.prefs_was.andand['profile']
483 profile_notification_address = Rails.configuration.user_profile_notification_address
484 ProfileNotifier.profile_created(self, profile_notification_address).deliver if profile_notification_address