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