1 class ApplicationController < ActionController::Base
2 include ArvadosApiClientHelper
3 include ApplicationHelper
5 respond_to :html, :json, :js
8 ERROR_ACTIONS = [:render_error, :render_not_found]
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
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
31 def unprocessable(message=nil)
34 @errors << message if message
35 render_error status: 422
38 def render_error(opts)
39 opts = {status: 500}.merge opts
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
45 f.json { render opts.merge(json: {success: false, errors: @errors}) }
46 f.html { render opts.merge(controller: 'application', action: 'error') }
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
58 self.render_error status: 422
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
67 def find_objects_for_index
70 @limit = params[:limit].to_i
75 @offset = params[:offset].to_i
80 filters = params[:filters]
81 if filters.is_a? String
82 filters = Oj.load filters
87 @objects ||= model_class
88 @objects = @objects.filter(@filters).limit(@limit).offset(@offset)
91 helper_method :next_page_offset
93 if @objects.respond_to?(:result_offset) and
94 @objects.respond_to?(:result_limit) and
95 @objects.respond_to?(:items_available)
96 next_offset = @objects.result_offset + @objects.result_limit
97 if next_offset < @objects.items_available
106 find_objects_for_index if !@objects
108 f.json { render json: @objects }
116 return render_not_found("object not found")
119 f.json { render json: @object.attributes.merge(href: url_for(@object)) }
121 if request.method.in? ['GET', 'HEAD']
124 redirect_to params[:return_to] || @object
132 params[:limit] ||= 20
133 find_objects_for_index if !@objects
138 content: render_to_string(partial: "choose_rows.html",
141 multiple: params[:multiple]
143 next_page_href: @next_page_href
148 render partial: 'choose', locals: {multiple: params[:multiple]}
155 return render_not_found("object not found")
160 @object = model_class.new
164 @updates ||= params[@object.resource_param_name.to_sym]
165 @updates.keys.each do |attr|
166 if @object.send(attr).is_a? Hash
167 if @updates[attr].is_a? String
168 @updates[attr] = Oj.load @updates[attr]
170 if params[:merge] || params["merge_#{attr}".to_sym]
171 # Merge provided Hash with current Hash, instead of
173 @updates[attr] = @object.send(attr).with_indifferent_access.
174 deep_merge(@updates[attr].with_indifferent_access)
178 if @object.update_attributes @updates
181 self.render_error status: 422
186 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
187 @new_resource_attrs ||= {}
188 @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
189 @object ||= model_class.new @new_resource_attrs
194 # Clone the given object, merging any attribute values supplied as
195 # with a create action.
197 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
198 @new_resource_attrs ||= {}
199 @object = @object.dup
200 @object.update_attributes @new_resource_attrs
201 if not @new_resource_attrs[:name] and @object.respond_to? :name
202 if @object.name and @object.name != ''
203 @object.name = "Copy of #{@object.name}"
205 @object.name = "Copy of unnamed #{@object.class_for_display.downcase}"
215 f.json { render json: @object }
217 redirect_to(params[:return_to] || :back)
222 self.render_error status: 422
227 if Thread.current[:arvados_api_token]
228 Thread.current[:user] ||= User.current
230 logger.error "No API token in Thread"
236 controller_name.classify.constantize
239 def breadcrumb_page_name
240 (@breadcrumb_page_name ||
241 (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
250 %w(Attributes Advanced)
255 def redirect_to_login
258 if request.method.in? ['GET', 'HEAD']
259 redirect_to arvados_api_client.arvados_login_url(return_to: request.url)
261 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."
266 @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.']
267 self.render_error status: 422
270 false # For convenience to return from callbacks
273 def using_specific_api_token(api_token)
275 [:arvados_api_token, :user].each do |key|
276 start_values[key] = Thread.current[key]
278 Thread.current[:arvados_api_token] = api_token
279 Thread.current[:user] = nil
283 start_values.each_key { |key| Thread.current[key] = start_values[key] }
287 def find_object_by_uuid
288 if params[:id] and params[:id].match /\D/
289 params[:uuid] = params.delete :id
293 elsif params[:uuid].is_a? String
294 if params[:uuid].empty?
297 if (model_class != Link and
298 resource_class_for_uuid(params[:uuid]) == Link)
299 @name_link = Link.find(params[:uuid])
300 @object = model_class.find(@name_link.head_uuid)
302 @object = model_class.find(params[:uuid])
306 @object = model_class.where(uuid: params[:uuid]).first
311 Thread.current[:arvados_api_token] = nil
312 Thread.current[:user] = nil
313 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
315 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
318 def thread_with_api_token(login_optional = false)
320 try_redirect_to_login = true
321 if params[:api_token]
322 try_redirect_to_login = false
323 Thread.current[:arvados_api_token] = params[:api_token]
324 # Before copying the token into session[], do a simple API
325 # call to verify its authenticity.
327 session[:arvados_api_token] = params[:api_token]
328 if !request.format.json? and request.method.in? ['GET', 'HEAD']
329 # Repeat this request with api_token in the (new) session
330 # cookie instead of the query string. This prevents API
331 # tokens from appearing in (and being inadvisedly copied
332 # and pasted from) browser Location bars.
333 redirect_to request.fullpath.sub(%r{([&\?]api_token=)[^&\?]*}, '')
338 @errors = ['Invalid API token']
339 self.render_error status: 401
341 elsif session[:arvados_api_token]
342 # In this case, the token must have already verified at some
343 # point, but it might have been revoked since. We'll try
344 # using it, and catch the exception if it doesn't work.
345 try_redirect_to_login = false
346 Thread.current[:arvados_api_token] = session[:arvados_api_token]
349 rescue ArvadosApiClient::NotLoggedInException
350 try_redirect_to_login = true
353 logger.debug "No token received, session is #{session.inspect}"
355 if try_redirect_to_login
356 unless login_optional
359 # login is optional for this route so go on to the regular controller
360 Thread.current[:arvados_api_token] = nil
365 # Remove token in case this Thread is used for anything else.
366 Thread.current[:arvados_api_token] = nil
370 def thread_with_mandatory_api_token
371 thread_with_api_token do
376 # This runs after thread_with_mandatory_api_token in the filter chain.
377 def thread_with_optional_api_token
378 if Thread.current[:arvados_api_token]
379 # We are already inside thread_with_mandatory_api_token.
382 # We skipped thread_with_mandatory_api_token. Use the optional version.
383 thread_with_api_token(true) do
391 Link.where(uuid: 'just-verifying-my-api-token')
393 rescue ArvadosApiClient::NotLoggedInException
398 def ensure_current_user_is_admin
399 unless current_user and current_user.is_admin
400 @errors = ['Permission denied']
401 self.render_error status: 401
405 def check_user_agreements
406 if current_user && !current_user.is_active && current_user.is_invited
407 signatures = UserAgreement.signatures
408 @signed_ua_uuids = UserAgreement.signatures.map &:head_uuid
409 @required_user_agreements = UserAgreement.all.map do |ua|
410 if not @signed_ua_uuids.index ua.uuid
411 Collection.find(ua.uuid)
414 if @required_user_agreements.empty?
415 # No agreements to sign. Perhaps we just need to ask?
416 current_user.activate
417 if !current_user.is_active
418 logger.warn "#{current_user.uuid.inspect}: " +
419 "No user agreements to sign, but activate failed!"
422 if !current_user.is_active
423 render 'user_agreements/index'
430 return Rails.configuration.arvados_theme
433 @@notification_tests = []
435 @@notification_tests.push lambda { |controller, current_user|
436 AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
439 return lambda { |view|
440 view.render partial: 'notifications/ssh_key_notification'
444 #@@notification_tests.push lambda { |controller, current_user|
445 # Job.limit(1).where(created_by: current_user.uuid).each do
448 # return lambda { |view|
449 # view.render partial: 'notifications/jobs_notification'
453 @@notification_tests.push lambda { |controller, current_user|
454 Collection.limit(1).where(created_by: current_user.uuid).each do
457 return lambda { |view|
458 view.render partial: 'notifications/collections_notification'
462 @@notification_tests.push lambda { |controller, current_user|
463 PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
466 return lambda { |view|
467 view.render partial: 'notifications/pipelines_notification'
471 def check_user_notifications
472 @notification_count = 0
476 @showallalerts = false
477 @@notification_tests.each do |t|
478 a = t.call(self, current_user)
480 @notification_count += 1
481 @notifications.push a
486 if @notification_count == 0
487 @notification_count = ''
491 helper_method :my_folders
493 return @my_folders if @my_folders
496 Group.filter([['group_class','=','folder']]).each do |g|
497 root_of[g.uuid] = g.owner_uuid
503 root_of = root_of.each_with_object({}) do |(child, parent), h|
505 h[child] = root_of[parent]
512 @my_folders = @my_folders.select do |g|
513 root_of[g.uuid] == current_user.uuid
517 helper_method :recent_jobs_and_pipelines
518 def recent_jobs_and_pipelines
519 (Job.limit(10) | PipelineInstance.limit(10)).
521 x.finished_at || x.started_at || x.created_at rescue x.created_at
525 helper_method :get_object
527 if @get_object.nil? and @objects
528 @get_object = @objects.each_with_object({}) do |object, h|
529 h[object.uuid] = object