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