1 class ApplicationController < ActionController::Base
2 ERROR_ACTIONS = [:render_exception, :render_not_found]
3 respond_to :html, :json, :js
5 around_filter :thread_clear
6 around_filter :thread_with_mandatory_api_token, :except => [:render_exception, :render_not_found]
7 around_filter :thread_with_optional_api_token
8 before_filter :find_object_by_uuid, :except => [:index] + ERROR_ACTIONS
9 before_filter :check_user_agreements, :except => ERROR_ACTIONS
10 before_filter :check_user_notifications, :except => ERROR_ACTIONS
11 before_filter :check_my_folders, :except => ERROR_ACTIONS
15 rescue_from Exception,
16 :with => :render_exception
17 rescue_from ActiveRecord::RecordNotFound,
18 :with => :render_not_found
19 rescue_from ActionController::RoutingError,
20 :with => :render_not_found
21 rescue_from ActionController::UnknownController,
22 :with => :render_not_found
23 rescue_from ::AbstractController::ActionNotFound,
24 :with => :render_not_found
27 def unprocessable(message=nil)
30 @errors << message if message
31 render_error status: 422
34 def render_error(opts)
35 opts = {status: 500}.merge opts
37 # json must come before html here, so it gets used as the
38 # default format when js is requested by the client. This lets
39 # ajax:error callback parse the response correctly, even though
41 f.json { render opts.merge(json: {success: false, errors: @errors}) }
42 f.html { render opts.merge(controller: 'application', action: 'error') }
46 def render_exception(e)
47 logger.error e.inspect
48 logger.error e.backtrace.collect { |x| x + "\n" }.join('') if e.backtrace
49 if @object.andand.errors.andand.full_messages.andand.any?
50 @errors = @object.errors.full_messages
54 self.render_error status: 422
57 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
58 logger.error e.inspect
59 @errors = ["Path not found"]
60 self.render_error status: 404
65 limit = params[:limit].to_i
71 offset = params[:offset].to_i
77 filters = params[:filters]
78 if filters.is_a? String
79 filters = Oj.load filters
85 @objects ||= model_class.filter(filters).limit(limit).offset(offset).all
87 f.json { render json: @objects }
95 return render_not_found("object not found")
98 f.json { render json: @object }
100 if request.method == 'GET'
103 redirect_to params[:return_to] || @object
112 return render_not_found("object not found")
117 @object = model_class.new
121 updates = params[@object.class.to_s.underscore.singularize.to_sym]
122 updates.keys.each do |attr|
123 if @object.send(attr).is_a? Hash
124 if updates[attr].is_a? String
125 updates[attr] = Oj.load updates[attr]
127 if params[:merge] || params["merge_#{attr}".to_sym]
128 # Merge provided Hash with current Hash, instead of
130 updates[attr] = @object.send(attr).with_indifferent_access.
131 deep_merge(updates[attr].with_indifferent_access)
135 if @object.update_attributes updates
138 self.render_error status: 422
143 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
144 @new_resource_attrs ||= {}
145 @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
146 @object ||= model_class.new @new_resource_attrs
150 f.json { render json: @object }
152 redirect_to(params[:return_to] || @object)
161 f.json { render json: @object }
163 redirect_to(params[:return_to] || :back)
168 self.render_error status: 422
173 if Thread.current[:arvados_api_token]
174 Thread.current[:user] ||= User.current
176 logger.error "No API token in Thread"
182 controller_name.classify.constantize
185 def breadcrumb_page_name
186 (@breadcrumb_page_name ||
187 (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
196 %w(Attributes Metadata JSON API)
201 def find_object_by_uuid
202 if params[:id] and params[:id].match /\D/
203 params[:uuid] = params.delete :id
207 elsif params[:uuid].is_a? String
208 if params[:uuid].empty?
211 @object = model_class.find(params[:uuid])
214 @object = model_class.where(uuid: params[:uuid]).first
219 Thread.current[:arvados_api_token] = nil
220 Thread.current[:user] = nil
221 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
223 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
226 def thread_with_api_token(login_optional = false)
228 try_redirect_to_login = true
229 if params[:api_token]
230 try_redirect_to_login = false
231 Thread.current[:arvados_api_token] = params[:api_token]
232 # Before copying the token into session[], do a simple API
233 # call to verify its authenticity.
235 session[:arvados_api_token] = params[:api_token]
236 if !request.format.json? and request.method == 'GET'
237 # Repeat this request with api_token in the (new) session
238 # cookie instead of the query string. This prevents API
239 # tokens from appearing in (and being inadvisedly copied
240 # and pasted from) browser Location bars.
241 redirect_to request.fullpath.sub(%r{([&\?]api_token=)[^&\?]*}, '')
246 @errors = ['Invalid API token']
247 self.render_error status: 401
249 elsif session[:arvados_api_token]
250 # In this case, the token must have already verified at some
251 # point, but it might have been revoked since. We'll try
252 # using it, and catch the exception if it doesn't work.
253 try_redirect_to_login = false
254 Thread.current[:arvados_api_token] = session[:arvados_api_token]
257 rescue ArvadosApiClient::NotLoggedInException
258 try_redirect_to_login = true
261 logger.debug "No token received, session is #{session.inspect}"
263 if try_redirect_to_login
264 unless login_optional
267 if request.method == 'GET'
268 redirect_to $arvados_api_client.arvados_login_url(return_to: request.url)
270 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."
275 @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.']
276 self.render_error status: 422
280 # login is optional for this route so go on to the regular controller
281 Thread.current[:arvados_api_token] = nil
286 # Remove token in case this Thread is used for anything else.
287 Thread.current[:arvados_api_token] = nil
291 def thread_with_mandatory_api_token
292 thread_with_api_token do
297 # This runs after thread_with_mandatory_api_token in the filter chain.
298 def thread_with_optional_api_token
299 if Thread.current[:arvados_api_token]
300 # We are already inside thread_with_mandatory_api_token.
303 # We skipped thread_with_mandatory_api_token. Use the optional version.
304 thread_with_api_token(true) do
312 Link.where(uuid: 'just-verifying-my-api-token')
314 rescue ArvadosApiClient::NotLoggedInException
319 def ensure_current_user_is_admin
320 unless current_user and current_user.is_admin
321 @errors = ['Permission denied']
322 self.render_error status: 401
326 def check_user_agreements
327 if current_user && !current_user.is_active && current_user.is_invited
328 signatures = UserAgreement.signatures
329 @signed_ua_uuids = UserAgreement.signatures.map &:head_uuid
330 @required_user_agreements = UserAgreement.all.map do |ua|
331 if not @signed_ua_uuids.index ua.uuid
332 Collection.find(ua.uuid)
335 if @required_user_agreements.empty?
336 # No agreements to sign. Perhaps we just need to ask?
337 current_user.activate
338 if !current_user.is_active
339 logger.warn "#{current_user.uuid.inspect}: " +
340 "No user agreements to sign, but activate failed!"
343 if !current_user.is_active
344 render 'user_agreements/index'
351 return Rails.configuration.arvados_theme
354 @@notification_tests = []
356 @@notification_tests.push lambda { |controller, current_user|
357 AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
360 return lambda { |view|
361 view.render partial: 'notifications/ssh_key_notification'
365 #@@notification_tests.push lambda { |controller, current_user|
366 # Job.limit(1).where(created_by: current_user.uuid).each do
369 # return lambda { |view|
370 # view.render partial: 'notifications/jobs_notification'
374 @@notification_tests.push lambda { |controller, current_user|
375 Collection.limit(1).where(created_by: current_user.uuid).each do
378 return lambda { |view|
379 view.render partial: 'notifications/collections_notification'
383 @@notification_tests.push lambda { |controller, current_user|
384 PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
387 return lambda { |view|
388 view.render partial: 'notifications/pipelines_notification'
393 @my_top_level_folders = lambda do
394 @top_level_folders ||= Group.
395 filter([['group_class','=','folder'],
396 ['owner_uuid','=',current_user.uuid]]).
401 def check_user_notifications
402 @notification_count = 0
406 @showallalerts = false
407 @@notification_tests.each do |t|
408 a = t.call(self, current_user)
410 @notification_count += 1
411 @notifications.push a
416 if @notification_count == 0
417 @notification_count = ''