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