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
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_specific_api_token(api_token)
217 [:arvados_api_token, :user].each do |key|
218 start_values[key] = Thread.current[key]
220 Thread.current[:arvados_api_token] = api_token
221 Thread.current[:user] = nil
225 start_values.each_key { |key| Thread.current[key] = start_values[key] }
229 def find_object_by_uuid
230 if params[:id] and params[:id].match /\D/
231 params[:uuid] = params.delete :id
235 elsif params[:uuid].is_a? String
236 if params[:uuid].empty?
239 @object = model_class.find(params[:uuid])
242 @object = model_class.where(uuid: params[:uuid]).first
247 Thread.current[:arvados_api_token] = nil
248 Thread.current[:user] = nil
249 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
251 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
254 def thread_with_api_token(login_optional = false)
256 try_redirect_to_login = true
257 if params[:api_token]
258 try_redirect_to_login = false
259 Thread.current[:arvados_api_token] = params[:api_token]
260 # Before copying the token into session[], do a simple API
261 # call to verify its authenticity.
263 session[:arvados_api_token] = params[:api_token]
264 if !request.format.json? and request.method == 'GET'
265 # Repeat this request with api_token in the (new) session
266 # cookie instead of the query string. This prevents API
267 # tokens from appearing in (and being inadvisedly copied
268 # and pasted from) browser Location bars.
269 redirect_to request.fullpath.sub(%r{([&\?]api_token=)[^&\?]*}, '')
274 @errors = ['Invalid API token']
275 self.render_error status: 401
277 elsif session[:arvados_api_token]
278 # In this case, the token must have already verified at some
279 # point, but it might have been revoked since. We'll try
280 # using it, and catch the exception if it doesn't work.
281 try_redirect_to_login = false
282 Thread.current[:arvados_api_token] = session[:arvados_api_token]
285 rescue ArvadosApiClient::NotLoggedInException
286 try_redirect_to_login = true
289 logger.debug "No token received, session is #{session.inspect}"
291 if try_redirect_to_login
292 unless login_optional
295 # login is optional for this route so go on to the regular controller
296 Thread.current[:arvados_api_token] = nil
301 # Remove token in case this Thread is used for anything else.
302 Thread.current[:arvados_api_token] = nil
306 def thread_with_mandatory_api_token
307 thread_with_api_token do
312 # This runs after thread_with_mandatory_api_token in the filter chain.
313 def thread_with_optional_api_token
314 if Thread.current[:arvados_api_token]
315 # We are already inside thread_with_mandatory_api_token.
318 # We skipped thread_with_mandatory_api_token. Use the optional version.
319 thread_with_api_token(true) do
327 Link.where(uuid: 'just-verifying-my-api-token')
329 rescue ArvadosApiClient::NotLoggedInException
334 def ensure_current_user_is_admin
335 unless current_user and current_user.is_admin
336 @errors = ['Permission denied']
337 self.render_error status: 401
341 def check_user_agreements
342 if current_user && !current_user.is_active && current_user.is_invited
343 signatures = UserAgreement.signatures
344 @signed_ua_uuids = UserAgreement.signatures.map &:head_uuid
345 @required_user_agreements = UserAgreement.all.map do |ua|
346 if not @signed_ua_uuids.index ua.uuid
347 Collection.find(ua.uuid)
350 if @required_user_agreements.empty?
351 # No agreements to sign. Perhaps we just need to ask?
352 current_user.activate
353 if !current_user.is_active
354 logger.warn "#{current_user.uuid.inspect}: " +
355 "No user agreements to sign, but activate failed!"
358 if !current_user.is_active
359 render 'user_agreements/index'
366 return Rails.configuration.arvados_theme
369 @@notification_tests = []
371 @@notification_tests.push lambda { |controller, current_user|
372 AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
375 return lambda { |view|
376 view.render partial: 'notifications/ssh_key_notification'
380 #@@notification_tests.push lambda { |controller, current_user|
381 # Job.limit(1).where(created_by: current_user.uuid).each do
384 # return lambda { |view|
385 # view.render partial: 'notifications/jobs_notification'
389 @@notification_tests.push lambda { |controller, current_user|
390 Collection.limit(1).where(created_by: current_user.uuid).each do
393 return lambda { |view|
394 view.render partial: 'notifications/collections_notification'
398 @@notification_tests.push lambda { |controller, current_user|
399 PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
402 return lambda { |view|
403 view.render partial: 'notifications/pipelines_notification'
408 @my_top_level_folders = lambda do
409 @top_level_folders ||= Group.
410 filter([['group_class','=','folder'],
411 ['owner_uuid','=',current_user.uuid]]).
412 sort_by { |x| x.name || '' }
416 def check_user_notifications
417 @notification_count = 0
421 @showallalerts = false
422 @@notification_tests.each do |t|
423 a = t.call(self, current_user)
425 @notification_count += 1
426 @notifications.push a
431 if @notification_count == 0
432 @notification_count = ''