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