Fix 2.4.2 upgrade notes formatting refs #19330
[arvados.git] / apps / workbench / app / controllers / users_controller.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 class UsersController < ApplicationController
6   skip_around_action :require_thread_api_token, only: :welcome
7   skip_before_action :check_user_agreements, only: [:welcome, :inactive, :link_account, :merge]
8   skip_before_action :check_user_profile, only: [:welcome, :inactive, :profile, :link_account, :merge]
9   skip_before_action :find_object_by_uuid, only: [:welcome, :activity, :storage]
10   before_action :ensure_current_user_is_admin, only: [:sudo, :unsetup, :setup]
11
12   def show
13     if params[:uuid] == current_user.uuid
14       respond_to do |f|
15         f.html do
16           if request.url.include?("/users/#{current_user.uuid}")
17             super
18           else
19             redirect_to(params[:return_to] || project_path(params[:uuid]))
20           end
21         end
22       end
23     else
24       super
25     end
26   end
27
28   def welcome
29     if current_user
30       redirect_to (params[:return_to] || '/')
31     end
32   end
33
34   def inactive
35     if current_user.andand.is_invited
36       redirect_to (params[:return_to] || '/')
37     end
38   end
39
40   def profile
41     params[:offer_return_to] ||= params[:return_to]
42
43     # In a federation situation, when you get a user record using
44     # "current user of token" it can fetch a stale user record from
45     # the local cluster. So even if profile settings were just written
46     # to the user record on the login cluster (because the user just
47     # filled out the profile), those profile settings may not appear
48     # in the "current user" response because it is returning a cached
49     # record from the local cluster.
50     #
51     # In this case, explicitly fetching user record forces it to get a
52     # fresh record from the login cluster.
53     Thread.current[:user] = User.find(current_user.uuid)
54   end
55
56   def activity
57     @breadcrumb_page_name = nil
58     @users = User.limit(params[:limit]).with_count("none")
59     @user_activity = {}
60     @activity = {
61       logins: {},
62       jobs: {},
63       pipeline_instances: {}
64     }
65     @total_activity = {}
66     @spans = [['This week', Time.now.beginning_of_week, Time.now],
67               ['Last week',
68                Time.now.beginning_of_week.advance(weeks:-1),
69                Time.now.beginning_of_week],
70               ['This month', Time.now.beginning_of_month, Time.now],
71               ['Last month',
72                1.month.ago.beginning_of_month,
73                Time.now.beginning_of_month]]
74     @spans.each do |span, threshold_start, threshold_end|
75       @activity[:logins][span] = Log.select(%w(uuid modified_by_user_uuid)).
76         filter([[:event_type, '=', 'login'],
77                 [:object_kind, '=', 'arvados#user'],
78                 [:created_at, '>=', threshold_start],
79                 [:created_at, '<', threshold_end]]).with_count("none")
80       @activity[:jobs][span] = Job.select(%w(uuid modified_by_user_uuid)).
81         filter([[:created_at, '>=', threshold_start],
82                 [:created_at, '<', threshold_end]]).with_count("none")
83       @activity[:pipeline_instances][span] = PipelineInstance.select(%w(uuid modified_by_user_uuid)).
84         filter([[:created_at, '>=', threshold_start],
85                 [:created_at, '<', threshold_end]]).with_count("none")
86       @activity.each do |type, act|
87         records = act[span]
88         @users.each do |u|
89           @user_activity[u.uuid] ||= {}
90           @user_activity[u.uuid][span + ' ' + type.to_s] ||= 0
91         end
92         records.each do |record|
93           @user_activity[record.modified_by_user_uuid] ||= {}
94           @user_activity[record.modified_by_user_uuid][span + ' ' + type.to_s] ||= 0
95           @user_activity[record.modified_by_user_uuid][span + ' ' + type.to_s] += 1
96           @total_activity[span + ' ' + type.to_s] ||= 0
97           @total_activity[span + ' ' + type.to_s] += 1
98         end
99       end
100     end
101     @users = @users.sort_by do |a|
102       [-@user_activity[a.uuid].values.inject(:+), a.full_name]
103     end
104     # Prepend a "Total" pseudo-user to the sorted list
105     @user_activity[nil] = @total_activity
106     @users = [OpenStruct.new(uuid: nil)] + @users
107   end
108
109   def storage
110     @breadcrumb_page_name = nil
111     @users = User.limit(params[:limit]).with_count("none")
112     @user_storage = {}
113     total_storage = {}
114     @log_date = {}
115     @users.each do |u|
116       @user_storage[u.uuid] ||= {}
117       storage_log = Log.
118         filter([[:object_uuid, '=', u.uuid],
119                 [:event_type, '=', 'user-storage-report']]).
120         order(:created_at => :desc).
121         with_count('none').
122         limit(1)
123       storage_log.each do |log_entry|
124         # We expect this block to only execute once since we specified limit(1)
125         @user_storage[u.uuid] = log_entry['properties']
126         @log_date[u.uuid] = log_entry['event_at']
127       end
128       total_storage.merge!(@user_storage[u.uuid]) { |k,v1,v2| v1 + v2 }
129     end
130     @users = @users.sort_by { |u|
131       [-@user_storage[u.uuid].values.push(0).inject(:+), u.full_name]}
132     # Prepend a "Total" pseudo-user to the sorted list
133     @users = [OpenStruct.new(uuid: nil)] + @users
134     @user_storage[nil] = total_storage
135   end
136
137   def show_pane_list
138     if current_user.andand.is_admin
139       %w(Admin) | super
140     else
141       super
142     end
143   end
144
145   def index_pane_list
146     if current_user.andand.is_admin
147       super | %w(Activity)
148     else
149       super
150     end
151   end
152
153   def sudo
154     resp = arvados_api_client.api(ApiClientAuthorization, '', {
155                                     api_client_authorization: {
156                                       owner_uuid: @object.uuid
157                                     }
158                                   })
159     redirect_to root_url(api_token: "v2/#{resp[:uuid]}/#{resp[:api_token]}")
160   end
161
162   def home
163     @my_ssh_keys = AuthorizedKey.where(authorized_user_uuid: current_user.uuid)
164     @my_tag_links = {}
165
166     @my_jobs = Job.
167       limit(10).
168       order('created_at desc').
169       with_count('none').
170       where(created_by: current_user.uuid)
171
172     @my_collections = Collection.
173       limit(10).
174       order('created_at desc').
175       with_count('none').
176       where(created_by: current_user.uuid)
177     collection_uuids = @my_collections.collect &:uuid
178
179     @persist_state = {}
180     collection_uuids.each do |uuid|
181       @persist_state[uuid] = 'cache'
182     end
183
184     Link.filter([['head_uuid', 'in', collection_uuids],
185                              ['link_class', 'in', ['tag', 'resources']]]).with_count("none")
186       each do |link|
187       case link.link_class
188       when 'tag'
189         (@my_tag_links[link.head_uuid] ||= []) << link
190       when 'resources'
191         if link.name == 'wants'
192           @persist_state[link.head_uuid] = 'persistent'
193         end
194       end
195     end
196
197     @my_pipelines = PipelineInstance.
198       limit(10).
199       order('created_at desc').
200       with_count('none').
201       where(created_by: current_user.uuid)
202
203     respond_to do |f|
204       f.js { render template: 'users/home.js' }
205       f.html { render template: 'users/home' }
206     end
207   end
208
209   def unsetup
210     if current_user.andand.is_admin
211       @object.unsetup
212     end
213     show
214   end
215
216   def setup
217     respond_to do |format|
218       if current_user.andand.is_admin
219         setup_params = {}
220         setup_params[:send_notification_email] = "#{Rails.configuration.Mail.SendUserSetupNotificationEmail}"
221         if params['user_uuid'] && params['user_uuid'].size>0
222           setup_params[:uuid] = params['user_uuid']
223         end
224         if params['email'] && params['email'].size>0
225           user = {email: params['email']}
226           setup_params[:user] = user
227         end
228         if params['openid_prefix'] && params['openid_prefix'].size>0
229           setup_params[:openid_prefix] = params['openid_prefix']
230         end
231         if params['vm_uuid'] && params['vm_uuid'].size>0
232           setup_params[:vm_uuid] = params['vm_uuid']
233         end
234
235         setup_resp = User.setup setup_params
236         if setup_resp
237           vm_link = nil
238           setup_resp[:items].each do |item|
239             if item[:head_kind] == "arvados#virtualMachine"
240               vm_link = item
241               break
242             end
243           end
244           if params[:groups]
245             new_groups = params[:groups].split(',').map(&:strip).select{|i| !i.empty?}
246             if vm_link and new_groups != vm_link[:properties][:groups]
247               vm_login_link = Link.where(uuid: vm_link[:uuid])
248               if vm_login_link.items_available > 0
249                 link = vm_login_link.results.first
250                 props = link.properties
251                 props[:groups] = new_groups
252                 link.save!
253               end
254             end
255           end
256
257           format.js
258         else
259           self.render_error status: 422
260         end
261       else
262         self.render_error status: 422
263       end
264     end
265   end
266
267   def setup_popup
268     @vms = VirtualMachine.all.results
269
270     @current_selections = find_current_links @object
271
272     respond_to do |format|
273       format.html
274       format.js
275     end
276   end
277
278   def virtual_machines
279     @my_vm_logins = {}
280     Link.where(tail_uuid: @object.uuid,
281                link_class: 'permission',
282                name: 'can_login').with_count("none").
283           each do |perm_link|
284             if perm_link.properties.andand[:username]
285               @my_vm_logins[perm_link.head_uuid] ||= []
286               @my_vm_logins[perm_link.head_uuid] << perm_link.properties[:username]
287             end
288           end
289     @my_virtual_machines = VirtualMachine.where(uuid: @my_vm_logins.keys).with_count("none")
290   end
291
292   def ssh_keys
293     @my_ssh_keys = AuthorizedKey.where(key_type: 'SSH', owner_uuid: @object.uuid)
294   end
295
296   def add_ssh_key_popup
297     respond_to do |format|
298       format.html
299       format.js
300     end
301   end
302
303   def add_ssh_key
304     respond_to do |format|
305       key_params = {'key_type' => 'SSH'}
306       key_params['authorized_user_uuid'] = current_user.uuid
307
308       if params['name'] && params['name'].size>0
309         key_params['name'] = params['name'].strip
310       end
311       if params['public_key'] && params['public_key'].size>0
312         key_params['public_key'] = params['public_key'].strip
313       end
314
315       if !key_params['name'] && params['public_key'].andand.size>0
316         split_key = key_params['public_key'].split
317         key_params['name'] = split_key[-1] if (split_key.size == 3)
318       end
319
320       new_key = AuthorizedKey.create! key_params
321       if new_key
322         format.js
323       else
324         self.render_error status: 422
325       end
326     end
327   end
328
329   def request_shell_access
330     logger.warn "request_access: #{params.inspect}"
331     params['request_url'] = request.url
332     RequestShellAccessReporter.send_request(current_user, params).deliver
333   end
334
335   def merge
336     User.merge params[:new_user_token], params[:direction]
337     redirect_to "/"
338   end
339
340   protected
341
342   def find_current_links user
343     current_selections = {}
344
345     if !user
346       return current_selections
347     end
348
349     # oid login perm
350     oid_login_perms = Link.where(tail_uuid: user.email,
351                                    head_kind: 'arvados#user',
352                                    link_class: 'permission',
353                                    name: 'can_login').with_count("none")
354
355     if oid_login_perms.any?
356       prefix_properties = oid_login_perms.first.properties
357       current_selections[:identity_url_prefix] = prefix_properties[:identity_url_prefix]
358     end
359
360     # repo perm
361     repo_perms = Link.where(tail_uuid: user.uuid,
362                             head_kind: 'arvados#repository',
363                             link_class: 'permission',
364                             name: 'can_write').with_count("none")
365     if repo_perms.any?
366       repo_uuid = repo_perms.first.head_uuid
367       repos = Repository.where(head_uuid: repo_uuid).with_count("none")
368       if repos.any?
369         repo_name = repos.first.name
370         current_selections[:repo_name] = repo_name
371       end
372     end
373
374     # vm login perm
375     vm_login_perms = Link.where(tail_uuid: user.uuid,
376                               head_kind: 'arvados#virtualMachine',
377                               link_class: 'permission',
378                               name: 'can_login').with_count("none")
379     if vm_login_perms.any?
380       vm_perm = vm_login_perms.first
381       vm_uuid = vm_perm.head_uuid
382       current_selections[:vm_uuid] = vm_uuid
383       current_selections[:groups] = vm_perm.properties[:groups].andand.join(', ')
384     end
385
386     return current_selections
387   end
388
389 end