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 }
97 return render_not_found("object not found")
100 f.json { render json: @object.attributes.merge(href: url_for(@object)) }
102 if request.method == 'GET'
105 redirect_to params[:return_to] || @object
114 return render_not_found("object not found")
119 @object = model_class.new
123 @updates ||= params[@object.class.to_s.underscore.singularize.to_sym]
124 @updates.keys.each do |attr|
125 if @object.send(attr).is_a? Hash
126 if @updates[attr].is_a? String
127 @updates[attr] = Oj.load @updates[attr]
129 if params[:merge] || params["merge_#{attr}".to_sym]
130 # Merge provided Hash with current Hash, instead of
132 @updates[attr] = @object.send(attr).with_indifferent_access.
133 deep_merge(@updates[attr].with_indifferent_access)
137 if @object.update_attributes @updates
140 self.render_error status: 422
145 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
146 @new_resource_attrs ||= {}
147 @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
148 @object ||= model_class.new @new_resource_attrs
156 f.json { render json: @object }
158 redirect_to(params[:return_to] || :back)
163 self.render_error status: 422
168 if Thread.current[:arvados_api_token]
169 Thread.current[:user] ||= User.current
171 logger.error "No API token in Thread"
177 controller_name.classify.constantize
180 def breadcrumb_page_name
181 (@breadcrumb_page_name ||
182 (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
191 %w(Attributes Metadata JSON API)
196 def redirect_to_login
199 if request.method == 'GET'
200 redirect_to arvados_api_client.arvados_login_url(return_to: request.url)
202 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."
207 @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.']
208 self.render_error status: 422
211 false # For convenience to return from callbacks
214 def using_specific_api_token(api_token)
216 [:arvados_api_token, :user].each do |key|
217 start_values[key] = Thread.current[key]
219 Thread.current[:arvados_api_token] = api_token
220 Thread.current[:user] = nil
224 start_values.each_key { |key| Thread.current[key] = start_values[key] }
228 def find_object_by_uuid
229 if params[:id] and params[:id].match /\D/
230 params[:uuid] = params.delete :id
234 elsif params[:uuid].is_a? String
235 if params[:uuid].empty?
238 @object = model_class.find(params[:uuid])
241 @object = model_class.where(uuid: params[:uuid]).first
246 Thread.current[:arvados_api_token] = nil
247 Thread.current[:user] = nil
248 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
250 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
253 def thread_with_api_token(login_optional = false)
255 try_redirect_to_login = true
256 if params[:api_token]
257 try_redirect_to_login = false
258 Thread.current[:arvados_api_token] = params[:api_token]
259 # Before copying the token into session[], do a simple API
260 # call to verify its authenticity.
262 session[:arvados_api_token] = params[:api_token]
263 if !request.format.json? and request.method == 'GET'
264 # Repeat this request with api_token in the (new) session
265 # cookie instead of the query string. This prevents API
266 # tokens from appearing in (and being inadvisedly copied
267 # and pasted from) browser Location bars.
268 redirect_to request.fullpath.sub(%r{([&\?]api_token=)[^&\?]*}, '')
273 @errors = ['Invalid API token']
274 self.render_error status: 401
276 elsif session[:arvados_api_token]
277 # In this case, the token must have already verified at some
278 # point, but it might have been revoked since. We'll try
279 # using it, and catch the exception if it doesn't work.
280 try_redirect_to_login = false
281 Thread.current[:arvados_api_token] = session[:arvados_api_token]
284 rescue ArvadosApiClient::NotLoggedInException
285 try_redirect_to_login = true
288 logger.debug "No token received, session is #{session.inspect}"
290 if try_redirect_to_login
291 unless login_optional
294 # login is optional for this route so go on to the regular controller
295 Thread.current[:arvados_api_token] = nil
300 # Remove token in case this Thread is used for anything else.
301 Thread.current[:arvados_api_token] = nil
305 def thread_with_mandatory_api_token
306 thread_with_api_token do
311 # This runs after thread_with_mandatory_api_token in the filter chain.
312 def thread_with_optional_api_token
313 if Thread.current[:arvados_api_token]
314 # We are already inside thread_with_mandatory_api_token.
317 # We skipped thread_with_mandatory_api_token. Use the optional version.
318 thread_with_api_token(true) do
326 Link.where(uuid: 'just-verifying-my-api-token')
328 rescue ArvadosApiClient::NotLoggedInException
333 def ensure_current_user_is_admin
334 unless current_user and current_user.is_admin
335 @errors = ['Permission denied']
336 self.render_error status: 401
340 def check_user_agreements
341 if current_user && !current_user.is_active && current_user.is_invited
342 signatures = UserAgreement.signatures
343 @signed_ua_uuids = UserAgreement.signatures.map &:head_uuid
344 @required_user_agreements = UserAgreement.all.map do |ua|
345 if not @signed_ua_uuids.index ua.uuid
346 Collection.find(ua.uuid)
349 if @required_user_agreements.empty?
350 # No agreements to sign. Perhaps we just need to ask?
351 current_user.activate
352 if !current_user.is_active
353 logger.warn "#{current_user.uuid.inspect}: " +
354 "No user agreements to sign, but activate failed!"
357 if !current_user.is_active
358 render 'user_agreements/index'
365 return Rails.configuration.arvados_theme
368 @@notification_tests = []
370 @@notification_tests.push lambda { |controller, current_user|
371 AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
374 return lambda { |view|
375 view.render partial: 'notifications/ssh_key_notification'
379 #@@notification_tests.push lambda { |controller, current_user|
380 # Job.limit(1).where(created_by: current_user.uuid).each do
383 # return lambda { |view|
384 # view.render partial: 'notifications/jobs_notification'
388 @@notification_tests.push lambda { |controller, current_user|
389 Collection.limit(1).where(created_by: current_user.uuid).each do
392 return lambda { |view|
393 view.render partial: 'notifications/collections_notification'
397 @@notification_tests.push lambda { |controller, current_user|
398 PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
401 return lambda { |view|
402 view.render partial: 'notifications/pipelines_notification'
406 def check_user_notifications
407 @notification_count = 0
411 @showallalerts = false
412 @@notification_tests.each do |t|
413 a = t.call(self, current_user)
415 @notification_count += 1
416 @notifications.push a
421 if @notification_count == 0
422 @notification_count = ''
426 helper_method :my_folders
428 return @my_folders if @my_folders
431 Group.filter([['group_class','=','folder']]).each do |g|
432 root_of[g.uuid] = g.owner_uuid
438 root_of = root_of.each_with_object({}) do |(child, parent), h|
440 h[child] = root_of[parent]
447 @my_folders = @my_folders.select do |g|
448 root_of[g.uuid] == current_user.uuid