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.attributes.merge(href: url_for(@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
154 f.json { render json: @object }
156 redirect_to(params[:return_to] || :back)
161 self.render_error status: 422
166 if Thread.current[:arvados_api_token]
167 Thread.current[:user] ||= User.current
169 logger.error "No API token in Thread"
175 controller_name.classify.constantize
178 def breadcrumb_page_name
179 (@breadcrumb_page_name ||
180 (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
189 %w(Attributes Metadata JSON API)
194 def find_object_by_uuid
195 if params[:id] and params[:id].match /\D/
196 params[:uuid] = params.delete :id
200 elsif params[:uuid].is_a? String
201 if params[:uuid].empty?
204 @object = model_class.find(params[:uuid])
207 @object = model_class.where(uuid: params[:uuid]).first
212 Thread.current[:arvados_api_token] = nil
213 Thread.current[:user] = nil
214 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
216 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
219 def thread_with_api_token(login_optional = false)
221 try_redirect_to_login = true
222 if params[:api_token]
223 try_redirect_to_login = false
224 Thread.current[:arvados_api_token] = params[:api_token]
225 # Before copying the token into session[], do a simple API
226 # call to verify its authenticity.
228 session[:arvados_api_token] = params[:api_token]
229 if !request.format.json? and request.method == 'GET'
230 # Repeat this request with api_token in the (new) session
231 # cookie instead of the query string. This prevents API
232 # tokens from appearing in (and being inadvisedly copied
233 # and pasted from) browser Location bars.
234 redirect_to request.fullpath.sub(%r{([&\?]api_token=)[^&\?]*}, '')
239 @errors = ['Invalid API token']
240 self.render_error status: 401
242 elsif session[:arvados_api_token]
243 # In this case, the token must have already verified at some
244 # point, but it might have been revoked since. We'll try
245 # using it, and catch the exception if it doesn't work.
246 try_redirect_to_login = false
247 Thread.current[:arvados_api_token] = session[:arvados_api_token]
250 rescue ArvadosApiClient::NotLoggedInException
251 try_redirect_to_login = true
254 logger.debug "No token received, session is #{session.inspect}"
256 if try_redirect_to_login
257 unless login_optional
260 if request.method == 'GET'
261 redirect_to $arvados_api_client.arvados_login_url(return_to: request.url)
263 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."
268 @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.']
269 self.render_error status: 422
273 # login is optional for this route so go on to the regular controller
274 Thread.current[:arvados_api_token] = nil
279 # Remove token in case this Thread is used for anything else.
280 Thread.current[:arvados_api_token] = nil
284 def thread_with_mandatory_api_token
285 thread_with_api_token do
290 # This runs after thread_with_mandatory_api_token in the filter chain.
291 def thread_with_optional_api_token
292 if Thread.current[:arvados_api_token]
293 # We are already inside thread_with_mandatory_api_token.
296 # We skipped thread_with_mandatory_api_token. Use the optional version.
297 thread_with_api_token(true) do
305 Link.where(uuid: 'just-verifying-my-api-token')
307 rescue ArvadosApiClient::NotLoggedInException
312 def ensure_current_user_is_admin
313 unless current_user and current_user.is_admin
314 @errors = ['Permission denied']
315 self.render_error status: 401
319 def check_user_agreements
320 if current_user && !current_user.is_active && current_user.is_invited
321 signatures = UserAgreement.signatures
322 @signed_ua_uuids = UserAgreement.signatures.map &:head_uuid
323 @required_user_agreements = UserAgreement.all.map do |ua|
324 if not @signed_ua_uuids.index ua.uuid
325 Collection.find(ua.uuid)
328 if @required_user_agreements.empty?
329 # No agreements to sign. Perhaps we just need to ask?
330 current_user.activate
331 if !current_user.is_active
332 logger.warn "#{current_user.uuid.inspect}: " +
333 "No user agreements to sign, but activate failed!"
336 if !current_user.is_active
337 render 'user_agreements/index'
344 return Rails.configuration.arvados_theme
347 @@notification_tests = []
349 @@notification_tests.push lambda { |controller, current_user|
350 AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
353 return lambda { |view|
354 view.render partial: 'notifications/ssh_key_notification'
358 #@@notification_tests.push lambda { |controller, current_user|
359 # Job.limit(1).where(created_by: current_user.uuid).each do
362 # return lambda { |view|
363 # view.render partial: 'notifications/jobs_notification'
367 @@notification_tests.push lambda { |controller, current_user|
368 Collection.limit(1).where(created_by: current_user.uuid).each do
371 return lambda { |view|
372 view.render partial: 'notifications/collections_notification'
376 @@notification_tests.push lambda { |controller, current_user|
377 PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
380 return lambda { |view|
381 view.render partial: 'notifications/pipelines_notification'
386 @my_top_level_folders = lambda do
387 @top_level_folders ||= Group.
388 filter([['group_class','=','folder'],
389 ['owner_uuid','=',current_user.uuid]]).
390 sort_by { |x| x.name || '' }
394 def check_user_notifications
395 @notification_count = 0
399 @showallalerts = false
400 @@notification_tests.each do |t|
401 a = t.call(self, current_user)
403 @notification_count += 1
404 @notifications.push a
409 if @notification_count == 0
410 @notification_count = ''