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