2871: preload links helper method is added to workbench application_controller.
[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 index
67     @limit ||= 200
68     if params[:limit]
69       @limit = params[:limit].to_i
70     end
71
72     @offset ||= 0
73     if params[:offset]
74       @offset = params[:offset].to_i
75     end
76
77     @filters ||= []
78     if params[:filters]
79       filters = params[:filters]
80       if filters.is_a? String
81         filters = Oj.load filters
82       end
83       @filters += filters
84     end
85
86     @objects ||= model_class
87     @objects = @objects.filter(@filters).limit(@limit).offset(@offset).all
88     respond_to do |f|
89       f.json { render json: @objects }
90       f.html { render }
91       f.js { render }
92     end
93   end
94
95   def show
96     if !@object
97       return render_not_found("object not found")
98     end
99     respond_to do |f|
100       f.json { render json: @object.attributes.merge(href: url_for(@object)) }
101       f.html {
102         if request.method == 'GET'
103           render
104         else
105           redirect_to params[:return_to] || @object
106         end
107       }
108       f.js { render }
109     end
110   end
111
112   def render_content
113     if !@object
114       return render_not_found("object not found")
115     end
116   end
117
118   def new
119     @object = model_class.new
120   end
121
122   def update
123     @updates ||= params[@object.class.to_s.underscore.singularize.to_sym]
124     @updates.keys.each do |attr|
125       if @object.send(attr).is_a? Hash
126         if @updates[attr].is_a? String
127           @updates[attr] = Oj.load @updates[attr]
128         end
129         if params[:merge] || params["merge_#{attr}".to_sym]
130           # Merge provided Hash with current Hash, instead of
131           # replacing.
132           @updates[attr] = @object.send(attr).with_indifferent_access.
133             deep_merge(@updates[attr].with_indifferent_access)
134         end
135       end
136     end
137     if @object.update_attributes @updates
138       show
139     else
140       self.render_error status: 422
141     end
142   end
143
144   def create
145     @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
146     @new_resource_attrs ||= {}
147     @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
148     @object ||= model_class.new @new_resource_attrs
149     @object.save!
150     show
151   end
152
153   def destroy
154     if @object.destroy
155       respond_to do |f|
156         f.json { render json: @object }
157         f.html {
158           redirect_to(params[:return_to] || :back)
159         }
160         f.js { render }
161       end
162     else
163       self.render_error status: 422
164     end
165   end
166
167   def current_user
168     if Thread.current[:arvados_api_token]
169       Thread.current[:user] ||= User.current
170     else
171       logger.error "No API token in Thread"
172       return nil
173     end
174   end
175
176   def model_class
177     controller_name.classify.constantize
178   end
179
180   def breadcrumb_page_name
181     (@breadcrumb_page_name ||
182      (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
183      action_name)
184   end
185
186   def index_pane_list
187     %w(Recent)
188   end
189
190   def show_pane_list
191     %w(Attributes Metadata JSON API)
192   end
193
194   # helper method to get links for given objects or uuids
195   helper_method :links_for_object
196   def links_for_object object_or_uuid
197     uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
198     preload_links_for_objects([uuid])
199     @all_links_for[uuid]
200   end
201
202   helper_method :preload_links_for_objects
203   def preload_links_for_objects objects_and_uuids
204     uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
205     @all_links_for ||= {}
206     if not uuids.select { |x| @all_links_for[x].nil? }.any?
207       # already preloaded for all of these uuids
208       return
209     end
210     uuids.each do |x|
211       @all_links_for[x] = []
212     end
213     # TODO: make sure we get every page of results from API server
214     Link.filter([['head_uuid','in',uuids]]).each do |link|
215       @all_links_for[link.head_uuid] << link
216     end
217   end
218
219   protected
220
221   def redirect_to_login
222     respond_to do |f|
223       f.html {
224         if request.method == 'GET'
225           redirect_to arvados_api_client.arvados_login_url(return_to: request.url)
226         else
227           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."
228           redirect_to :back
229         end
230       }
231       f.json {
232         @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.']
233         self.render_error status: 422
234       }
235     end
236     false  # For convenience to return from callbacks
237   end
238
239   def using_specific_api_token(api_token)
240     start_values = {}
241     [:arvados_api_token, :user].each do |key|
242       start_values[key] = Thread.current[key]
243     end
244     Thread.current[:arvados_api_token] = api_token
245     Thread.current[:user] = nil
246     begin
247       yield
248     ensure
249       start_values.each_key { |key| Thread.current[key] = start_values[key] }
250     end
251   end
252
253   def find_object_by_uuid
254     if params[:id] and params[:id].match /\D/
255       params[:uuid] = params.delete :id
256     end
257     if not model_class
258       @object = nil
259     elsif params[:uuid].is_a? String
260       if params[:uuid].empty?
261         @object = nil
262       else
263         @object = model_class.find(params[:uuid])
264       end
265     else
266       @object = model_class.where(uuid: params[:uuid]).first
267     end
268   end
269
270   def thread_clear
271     Thread.current[:arvados_api_token] = nil
272     Thread.current[:user] = nil
273     Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
274     yield
275     Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
276   end
277
278   def thread_with_api_token(login_optional = false)
279     begin
280       try_redirect_to_login = true
281       if params[:api_token]
282         try_redirect_to_login = false
283         Thread.current[:arvados_api_token] = params[:api_token]
284         # Before copying the token into session[], do a simple API
285         # call to verify its authenticity.
286         if verify_api_token
287           session[:arvados_api_token] = params[:api_token]
288           if !request.format.json? and request.method == 'GET'
289             # Repeat this request with api_token in the (new) session
290             # cookie instead of the query string.  This prevents API
291             # tokens from appearing in (and being inadvisedly copied
292             # and pasted from) browser Location bars.
293             redirect_to request.fullpath.sub(%r{([&\?]api_token=)[^&\?]*}, '')
294           else
295             yield
296           end
297         else
298           @errors = ['Invalid API token']
299           self.render_error status: 401
300         end
301       elsif session[:arvados_api_token]
302         # In this case, the token must have already verified at some
303         # point, but it might have been revoked since.  We'll try
304         # using it, and catch the exception if it doesn't work.
305         try_redirect_to_login = false
306         Thread.current[:arvados_api_token] = session[:arvados_api_token]
307         begin
308           yield
309         rescue ArvadosApiClient::NotLoggedInException
310           try_redirect_to_login = true
311         end
312       else
313         logger.debug "No token received, session is #{session.inspect}"
314       end
315       if try_redirect_to_login
316         unless login_optional
317           redirect_to_login
318         else
319           # login is optional for this route so go on to the regular controller
320           Thread.current[:arvados_api_token] = nil
321           yield
322         end
323       end
324     ensure
325       # Remove token in case this Thread is used for anything else.
326       Thread.current[:arvados_api_token] = nil
327     end
328   end
329
330   def thread_with_mandatory_api_token
331     thread_with_api_token do
332       yield
333     end
334   end
335
336   # This runs after thread_with_mandatory_api_token in the filter chain.
337   def thread_with_optional_api_token
338     if Thread.current[:arvados_api_token]
339       # We are already inside thread_with_mandatory_api_token.
340       yield
341     else
342       # We skipped thread_with_mandatory_api_token. Use the optional version.
343       thread_with_api_token(true) do
344         yield
345       end
346     end
347   end
348
349   def verify_api_token
350     begin
351       Link.where(uuid: 'just-verifying-my-api-token')
352       true
353     rescue ArvadosApiClient::NotLoggedInException
354       false
355     end
356   end
357
358   def ensure_current_user_is_admin
359     unless current_user and current_user.is_admin
360       @errors = ['Permission denied']
361       self.render_error status: 401
362     end
363   end
364
365   def check_user_agreements
366     if current_user && !current_user.is_active && current_user.is_invited
367       signatures = UserAgreement.signatures
368       @signed_ua_uuids = UserAgreement.signatures.map &:head_uuid
369       @required_user_agreements = UserAgreement.all.map do |ua|
370         if not @signed_ua_uuids.index ua.uuid
371           Collection.find(ua.uuid)
372         end
373       end.compact
374       if @required_user_agreements.empty?
375         # No agreements to sign. Perhaps we just need to ask?
376         current_user.activate
377         if !current_user.is_active
378           logger.warn "#{current_user.uuid.inspect}: " +
379             "No user agreements to sign, but activate failed!"
380         end
381       end
382       if !current_user.is_active
383         render 'user_agreements/index'
384       end
385     end
386     true
387   end
388
389   def select_theme
390     return Rails.configuration.arvados_theme
391   end
392
393   @@notification_tests = []
394
395   @@notification_tests.push lambda { |controller, current_user|
396     AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
397       return nil
398     end
399     return lambda { |view|
400       view.render partial: 'notifications/ssh_key_notification'
401     }
402   }
403
404   #@@notification_tests.push lambda { |controller, current_user|
405   #  Job.limit(1).where(created_by: current_user.uuid).each do
406   #    return nil
407   #  end
408   #  return lambda { |view|
409   #    view.render partial: 'notifications/jobs_notification'
410   #  }
411   #}
412
413   @@notification_tests.push lambda { |controller, current_user|
414     Collection.limit(1).where(created_by: current_user.uuid).each do
415       return nil
416     end
417     return lambda { |view|
418       view.render partial: 'notifications/collections_notification'
419     }
420   }
421
422   @@notification_tests.push lambda { |controller, current_user|
423     PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
424       return nil
425     end
426     return lambda { |view|
427       view.render partial: 'notifications/pipelines_notification'
428     }
429   }
430
431   def check_user_notifications
432     @notification_count = 0
433     @notifications = []
434
435     if current_user
436       @showallalerts = false
437       @@notification_tests.each do |t|
438         a = t.call(self, current_user)
439         if a
440           @notification_count += 1
441           @notifications.push a
442         end
443       end
444     end
445
446     if @notification_count == 0
447       @notification_count = ''
448     end
449   end
450 end