1 class ApplicationController < ActionController::Base
2 include ArvadosApiClientHelper
4 respond_to :html, :json, :js
7 ERROR_ACTIONS = [:render_error, :render_not_found]
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
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
33 def unprocessable(message=nil)
36 @errors << message if message
37 render_error status: 422
40 def render_error(opts)
41 opts = {status: 500}.merge opts
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
47 f.json { render opts.merge(json: {success: false, errors: @errors}) }
48 f.html { render opts.merge(controller: 'application', action: 'error') }
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
60 self.render_error status: 422
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
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
74 @name_links_cache[uuid] = []
79 filter([['link_class', '=', 'name'],
80 ['head_uuid', 'in', uuids]]).
83 name_links.each do |link|
84 @name_links_cache[link.head_uuid] << link
86 offset += name_links.result_limit
87 break if offset >= name_links.items_available
90 @name_links_cache[object.uuid] || []
96 @limit = params[:limit].to_i
101 @offset = params[:offset].to_i
106 filters = params[:filters]
107 if filters.is_a? String
108 filters = Oj.load filters
113 @objects ||= model_class
114 @objects = @objects.filter(@filters).limit(@limit).offset(@offset).all
116 f.json { render json: @objects }
124 return render_not_found("object not found")
127 f.json { render json: @object.attributes.merge(href: url_for(@object)) }
129 if request.method == 'GET'
131 elsif params[:return_to]
132 redirect_to params[:return_to]
134 redirect_to action: :show, id: @name_link.uuid
145 return render_not_found("object not found")
150 @object = model_class.new
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]
160 if params[:merge] || params["merge_#{attr}".to_sym]
161 # Merge provided Hash with current Hash, instead of
163 updates[attr] = @object.send(attr).with_indifferent_access.
164 deep_merge(updates[attr].with_indifferent_access)
168 if @object.update_attributes updates
171 self.render_error status: 422
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
181 if model_class != Link
182 @name_link = Link.new(tail_uuid: current_user.uuid,
183 head_uuid: @object.uuid,
194 f.json { render json: @object }
196 redirect_to(params[:return_to] || :back)
201 self.render_error status: 422
206 if Thread.current[:arvados_api_token]
207 Thread.current[:user] ||= User.current
209 logger.error "No API token in Thread"
215 controller_name.classify.constantize
218 def breadcrumb_page_name
219 (@breadcrumb_page_name ||
220 (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
229 %w(Attributes Metadata JSON API)
234 def redirect_to_login
237 if request.method == 'GET'
238 redirect_to arvados_api_client.arvados_login_url(return_to: request.url)
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."
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
249 false # For convenience to return from callbacks
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]
258 rescue ArvadosApiClient::NotLoggedInException
262 return redirect_to_login
265 Thread.current[:reader_tokens] = nil
269 def using_specific_api_token(api_token)
271 [:arvados_api_token, :user].each do |key|
272 start_values[key] = Thread.current[key]
274 Thread.current[:arvados_api_token] = api_token
275 Thread.current[:user] = nil
279 start_values.each_key { |key| Thread.current[key] = start_values[key] }
283 def find_object_by_uuid
284 if params[:id] and params[:id].match /\D/
285 params[:uuid] = params.delete :id
289 elsif params[:uuid].is_a? String
290 if params[:uuid].empty?
292 elsif model_class.to_s != 'Link' and
293 ArvadosBase::resource_class_for_uuid(params[:uuid]).to_s == 'Link'
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
300 @object = model_class.find(params[:uuid])
303 @object = model_class.where(uuid: params[:uuid]).first
308 Thread.current[:arvados_api_token] = nil
309 Thread.current[:user] = nil
310 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
312 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
315 def thread_with_api_token(login_optional = false)
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.
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=)[^&\?]*}, '')
335 @errors = ['Invalid API token']
336 self.render_error status: 401
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]
346 rescue ArvadosApiClient::NotLoggedInException
347 try_redirect_to_login = true
350 logger.debug "No token received, session is #{session.inspect}"
352 if try_redirect_to_login
353 unless login_optional
356 # login is optional for this route so go on to the regular controller
357 Thread.current[:arvados_api_token] = nil
362 # Remove token in case this Thread is used for anything else.
363 Thread.current[:arvados_api_token] = nil
367 def thread_with_mandatory_api_token
368 thread_with_api_token do
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.
379 # We skipped thread_with_mandatory_api_token. Use the optional version.
380 thread_with_api_token(true) do
388 Link.where(uuid: 'just-verifying-my-api-token')
390 rescue ArvadosApiClient::NotLoggedInException
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
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)
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!"
419 if !current_user.is_active
420 render 'user_agreements/index'
427 return Rails.configuration.arvados_theme
430 @@notification_tests = []
432 @@notification_tests.push lambda { |controller, current_user|
433 AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
436 return lambda { |view|
437 view.render partial: 'notifications/ssh_key_notification'
441 #@@notification_tests.push lambda { |controller, current_user|
442 # Job.limit(1).where(created_by: current_user.uuid).each do
445 # return lambda { |view|
446 # view.render partial: 'notifications/jobs_notification'
450 @@notification_tests.push lambda { |controller, current_user|
451 Collection.limit(1).where(created_by: current_user.uuid).each do
454 return lambda { |view|
455 view.render partial: 'notifications/collections_notification'
459 @@notification_tests.push lambda { |controller, current_user|
460 PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
463 return lambda { |view|
464 view.render partial: 'notifications/pipelines_notification'
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 || '' }
477 def check_user_notifications
478 @notification_count = 0
482 @showallalerts = false
483 @@notification_tests.each do |t|
484 a = t.call(self, current_user)
486 @notification_count += 1
487 @notifications.push a
492 if @notification_count == 0
493 @notification_count = ''