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