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, 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
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
30 def unprocessable(message=nil)
33 @errors << message if message
34 render_error status: 422
37 def render_error(opts)
38 opts = {status: 500}.merge opts
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
44 f.json { render opts.merge(json: {success: false, errors: @errors}) }
45 f.html { render opts.merge(controller: 'application', action: 'error') }
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
57 self.render_error status: 422
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
69 @limit = params[:limit].to_i
74 @offset = params[:offset].to_i
79 filters = params[:filters]
80 if filters.is_a? String
81 filters = Oj.load filters
86 @objects ||= model_class
87 @objects = @objects.filter(@filters).limit(@limit).offset(@offset).all
89 f.json { render json: @objects }
92 comparable = self.respond_to? :compare
93 render(partial: 'show_' + params['tab_pane'].downcase,
94 locals: { comparable: comparable, objects: @objects })
105 return render_not_found("object not found")
109 f.json { render json: @object.attributes.merge(href: url_for(@object)) }
111 if params['tab_pane']
112 comparable = self.respond_to? :compare
113 render(partial: 'show_' + params['tab_pane'].downcase,
114 locals: { comparable: comparable, objects: @objects })
116 if request.method == 'GET'
119 redirect_to params[:return_to] || @object
129 return render_not_found("object not found")
134 @object = model_class.new
138 @updates ||= params[@object.class.to_s.underscore.singularize.to_sym]
139 @updates.keys.each do |attr|
140 if @object.send(attr).is_a? Hash
141 if @updates[attr].is_a? String
142 @updates[attr] = Oj.load @updates[attr]
144 if params[:merge] || params["merge_#{attr}".to_sym]
145 # Merge provided Hash with current Hash, instead of
147 @updates[attr] = @object.send(attr).with_indifferent_access.
148 deep_merge(@updates[attr].with_indifferent_access)
152 if @object.update_attributes @updates
155 self.render_error status: 422
160 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
161 @new_resource_attrs ||= {}
162 @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
163 @object ||= model_class.new @new_resource_attrs, params["options"]
166 f.json { render json: @object.attributes.merge(href: url_for(@object)) }
173 self.render_error status: 422
180 f.json { render json: @object }
182 redirect_to(params[:return_to] || :back)
187 self.render_error status: 422
192 return Thread.current[:user] if Thread.current[:user]
194 if Thread.current[:arvados_api_token]
196 if session[:user][:is_active] != true
197 Thread.current[:user] = User.current
199 Thread.current[:user] = User.new(session[:user])
202 Thread.current[:user] = User.current
205 logger.error "No API token in Thread"
211 controller_name.classify.constantize
214 def breadcrumb_page_name
215 (@breadcrumb_page_name ||
216 (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
225 %w(Attributes Metadata JSON API)
230 def redirect_to_login
233 if request.method == 'GET'
234 redirect_to arvados_api_client.arvados_login_url(return_to: request.url)
236 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 @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.']
242 self.render_error status: 422
245 false # For convenience to return from callbacks
248 def using_specific_api_token(api_token)
250 [:arvados_api_token, :user].each do |key|
251 start_values[key] = Thread.current[key]
253 Thread.current[:arvados_api_token] = api_token
254 Thread.current[:user] = nil
258 start_values.each_key { |key| Thread.current[key] = start_values[key] }
262 def find_object_by_uuid
263 if params[:id] and params[:id].match /\D/
264 params[:uuid] = params.delete :id
268 elsif params[:uuid].is_a? String
269 if params[:uuid].empty?
272 @object = model_class.find(params[:uuid])
275 @object = model_class.where(uuid: params[:uuid]).first
280 Thread.current[:arvados_api_token] = nil
281 Thread.current[:user] = nil
282 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
284 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
287 def thread_with_api_token(login_optional = false)
289 try_redirect_to_login = true
290 if params[:api_token]
291 try_redirect_to_login = false
292 Thread.current[:arvados_api_token] = params[:api_token]
293 # Before copying the token into session[], do a simple API
294 # call to verify its authenticity.
296 session[:arvados_api_token] = params[:api_token]
300 first_name: u.first_name,
301 last_name: u.last_name,
302 is_active: u.is_active,
303 is_admin: u.is_admin,
306 if !request.format.json? and request.method == 'GET'
307 # Repeat this request with api_token in the (new) session
308 # cookie instead of the query string. This prevents API
309 # tokens from appearing in (and being inadvisedly copied
310 # and pasted from) browser Location bars.
311 redirect_to request.fullpath.sub(%r{([&\?]api_token=)[^&\?]*}, '')
316 @errors = ['Invalid API token']
317 self.render_error status: 401
319 elsif session[:arvados_api_token]
320 # In this case, the token must have already verified at some
321 # point, but it might have been revoked since. We'll try
322 # using it, and catch the exception if it doesn't work.
323 try_redirect_to_login = false
324 Thread.current[:arvados_api_token] = session[:arvados_api_token]
327 rescue ArvadosApiClient::NotLoggedInException
328 try_redirect_to_login = true
331 logger.debug "No token received, session is #{session.inspect}"
333 if try_redirect_to_login
334 unless login_optional
337 # login is optional for this route so go on to the regular controller
338 Thread.current[:arvados_api_token] = nil
343 # Remove token in case this Thread is used for anything else.
344 Thread.current[:arvados_api_token] = nil
348 def thread_with_mandatory_api_token
349 thread_with_api_token do
354 # This runs after thread_with_mandatory_api_token in the filter chain.
355 def thread_with_optional_api_token
356 if Thread.current[:arvados_api_token]
357 # We are already inside thread_with_mandatory_api_token.
360 # We skipped thread_with_mandatory_api_token. Use the optional version.
361 thread_with_api_token(true) do
369 Link.where(uuid: 'just-verifying-my-api-token')
371 rescue ArvadosApiClient::NotLoggedInException
376 def ensure_current_user_is_admin
377 unless current_user and current_user.is_admin
378 @errors = ['Permission denied']
379 self.render_error status: 401
383 def check_user_agreements
384 if current_user && !current_user.is_active && current_user.is_invited
385 signatures = UserAgreement.signatures
386 @signed_ua_uuids = UserAgreement.signatures.map &:head_uuid
387 @required_user_agreements = UserAgreement.all.map do |ua|
388 if not @signed_ua_uuids.index ua.uuid
389 Collection.find(ua.uuid)
392 if @required_user_agreements.empty?
393 # No agreements to sign. Perhaps we just need to ask?
394 current_user.activate
395 if !current_user.is_active
396 logger.warn "#{current_user.uuid.inspect}: " +
397 "No user agreements to sign, but activate failed!"
400 if !current_user.is_active
401 render 'user_agreements/index'
408 return Rails.configuration.arvados_theme
411 @@notification_tests = []
413 @@notification_tests.push lambda { |controller, current_user|
414 AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
417 return lambda { |view|
418 view.render partial: 'notifications/ssh_key_notification'
422 #@@notification_tests.push lambda { |controller, current_user|
423 # Job.limit(1).where(created_by: current_user.uuid).each do
426 # return lambda { |view|
427 # view.render partial: 'notifications/jobs_notification'
431 @@notification_tests.push lambda { |controller, current_user|
432 Collection.limit(1).where(created_by: current_user.uuid).each do
435 return lambda { |view|
436 view.render partial: 'notifications/collections_notification'
440 @@notification_tests.push lambda { |controller, current_user|
441 PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
444 return lambda { |view|
445 view.render partial: 'notifications/pipelines_notification'
449 def check_user_notifications
450 return if params['tab_pane']
452 @notification_count = 0
456 @showallalerts = false
457 @@notification_tests.each do |t|
458 a = t.call(self, current_user)
460 @notification_count += 1
461 @notifications.push a
466 if @notification_count == 0
467 @notification_count = ''
471 helper_method :my_folders
473 return @my_folders if @my_folders
476 Group.filter([['group_class','=','folder']]).each do |g|
477 root_of[g.uuid] = g.owner_uuid
483 root_of = root_of.each_with_object({}) do |(child, parent), h|
485 h[child] = root_of[parent]
492 @my_folders = @my_folders.select do |g|
493 root_of[g.uuid] == current_user.uuid