Merge branch 'master' into 6277-manifest-validation
[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])
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.select(%w(uuid modified_by_user_uuid)).
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.select(%w(uuid modified_by_user_uuid)).
61         filter([[:created_at, '>=', threshold_start],
62                 [:created_at, '<', threshold_end]])
63       @activity[:pipeline_instances][span] = PipelineInstance.select(%w(uuid modified_by_user_uuid)).
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])
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     @my_ssh_keys = AuthorizedKey.where(authorized_user_uuid: current_user.uuid)
143     @my_tag_links = {}
144
145     @my_jobs = Job.
146       limit(10).
147       order('created_at desc').
148       where(created_by: current_user.uuid)
149
150     @my_collections = Collection.
151       limit(10).
152       order('created_at desc').
153       where(created_by: current_user.uuid)
154     collection_uuids = @my_collections.collect &:uuid
155
156     @persist_state = {}
157     collection_uuids.each do |uuid|
158       @persist_state[uuid] = 'cache'
159     end
160
161     Link.filter([['head_uuid', 'in', collection_uuids],
162                              ['link_class', 'in', ['tag', 'resources']]]).
163       each do |link|
164       case link.link_class
165       when 'tag'
166         (@my_tag_links[link.head_uuid] ||= []) << link
167       when 'resources'
168         if link.name == 'wants'
169           @persist_state[link.head_uuid] = 'persistent'
170         end
171       end
172     end
173
174     @my_pipelines = PipelineInstance.
175       limit(10).
176       order('created_at desc').
177       where(created_by: current_user.uuid)
178
179     respond_to do |f|
180       f.js { render template: 'users/home.js' }
181       f.html { render template: 'users/home' }
182     end
183   end
184
185   def unsetup
186     if current_user.andand.is_admin
187       @object.unsetup
188     end
189     show
190   end
191
192   def setup
193     respond_to do |format|
194       if current_user.andand.is_admin
195         setup_params = {}
196         setup_params[:send_notification_email] = "#{Rails.configuration.send_user_setup_notification_email}"
197         if params['user_uuid'] && params['user_uuid'].size>0
198           setup_params[:uuid] = params['user_uuid']
199         end
200         if params['email'] && params['email'].size>0
201           user = {email: params['email']}
202           setup_params[:user] = user
203         end
204         if params['openid_prefix'] && params['openid_prefix'].size>0
205           setup_params[:openid_prefix] = params['openid_prefix']
206         end
207         if params['repo_name'] && params['repo_name'].size>0
208           setup_params[:repo_name] = params['repo_name']
209         end
210         if params['vm_uuid'] && params['vm_uuid'].size>0
211           setup_params[:vm_uuid] = params['vm_uuid']
212         end
213
214         setup_resp = User.setup setup_params
215         if setup_resp
216           vm_link = nil
217           setup_resp[:items].each do |item|
218             if item[:head_kind] == "arvados#virtualMachine"
219               vm_link = item
220               break
221             end
222           end
223           if params[:groups]
224             new_groups = params[:groups].split(',').map(&:strip).select{|i| !i.empty?}
225             if vm_link and new_groups != vm_link[:properties][:groups]
226               vm_login_link = Link.where(uuid: vm_link[:uuid])
227               if vm_login_link.items_available > 0
228                 link = vm_login_link.results.first
229                 props = link.properties
230                 props[:groups] = new_groups
231                 link.save!
232               end
233             end
234           end
235
236           format.js
237         else
238           self.render_error status: 422
239         end
240       else
241         self.render_error status: 422
242       end
243     end
244   end
245
246   def setup_popup
247     @vms = VirtualMachine.all.results
248
249     @current_selections = find_current_links @object
250
251     respond_to do |format|
252       format.html
253       format.js
254     end
255   end
256
257   def manage_account
258     # repositories current user can read / write
259     repo_links = Link.
260       filter([['head_uuid', 'is_a', 'arvados#repository'],
261               ['tail_uuid', '=', current_user.uuid],
262               ['link_class', '=', 'permission'],
263              ])
264
265     owned_repositories = Repository.where(owner_uuid: current_user.uuid)
266
267     @my_repositories = (Repository.where(uuid: repo_links.collect(&:head_uuid)) |
268                         owned_repositories).
269                        uniq { |repo| repo.uuid }
270
271
272     @repo_writable = {}
273     repo_links.each do |link|
274       if link.name.in? ['can_write', 'can_manage']
275         @repo_writable[link.head_uuid] = link.name
276       end
277     end
278
279     owned_repositories.each do |repo|
280       @repo_writable[repo.uuid] = 'can_manage'
281     end
282
283     # virtual machines the current user can login into
284     @my_vm_logins = {}
285     Link.where(tail_uuid: current_user.uuid,
286                link_class: 'permission',
287                name: 'can_login').
288           each do |perm_link|
289             if perm_link.properties.andand[:username]
290               @my_vm_logins[perm_link.head_uuid] ||= []
291               @my_vm_logins[perm_link.head_uuid] << perm_link.properties[:username]
292             end
293           end
294     @my_virtual_machines = VirtualMachine.where(uuid: @my_vm_logins.keys)
295
296     # current user's ssh keys
297     @my_ssh_keys = AuthorizedKey.where(key_type: 'SSH', owner_uuid: current_user.uuid)
298
299     respond_to do |f|
300       f.html { render template: 'users/manage_account' }
301     end
302   end
303
304   def add_ssh_key_popup
305     respond_to do |format|
306       format.html
307       format.js
308     end
309   end
310
311   def add_ssh_key
312     respond_to do |format|
313       key_params = {'key_type' => 'SSH'}
314       key_params['authorized_user_uuid'] = current_user.uuid
315
316       if params['name'] && params['name'].size>0
317         key_params['name'] = params['name'].strip
318       end
319       if params['public_key'] && params['public_key'].size>0
320         key_params['public_key'] = params['public_key'].strip
321       end
322
323       if !key_params['name'] && params['public_key'].andand.size>0
324         split_key = key_params['public_key'].split
325         key_params['name'] = split_key[-1] if (split_key.size == 3)
326       end
327
328       new_key = AuthorizedKey.create! key_params
329       if new_key
330         format.js
331       else
332         self.render_error status: 422
333       end
334     end
335   end
336
337   def request_shell_access
338     logger.warn "request_access: #{params.inspect}"
339     params['request_url'] = request.url
340     RequestShellAccessReporter.send_request(current_user, params).deliver
341   end
342
343   protected
344
345   def find_current_links user
346     current_selections = {}
347
348     if !user
349       return current_selections
350     end
351
352     # oid login perm
353     oid_login_perms = Link.where(tail_uuid: user.email,
354                                    head_kind: 'arvados#user',
355                                    link_class: 'permission',
356                                    name: 'can_login')
357
358     if oid_login_perms.any?
359       prefix_properties = oid_login_perms.first.properties
360       current_selections[:identity_url_prefix] = prefix_properties[:identity_url_prefix]
361     end
362
363     # repo perm
364     repo_perms = Link.where(tail_uuid: user.uuid,
365                             head_kind: 'arvados#repository',
366                             link_class: 'permission',
367                             name: 'can_write')
368     if repo_perms.any?
369       repo_uuid = repo_perms.first.head_uuid
370       repos = Repository.where(head_uuid: repo_uuid)
371       if repos.any?
372         repo_name = repos.first.name
373         current_selections[:repo_name] = repo_name
374       end
375     end
376
377     # vm login perm
378     vm_login_perms = Link.where(tail_uuid: user.uuid,
379                               head_kind: 'arvados#virtualMachine',
380                               link_class: 'permission',
381                               name: 'can_login')
382     if vm_login_perms.any?
383       vm_perm = vm_login_perms.first
384       vm_uuid = vm_perm.head_uuid
385       current_selections[:vm_uuid] = vm_uuid
386       current_selections[:groups] = vm_perm.properties[:groups].andand.join(', ')
387     end
388
389     return current_selections
390   end
391
392 end