refs #2871
[arvados.git] / apps / workbench / app / controllers / application_controller.rb
1 class ApplicationController < ActionController::Base
2   include ArvadosApiClientHelper
3
4   respond_to :html, :json, :js
5   protect_from_forgery
6
7   ERROR_ACTIONS = [:render_error, :render_not_found]
8
9   around_filter :thread_clear
10   around_filter :thread_with_mandatory_api_token, except: ERROR_ACTIONS
11   around_filter :thread_with_optional_api_token
12   before_filter :check_user_agreements, except: ERROR_ACTIONS
13   before_filter :check_user_notifications, except: ERROR_ACTIONS
14   before_filter :find_object_by_uuid, except: [:index] + ERROR_ACTIONS
15   theme :select_theme
16
17   begin
18     rescue_from Exception,
19     :with => :render_exception
20     rescue_from ActiveRecord::RecordNotFound,
21     :with => :render_not_found
22     rescue_from ActionController::RoutingError,
23     :with => :render_not_found
24     rescue_from ActionController::UnknownController,
25     :with => :render_not_found
26     rescue_from ::AbstractController::ActionNotFound,
27     :with => :render_not_found
28   end
29
30   def unprocessable(message=nil)
31     @errors ||= []
32
33     @errors << message if message
34     render_error status: 422
35   end
36
37   def render_error(opts)
38     opts = {status: 500}.merge opts
39     respond_to do |f|
40       # json must come before html here, so it gets used as the
41       # default format when js is requested by the client. This lets
42       # ajax:error callback parse the response correctly, even though
43       # the browser can't.
44       f.json { render opts.merge(json: {success: false, errors: @errors}) }
45       f.html { render opts.merge(controller: 'application', action: 'error') }
46     end
47   end
48
49   def render_exception(e)
50     logger.error e.inspect
51     logger.error e.backtrace.collect { |x| x + "\n" }.join('') if e.backtrace
52     if @object.andand.errors.andand.full_messages.andand.any?
53       @errors = @object.errors.full_messages
54     else
55       @errors = [e.to_s]
56     end
57     self.render_error status: 422
58   end
59
60   def render_not_found(e=ActionController::RoutingError.new("Path not found"))
61     logger.error e.inspect
62     @errors = ["Path not found"]
63     self.render_error status: 404
64   end
65
66   def render_index
67     respond_to do |f|
68       f.json { render json: @objects }
69       f.html {
70         if params['tab_pane']
71           comparable = self.respond_to? :compare
72           render(partial: 'show_' + params['tab_pane'].downcase,
73                  locals: { comparable: comparable, objects: @objects })
74         else
75           render
76         end
77       }
78       f.js { render }
79     end
80   end
81
82   def index
83     @limit ||= 200
84     if params[:limit]
85       @limit = params[:limit].to_i
86     end
87
88     @offset ||= 0
89     if params[:offset]
90       @offset = params[:offset].to_i
91     end
92
93     @filters ||= []
94     if params[:filters]
95       filters = params[:filters]
96       if filters.is_a? String
97         filters = Oj.load filters
98       end
99       @filters += filters
100     end
101
102     @objects ||= model_class
103     @objects = @objects.filter(@filters).limit(@limit).offset(@offset).all
104     render_index
105   end
106
107   def show
108     if !@object
109       return render_not_found("object not found")
110     end
111     respond_to do |f|
112       f.json { render json: @object.attributes.merge(href: url_for(@object)) }
113       f.html {
114         if params['tab_pane']
115           comparable = self.respond_to? :compare
116           render(partial: 'show_' + params['tab_pane'].downcase,
117                  locals: { comparable: comparable, objects: @objects })
118         else
119           if request.method == 'GET'
120             render
121           else
122             redirect_to params[:return_to] || @object
123           end
124         end
125       }
126       f.js { render }
127     end
128   end
129
130   def render_content
131     if !@object
132       return render_not_found("object not found")
133     end
134   end
135
136   def new
137     @object = model_class.new
138   end
139
140   def update
141     @updates ||= params[@object.class.to_s.underscore.singularize.to_sym]
142     @updates.keys.each do |attr|
143       if @object.send(attr).is_a? Hash
144         if @updates[attr].is_a? String
145           @updates[attr] = Oj.load @updates[attr]
146         end
147         if params[:merge] || params["merge_#{attr}".to_sym]
148           # Merge provided Hash with current Hash, instead of
149           # replacing.
150           @updates[attr] = @object.send(attr).with_indifferent_access.
151             deep_merge(@updates[attr].with_indifferent_access)
152         end
153       end
154     end
155     if @object.update_attributes @updates
156       show
157     else
158       self.render_error status: 422
159     end
160   end
161
162   def create
163     @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
164     @new_resource_attrs ||= {}
165     @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
166     @object ||= model_class.new @new_resource_attrs, params["options"]
167     if @object.save
168       respond_to do |f|
169         f.json { render json: @object.attributes.merge(href: url_for(@object)) }
170         f.html {
171           redirect_to @object
172         }
173         f.js { render }
174       end
175     else
176       self.render_error status: 422
177     end
178   end
179
180   def destroy
181     if @object.destroy
182       respond_to do |f|
183         f.json { render json: @object }
184         f.html {
185           redirect_to(params[:return_to] || :back)
186         }
187         f.js { render }
188       end
189     else
190       self.render_error status: 422
191     end
192   end
193
194   def current_user
195     return Thread.current[:user] if Thread.current[:user]
196
197     if Thread.current[:arvados_api_token]
198       if session[:user]
199         if session[:user][:is_active] != true
200           Thread.current[:user] = User.current
201         else
202           Thread.current[:user] = User.new(session[:user])
203         end
204       else
205         Thread.current[:user] = User.current
206       end
207     else
208       logger.error "No API token in Thread"
209       return nil
210     end
211   end
212
213   def model_class
214     controller_name.classify.constantize
215   end
216
217   def breadcrumb_page_name
218     (@breadcrumb_page_name ||
219      (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
220      action_name)
221   end
222
223   def index_pane_list
224     %w(Recent)
225   end
226
227   def show_pane_list
228     %w(Attributes Metadata JSON API)
229   end
230
231   protected
232
233   def redirect_to_login
234     respond_to do |f|
235       f.html {
236         if request.method == 'GET'
237           redirect_to arvados_api_client.arvados_login_url(return_to: request.url)
238         else
239           flash[:error] = "Either you are not logged in, or your session has timed out. I can't automatically log you in and re-attempt this request."
240           redirect_to :back
241         end
242       }
243       f.json {
244         @errors = ['You do not seem to be logged in. You did not supply an API token with this request, and your session (if any) has timed out.']
245         self.render_error status: 422
246       }
247     end
248     false  # For convenience to return from callbacks
249   end
250
251   def using_specific_api_token(api_token)
252     start_values = {}
253     [:arvados_api_token, :user].each do |key|
254       start_values[key] = Thread.current[key]
255     end
256     Thread.current[:arvados_api_token] = api_token
257     Thread.current[:user] = nil
258     begin
259       yield
260     ensure
261       start_values.each_key { |key| Thread.current[key] = start_values[key] }
262     end
263   end
264
265   def find_object_by_uuid
266     if params[:id] and params[:id].match /\D/
267       params[:uuid] = params.delete :id
268     end
269     if not model_class
270       @object = nil
271     elsif params[:uuid].is_a? String
272       if params[:uuid].empty?
273         @object = nil
274       else
275         @object = model_class.find(params[:uuid])
276       end
277     else
278       @object = model_class.where(uuid: params[:uuid]).first
279     end
280   end
281
282   def thread_clear
283     Thread.current[:arvados_api_token] = nil
284     Thread.current[:user] = nil
285     Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
286     yield
287     Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
288   end
289
290   def thread_with_api_token(login_optional = false)
291     begin
292       try_redirect_to_login = true
293       if params[:api_token]
294         try_redirect_to_login = false
295         Thread.current[:arvados_api_token] = params[:api_token]
296         # Before copying the token into session[], do a simple API
297         # call to verify its authenticity.
298         if verify_api_token
299           session[:arvados_api_token] = params[:api_token]
300           u = User.current
301           session[:user] = {
302             uuid: u.uuid,
303             email: u.email,
304             first_name: u.first_name,
305             last_name: u.last_name,
306             is_active: u.is_active,
307             is_admin: u.is_admin,
308             prefs: u.prefs
309           }
310           if !request.format.json? and request.method == 'GET'
311             # Repeat this request with api_token in the (new) session
312             # cookie instead of the query string.  This prevents API
313             # tokens from appearing in (and being inadvisedly copied
314             # and pasted from) browser Location bars.
315             redirect_to request.fullpath.sub(%r{([&\?]api_token=)[^&\?]*}, '')
316           else
317             yield
318           end
319         else
320           @errors = ['Invalid API token']
321           self.render_error status: 401
322         end
323       elsif session[:arvados_api_token]
324         # In this case, the token must have already verified at some
325         # point, but it might have been revoked since.  We'll try
326         # using it, and catch the exception if it doesn't work.
327         try_redirect_to_login = false
328         Thread.current[:arvados_api_token] = session[:arvados_api_token]
329         begin
330           yield
331         rescue ArvadosApiClient::NotLoggedInException
332           try_redirect_to_login = true
333         end
334       else
335         logger.debug "No token received, session is #{session.inspect}"
336       end
337       if try_redirect_to_login
338         unless login_optional
339           redirect_to_login
340         else
341           # login is optional for this route so go on to the regular controller
342           Thread.current[:arvados_api_token] = nil
343           yield
344         end
345       end
346     ensure
347       # Remove token in case this Thread is used for anything else.
348       Thread.current[:arvados_api_token] = nil
349     end
350   end
351
352   def thread_with_mandatory_api_token
353     thread_with_api_token do
354       yield
355     end
356   end
357
358   # This runs after thread_with_mandatory_api_token in the filter chain.
359   def thread_with_optional_api_token
360     if Thread.current[:arvados_api_token]
361       # We are already inside thread_with_mandatory_api_token.
362       yield
363     else
364       # We skipped thread_with_mandatory_api_token. Use the optional version.
365       thread_with_api_token(true) do
366         yield
367       end
368     end
369   end
370
371   def verify_api_token
372     begin
373       Link.where(uuid: 'just-verifying-my-api-token')
374       true
375     rescue ArvadosApiClient::NotLoggedInException
376       false
377     end
378   end
379
380   def ensure_current_user_is_admin
381     unless current_user and current_user.is_admin
382       @errors = ['Permission denied']
383       self.render_error status: 401
384     end
385   end
386
387   def check_user_agreements
388     if current_user && !current_user.is_active && current_user.is_invited
389       signatures = UserAgreement.signatures
390       @signed_ua_uuids = UserAgreement.signatures.map &:head_uuid
391       @required_user_agreements = UserAgreement.all.map do |ua|
392         if not @signed_ua_uuids.index ua.uuid
393           Collection.find(ua.uuid)
394         end
395       end.compact
396       if @required_user_agreements.empty?
397         # No agreements to sign. Perhaps we just need to ask?
398         current_user.activate
399         if !current_user.is_active
400           logger.warn "#{current_user.uuid.inspect}: " +
401             "No user agreements to sign, but activate failed!"
402         end
403       end
404       if !current_user.is_active
405         render 'user_agreements/index'
406       end
407     end
408     true
409   end
410
411   def select_theme
412     return Rails.configuration.arvados_theme
413   end
414
415   @@notification_tests = []
416
417   @@notification_tests.push lambda { |controller, current_user|
418     AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
419       return nil
420     end
421     return lambda { |view|
422       view.render partial: 'notifications/ssh_key_notification'
423     }
424   }
425
426   #@@notification_tests.push lambda { |controller, current_user|
427   #  Job.limit(1).where(created_by: current_user.uuid).each do
428   #    return nil
429   #  end
430   #  return lambda { |view|
431   #    view.render partial: 'notifications/jobs_notification'
432   #  }
433   #}
434
435   @@notification_tests.push lambda { |controller, current_user|
436     Collection.limit(1).where(created_by: current_user.uuid).each do
437       return nil
438     end
439     return lambda { |view|
440       view.render partial: 'notifications/collections_notification'
441     }
442   }
443
444   @@notification_tests.push lambda { |controller, current_user|
445     PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
446       return nil
447     end
448     return lambda { |view|
449       view.render partial: 'notifications/pipelines_notification'
450     }
451   }
452
453   def check_user_notifications
454     return if params['tab_pane']
455
456     @notification_count = 0
457     @notifications = []
458
459     if current_user
460       @showallalerts = false
461       @@notification_tests.each do |t|
462         a = t.call(self, current_user)
463         if a
464           @notification_count += 1
465           @notifications.push a
466         end
467       end
468     end
469
470     if @notification_count == 0
471       @notification_count = ''
472     end
473   end
474
475   helper_method :my_folders
476   def my_folders
477     return @my_folders if @my_folders
478     @my_folders = []
479     root_of = {}
480     Group.filter([['group_class','=','folder']]).each do |g|
481       root_of[g.uuid] = g.owner_uuid
482       @my_folders << g
483     end
484     done = false
485     while not done
486       done = true
487       root_of = root_of.each_with_object({}) do |(child, parent), h|
488         if root_of[parent]
489           h[child] = root_of[parent]
490           done = false
491         else
492           h[child] = parent
493         end
494       end
495     end
496     @my_folders = @my_folders.select do |g|
497       root_of[g.uuid] == current_user.uuid
498     end
499   end
500
501   # helper method to get links for given object or uuid
502   helper_method :links_for_object
503   def links_for_object object_or_uuid
504     raise ArgumentError, 'No input argument' unless object_or_uuid
505     preload_links_for_objects([object_or_uuid])
506     uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
507     @all_links_for[uuid] ||= []
508   end
509
510   # helper method to preload links for given objects and uuids
511   helper_method :preload_links_for_objects
512   def preload_links_for_objects objects_and_uuids
513     @all_links_for ||= {}
514
515     raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
516     return @all_links_for if objects_and_uuids.empty?
517
518     uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
519
520     # if already preloaded for all of these uuids, return
521     if not uuids.select { |x| @all_links_for[x].nil? }.any?
522       return @all_links_for
523     end
524
525     uuids.each do |x|
526       @all_links_for[x] = []
527     end
528
529     # TODO: make sure we get every page of results from API server
530     Link.filter([['head_uuid', 'in', uuids]]).each do |link|
531       @all_links_for[link.head_uuid] << link
532     end
533     @all_links_for
534   end
535
536   # helper method to get a certain number of objects of a specific type
537   # this can be used to replace any uses of: "dataclass.limit(n)"
538   helper_method :get_n_objects_of_class
539   def get_n_objects_of_class dataclass, size
540     @objects_map_for ||= {}
541
542     raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
543     raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0)
544
545     # if the objects_map_for has a value for this dataclass, and the
546     # size used to retrieve those objects is equal, return it
547     size_key = "#{dataclass.name}_size"
548     if @objects_map_for[dataclass.name] && @objects_map_for[size_key] &&
549         (@objects_map_for[size_key] == size)
550       return @objects_map_for[dataclass.name]
551     end
552
553     @objects_map_for[size_key] = size
554     @objects_map_for[dataclass.name] = dataclass.limit(size)
555   end
556
557   # helper method to get collections for the given uuid
558   helper_method :collections_for_object
559   def collections_for_object uuid
560     raise ArgumentError, 'No input argument' unless uuid
561     preload_collections_for_objects([uuid])
562     @all_collections_for[uuid] ||= []
563   end
564
565   # helper method to preload collections for the given uuids
566   helper_method :preload_collections_for_objects
567   def preload_collections_for_objects uuids
568     @all_collections_for ||= {}
569
570     raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
571     return @all_collections_for if uuids.empty?
572
573     # if already preloaded for all of these uuids, return
574     if not uuids.select { |x| @all_collections_for[x].nil? }.any?
575       return @all_collections_for
576     end
577
578     uuids.each do |x|
579       @all_collections_for[x] = []
580     end
581
582     # TODO: make sure we get every page of results from API server
583     Collection.where(uuid: uuids).each do |collection|
584       @all_collections_for[collection.uuid] << collection
585     end
586     @all_collections_for
587   end
588
589   # helper method to get log collections for the given log
590   helper_method :log_collections_for_object
591   def log_collections_for_object log
592     raise ArgumentError, 'No input argument' unless log
593
594     preload_log_collections_for_objects([log])
595
596     uuid = log
597     fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
598     if fixup && fixup.size>1
599       uuid = fixup[1]
600     end
601
602     @all_log_collections_for[uuid] ||= []
603   end
604
605   # helper method to preload collections for the given uuids
606   helper_method :preload_log_collections_for_objects
607   def preload_log_collections_for_objects logs
608     @all_log_collections_for ||= {}
609
610     raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
611     return @all_log_collections_for if logs.empty?
612
613     uuids = []
614     logs.each do |log|
615       fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
616       if fixup && fixup.size>1
617         uuids << fixup[1]
618       else
619         uuids << log
620       end
621     end
622
623     # if already preloaded for all of these uuids, return
624     if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
625       return @all_log_collections_for
626     end
627
628     uuids.each do |x|
629       @all_log_collections_for[x] = []
630     end
631
632     # TODO: make sure we get every page of results from API server
633     Collection.where(uuid: uuids).each do |collection|
634       @all_log_collections_for[collection.uuid] << collection
635     end
636     @all_log_collections_for
637   end
638
639   # helper method to get object of a given dataclass and uuid
640   helper_method :object_for_dataclass
641   def object_for_dataclass dataclass, uuid
642     raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid)
643     preload_objects_for_dataclass(dataclass, [uuid])
644     @objects_for[uuid]
645   end
646
647   # helper method to preload objects for given dataclass and uuids
648   helper_method :preload_objects_for_dataclass
649   def preload_objects_for_dataclass dataclass, uuids
650     @objects_for ||= {}
651
652     raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
653     raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
654
655     return @objects_for if uuids.empty?
656
657     # if already preloaded for all of these uuids, return
658     if not uuids.select { |x| @objects_for[x].nil? }.any?
659       return @objects_for
660     end
661
662     dataclass.where(uuid: uuids).each do |obj|
663       @objects_for[obj.uuid] = obj
664     end
665     @objects_for
666   end
667
668 end