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