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
68 f.json { render json: @objects }
71 comparable = self.respond_to? :compare
72 render(partial: 'show_' + params['tab_pane'].downcase,
73 locals: { comparable: comparable, objects: @objects })
85 @limit = params[:limit].to_i
90 @offset = params[:offset].to_i
95 filters = params[:filters]
96 if filters.is_a? String
97 filters = Oj.load filters
102 @objects ||= model_class
103 @objects = @objects.filter(@filters).limit(@limit).offset(@offset).all
109 return render_not_found("object not found")
112 f.json { render json: @object.attributes.merge(href: url_for(@object)) }
114 if params['tab_pane']
115 comparable = self.respond_to? :compare
116 render(partial: 'show_' + params['tab_pane'].downcase,
117 locals: { comparable: comparable, objects: @objects })
119 if request.method == 'GET'
122 redirect_to params[:return_to] || @object
132 return render_not_found("object not found")
137 @object = model_class.new
141 @updates ||= params[@object.class.to_s.underscore.singularize.to_sym]
142 @updates.keys.each do |attr|
143 if @object.send(attr).is_a? Hash
144 if @updates[attr].is_a? String
145 @updates[attr] = Oj.load @updates[attr]
147 if params[:merge] || params["merge_#{attr}".to_sym]
148 # Merge provided Hash with current Hash, instead of
150 @updates[attr] = @object.send(attr).with_indifferent_access.
151 deep_merge(@updates[attr].with_indifferent_access)
155 if @object.update_attributes @updates
158 self.render_error status: 422
163 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
164 @new_resource_attrs ||= {}
165 @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
166 @object ||= model_class.new @new_resource_attrs, params["options"]
169 f.json { render json: @object.attributes.merge(href: url_for(@object)) }
176 self.render_error status: 422
183 f.json { render json: @object }
185 redirect_to(params[:return_to] || :back)
190 self.render_error status: 422
195 return Thread.current[:user] if Thread.current[:user]
197 if Thread.current[:arvados_api_token]
199 if session[:user][:is_active] != true
200 Thread.current[:user] = User.current
202 Thread.current[:user] = User.new(session[:user])
205 Thread.current[:user] = User.current
208 logger.error "No API token in Thread"
214 controller_name.classify.constantize
217 def breadcrumb_page_name
218 (@breadcrumb_page_name ||
219 (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
228 %w(Attributes Metadata JSON API)
233 def redirect_to_login
236 if request.method == 'GET'
237 redirect_to arvados_api_client.arvados_login_url(return_to: request.url)
239 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."
244 @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.']
245 self.render_error status: 422
248 false # For convenience to return from callbacks
251 def using_specific_api_token(api_token)
253 [:arvados_api_token, :user].each do |key|
254 start_values[key] = Thread.current[key]
256 Thread.current[:arvados_api_token] = api_token
257 Thread.current[:user] = nil
261 start_values.each_key { |key| Thread.current[key] = start_values[key] }
265 def find_object_by_uuid
266 if params[:id] and params[:id].match /\D/
267 params[:uuid] = params.delete :id
271 elsif params[:uuid].is_a? String
272 if params[:uuid].empty?
275 @object = model_class.find(params[:uuid])
278 @object = model_class.where(uuid: params[:uuid]).first
283 Thread.current[:arvados_api_token] = nil
284 Thread.current[:user] = nil
285 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
287 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
290 def thread_with_api_token(login_optional = false)
292 try_redirect_to_login = true
293 if params[:api_token]
294 try_redirect_to_login = false
295 Thread.current[:arvados_api_token] = params[:api_token]
296 # Before copying the token into session[], do a simple API
297 # call to verify its authenticity.
299 session[:arvados_api_token] = params[:api_token]
303 first_name: u.first_name,
304 last_name: u.last_name,
305 is_active: u.is_active,
306 is_admin: u.is_admin,
309 if !request.format.json? and request.method == 'GET'
310 # Repeat this request with api_token in the (new) session
311 # cookie instead of the query string. This prevents API
312 # tokens from appearing in (and being inadvisedly copied
313 # and pasted from) browser Location bars.
314 redirect_to request.fullpath.sub(%r{([&\?]api_token=)[^&\?]*}, '')
319 @errors = ['Invalid API token']
320 self.render_error status: 401
322 elsif session[:arvados_api_token]
323 # In this case, the token must have already verified at some
324 # point, but it might have been revoked since. We'll try
325 # using it, and catch the exception if it doesn't work.
326 try_redirect_to_login = false
327 Thread.current[:arvados_api_token] = session[:arvados_api_token]
330 rescue ArvadosApiClient::NotLoggedInException
331 try_redirect_to_login = true
334 logger.debug "No token received, session is #{session.inspect}"
336 if try_redirect_to_login
337 unless login_optional
340 # login is optional for this route so go on to the regular controller
341 Thread.current[:arvados_api_token] = nil
346 # Remove token in case this Thread is used for anything else.
347 Thread.current[:arvados_api_token] = nil
351 def thread_with_mandatory_api_token
352 thread_with_api_token do
357 # This runs after thread_with_mandatory_api_token in the filter chain.
358 def thread_with_optional_api_token
359 if Thread.current[:arvados_api_token]
360 # We are already inside thread_with_mandatory_api_token.
363 # We skipped thread_with_mandatory_api_token. Use the optional version.
364 thread_with_api_token(true) do
372 Link.where(uuid: 'just-verifying-my-api-token')
374 rescue ArvadosApiClient::NotLoggedInException
379 def ensure_current_user_is_admin
380 unless current_user and current_user.is_admin
381 @errors = ['Permission denied']
382 self.render_error status: 401
386 def check_user_agreements
387 if current_user && !current_user.is_active && current_user.is_invited
388 signatures = UserAgreement.signatures
389 @signed_ua_uuids = UserAgreement.signatures.map &:head_uuid
390 @required_user_agreements = UserAgreement.all.map do |ua|
391 if not @signed_ua_uuids.index ua.uuid
392 Collection.find(ua.uuid)
395 if @required_user_agreements.empty?
396 # No agreements to sign. Perhaps we just need to ask?
397 current_user.activate
398 if !current_user.is_active
399 logger.warn "#{current_user.uuid.inspect}: " +
400 "No user agreements to sign, but activate failed!"
403 if !current_user.is_active
404 render 'user_agreements/index'
411 return Rails.configuration.arvados_theme
414 @@notification_tests = []
416 @@notification_tests.push lambda { |controller, current_user|
417 AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
420 return lambda { |view|
421 view.render partial: 'notifications/ssh_key_notification'
425 #@@notification_tests.push lambda { |controller, current_user|
426 # Job.limit(1).where(created_by: current_user.uuid).each do
429 # return lambda { |view|
430 # view.render partial: 'notifications/jobs_notification'
434 @@notification_tests.push lambda { |controller, current_user|
435 Collection.limit(1).where(created_by: current_user.uuid).each do
438 return lambda { |view|
439 view.render partial: 'notifications/collections_notification'
443 @@notification_tests.push lambda { |controller, current_user|
444 PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
447 return lambda { |view|
448 view.render partial: 'notifications/pipelines_notification'
452 def check_user_notifications
453 return if params['tab_pane']
455 @notification_count = 0
459 @showallalerts = false
460 @@notification_tests.each do |t|
461 a = t.call(self, current_user)
463 @notification_count += 1
464 @notifications.push a
469 if @notification_count == 0
470 @notification_count = ''
474 helper_method :my_folders
476 return @my_folders if @my_folders
479 Group.filter([['group_class','=','folder']]).each do |g|
480 root_of[g.uuid] = g.owner_uuid
486 root_of = root_of.each_with_object({}) do |(child, parent), h|
488 h[child] = root_of[parent]
495 @my_folders = @my_folders.select do |g|
496 root_of[g.uuid] == current_user.uuid