1 class ApplicationController < ActionController::Base
2 respond_to :html, :json, :js
5 ERROR_ACTIONS = [:render_error, :render_not_found]
7 around_filter :thread_clear
8 around_filter(:thread_with_mandatory_api_token,
9 except: [:index, :show] + ERROR_ACTIONS)
10 around_filter :thread_with_optional_api_token
11 before_filter :check_user_agreements, except: ERROR_ACTIONS
12 before_filter :check_user_notifications, except: ERROR_ACTIONS
13 around_filter :using_reader_tokens, only: [:index, :show]
14 before_filter :find_object_by_uuid, except: [:index] + ERROR_ACTIONS
15 before_filter :check_my_folders, :except => 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
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).all
90 f.json { render json: @objects }
98 return render_not_found("object not found")
101 f.json { render json: @object.attributes.merge(href: url_for(@object)) }
103 if request.method == 'GET'
106 redirect_to params[:return_to] || @object
115 return render_not_found("object not found")
120 @object = model_class.new
124 updates = params[@object.class.to_s.underscore.singularize.to_sym]
125 updates.keys.each do |attr|
126 if @object.send(attr).is_a? Hash
127 if updates[attr].is_a? String
128 updates[attr] = Oj.load updates[attr]
130 if params[:merge] || params["merge_#{attr}".to_sym]
131 # Merge provided Hash with current Hash, instead of
133 updates[attr] = @object.send(attr).with_indifferent_access.
134 deep_merge(updates[attr].with_indifferent_access)
138 if @object.update_attributes updates
141 self.render_error status: 422
146 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
147 @new_resource_attrs ||= {}
148 @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
149 @object ||= model_class.new @new_resource_attrs
157 f.json { render json: @object }
159 redirect_to(params[:return_to] || :back)
164 self.render_error status: 422
169 if Thread.current[:arvados_api_token]
170 Thread.current[:user] ||= User.current
172 logger.error "No API token in Thread"
178 controller_name.classify.constantize
181 def breadcrumb_page_name
182 (@breadcrumb_page_name ||
183 (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
192 %w(Attributes Metadata JSON API)
197 def redirect_to_login
200 if request.method == 'GET'
201 redirect_to $arvados_api_client.arvados_login_url(return_to: request.url)
203 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."
208 @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.']
209 self.render_error status: 422
212 false # For convenience to return from callbacks
215 def using_reader_tokens(login_optional=false)
216 if params[:reader_tokens].is_a?(Array) and params[:reader_tokens].any?
217 Thread.current[:reader_tokens] = params[:reader_tokens]
221 rescue ArvadosApiClient::NotLoggedInException
225 return redirect_to_login
228 Thread.current[:reader_tokens] = nil
232 def using_specific_api_token(api_token)
234 [:arvados_api_token, :user].each do |key|
235 start_values[key] = Thread.current[key]
237 Thread.current[:arvados_api_token] = api_token
238 Thread.current[:user] = nil
242 start_values.each_key { |key| Thread.current[key] = start_values[key] }
246 def find_object_by_uuid
247 if params[:id] and params[:id].match /\D/
248 params[:uuid] = params.delete :id
252 elsif params[:uuid].is_a? String
253 if params[:uuid].empty?
256 @object = model_class.find(params[:uuid])
259 @object = model_class.where(uuid: params[:uuid]).first
264 Thread.current[:arvados_api_token] = nil
265 Thread.current[:user] = nil
266 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
268 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
271 def thread_with_api_token(login_optional = false)
273 try_redirect_to_login = true
274 if params[:api_token]
275 try_redirect_to_login = false
276 Thread.current[:arvados_api_token] = params[:api_token]
277 # Before copying the token into session[], do a simple API
278 # call to verify its authenticity.
280 session[:arvados_api_token] = params[:api_token]
281 if !request.format.json? and request.method == 'GET'
282 # Repeat this request with api_token in the (new) session
283 # cookie instead of the query string. This prevents API
284 # tokens from appearing in (and being inadvisedly copied
285 # and pasted from) browser Location bars.
286 redirect_to request.fullpath.sub(%r{([&\?]api_token=)[^&\?]*}, '')
291 @errors = ['Invalid API token']
292 self.render_error status: 401
294 elsif session[:arvados_api_token]
295 # In this case, the token must have already verified at some
296 # point, but it might have been revoked since. We'll try
297 # using it, and catch the exception if it doesn't work.
298 try_redirect_to_login = false
299 Thread.current[:arvados_api_token] = session[:arvados_api_token]
302 rescue ArvadosApiClient::NotLoggedInException
303 try_redirect_to_login = true
306 logger.debug "No token received, session is #{session.inspect}"
308 if try_redirect_to_login
309 unless login_optional
312 # login is optional for this route so go on to the regular controller
313 Thread.current[:arvados_api_token] = nil
318 # Remove token in case this Thread is used for anything else.
319 Thread.current[:arvados_api_token] = nil
323 def thread_with_mandatory_api_token
324 thread_with_api_token do
329 # This runs after thread_with_mandatory_api_token in the filter chain.
330 def thread_with_optional_api_token
331 if Thread.current[:arvados_api_token]
332 # We are already inside thread_with_mandatory_api_token.
335 # We skipped thread_with_mandatory_api_token. Use the optional version.
336 thread_with_api_token(true) do
344 Link.where(uuid: 'just-verifying-my-api-token')
346 rescue ArvadosApiClient::NotLoggedInException
351 def ensure_current_user_is_admin
352 unless current_user and current_user.is_admin
353 @errors = ['Permission denied']
354 self.render_error status: 401
358 def check_user_agreements
359 if current_user && !current_user.is_active && current_user.is_invited
360 signatures = UserAgreement.signatures
361 @signed_ua_uuids = UserAgreement.signatures.map &:head_uuid
362 @required_user_agreements = UserAgreement.all.map do |ua|
363 if not @signed_ua_uuids.index ua.uuid
364 Collection.find(ua.uuid)
367 if @required_user_agreements.empty?
368 # No agreements to sign. Perhaps we just need to ask?
369 current_user.activate
370 if !current_user.is_active
371 logger.warn "#{current_user.uuid.inspect}: " +
372 "No user agreements to sign, but activate failed!"
375 if !current_user.is_active
376 render 'user_agreements/index'
383 return Rails.configuration.arvados_theme
386 @@notification_tests = []
388 @@notification_tests.push lambda { |controller, current_user|
389 AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
392 return lambda { |view|
393 view.render partial: 'notifications/ssh_key_notification'
397 #@@notification_tests.push lambda { |controller, current_user|
398 # Job.limit(1).where(created_by: current_user.uuid).each do
401 # return lambda { |view|
402 # view.render partial: 'notifications/jobs_notification'
406 @@notification_tests.push lambda { |controller, current_user|
407 Collection.limit(1).where(created_by: current_user.uuid).each do
410 return lambda { |view|
411 view.render partial: 'notifications/collections_notification'
415 @@notification_tests.push lambda { |controller, current_user|
416 PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
419 return lambda { |view|
420 view.render partial: 'notifications/pipelines_notification'
425 @my_top_level_folders = lambda do
426 @top_level_folders ||= Group.
427 filter([['group_class','=','folder'],
428 ['owner_uuid','=',current_user.uuid]]).
429 sort_by { |x| x.name || '' }
433 def check_user_notifications
434 @notification_count = 0
438 @showallalerts = false
439 @@notification_tests.each do |t|
440 a = t.call(self, current_user)
442 @notification_count += 1
443 @notifications.push a
448 if @notification_count == 0
449 @notification_count = ''