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