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