1 class ApplicationController < ActionController::Base
2 respond_to :html, :json, :js
4 around_filter :thread_clear
5 around_filter :thread_with_mandatory_api_token, :except => [:render_exception, :render_not_found]
6 around_filter :thread_with_optional_api_token
7 before_filter :find_object_by_uuid, :except => [:index, :render_exception, :render_not_found]
8 before_filter :check_user_agreements, :except => [:render_exception, :render_not_found]
9 before_filter :check_user_notifications, :except => [:render_exception, :render_not_found]
13 rescue_from Exception,
14 :with => :render_exception
15 rescue_from ActiveRecord::RecordNotFound,
16 :with => :render_not_found
17 rescue_from ActionController::RoutingError,
18 :with => :render_not_found
19 rescue_from ActionController::UnknownController,
20 :with => :render_not_found
21 rescue_from ::AbstractController::ActionNotFound,
22 :with => :render_not_found
25 def unprocessable(message=nil)
28 @errors << message if message
29 render_error status: 422
32 def render_error(opts)
33 opts = {status: 500}.merge opts
35 # json must come before html here, so it gets used as the
36 # default format when js is requested by the client. This lets
37 # ajax:error callback parse the response correctly, even though
39 f.json { render opts.merge(json: {success: false, errors: @errors}) }
40 f.html { render opts.merge(controller: 'application', action: 'error') }
44 def render_exception(e)
45 logger.error e.inspect
46 logger.error e.backtrace.collect { |x| x + "\n" }.join('') if e.backtrace
47 if @object.andand.errors.andand.full_messages.andand.any?
48 @errors = @object.errors.full_messages
52 self.render_error status: 422
55 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
56 logger.error e.inspect
57 @errors = ["Path not found"]
58 self.render_error status: 404
63 limit = params[:limit].to_i
69 offset = params[:offset].to_i
74 @objects ||= model_class.limit(limit).offset(offset).all
76 f.json { render json: @objects }
84 return render_not_found("object not found")
87 f.json { render json: @object }
89 if request.method == 'GET'
92 redirect_to params[:return_to] || @object
101 return render_not_found("object not found")
106 @object = model_class.new
110 updates = params[@object.class.to_s.underscore.singularize.to_sym]
111 updates.keys.each do |attr|
112 if @object.send(attr).is_a? Hash
113 if updates[attr].is_a? String
114 updates[attr] = Oj.load updates[attr]
116 if params[:merge] || params["merge_#{attr}".to_sym]
117 # Merge provided Hash with current Hash, instead of
119 updates[attr] = @object.send(attr).with_indifferent_access.
120 deep_merge(updates[attr].with_indifferent_access)
124 if @object.update_attributes updates
127 self.render_error status: 422
132 @object ||= model_class.new params[model_class.to_s.underscore.singularize]
136 f.json { render json: @object }
138 redirect_to(params[:return_to] || @object)
147 f.json { render json: @object }
149 redirect_to(params[:return_to] || :back)
154 self.render_error status: 422
159 if Thread.current[:arvados_api_token]
160 Thread.current[:user] ||= User.current
162 logger.error "No API token in Thread"
168 controller_name.classify.constantize
171 def breadcrumb_page_name
172 (@breadcrumb_page_name ||
173 (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
182 %w(Attributes Metadata JSON API)
187 def find_object_by_uuid
188 if params[:id] and params[:id].match /\D/
189 params[:uuid] = params.delete :id
191 if params[:uuid].is_a? String
192 @object = model_class.find(params[:uuid])
194 @object = model_class.where(uuid: params[:uuid]).first
199 Thread.current[:arvados_api_token] = nil
200 Thread.current[:user] = nil
201 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
203 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
206 def thread_with_api_token(login_optional = false)
208 try_redirect_to_login = true
209 if params[:api_token]
210 try_redirect_to_login = false
211 Thread.current[:arvados_api_token] = params[:api_token]
212 # Before copying the token into session[], do a simple API
213 # call to verify its authenticity.
215 session[:arvados_api_token] = params[:api_token]
216 if !request.format.json? and request.method == 'GET'
217 # Repeat this request with api_token in the (new) session
218 # cookie instead of the query string. This prevents API
219 # tokens from appearing in (and being inadvisedly copied
220 # and pasted from) browser Location bars.
221 redirect_to request.fullpath.sub(%r{([&\?]api_token=)[^&\?]*}, '')
226 @errors = ['Invalid API token']
227 self.render_error status: 401
229 elsif session[:arvados_api_token]
230 # In this case, the token must have already verified at some
231 # point, but it might have been revoked since. We'll try
232 # using it, and catch the exception if it doesn't work.
233 try_redirect_to_login = false
234 Thread.current[:arvados_api_token] = session[:arvados_api_token]
237 rescue ArvadosApiClient::NotLoggedInException
238 try_redirect_to_login = true
241 logger.debug "No token received, session is #{session.inspect}"
243 if try_redirect_to_login
244 unless login_optional
247 if request.method == 'GET'
248 redirect_to $arvados_api_client.arvados_login_url(return_to: request.url)
250 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."
255 @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.']
256 self.render_error status: 422
260 # login is optional for this route so go on to the regular controller
261 Thread.current[:arvados_api_token] = nil
266 # Remove token in case this Thread is used for anything else.
267 Thread.current[:arvados_api_token] = nil
271 def thread_with_mandatory_api_token
272 thread_with_api_token do
277 # This runs after thread_with_mandatory_api_token in the filter chain.
278 def thread_with_optional_api_token
279 if Thread.current[:arvados_api_token]
280 # We are already inside thread_with_mandatory_api_token.
283 # We skipped thread_with_mandatory_api_token. Use the optional version.
284 thread_with_api_token(true) do
292 Link.where(uuid: 'just-verifying-my-api-token')
294 rescue ArvadosApiClient::NotLoggedInException
299 def ensure_current_user_is_admin
300 unless current_user and current_user.is_admin
301 @errors = ['Permission denied']
302 self.render_error status: 401
306 def check_user_agreements
307 if current_user && !current_user.is_active && current_user.is_invited
308 signatures = UserAgreement.signatures
309 @signed_ua_uuids = UserAgreement.signatures.map &:head_uuid
310 @required_user_agreements = UserAgreement.all.map do |ua|
311 if not @signed_ua_uuids.index ua.uuid
312 Collection.find(ua.uuid)
315 if @required_user_agreements.empty?
316 # No agreements to sign. Perhaps we just need to ask?
317 current_user.activate
318 if !current_user.is_active
319 logger.warn "#{current_user.uuid.inspect}: " +
320 "No user agreements to sign, but activate failed!"
323 if !current_user.is_active
324 render 'user_agreements/index'
331 return Rails.configuration.arvados_theme
334 @@notification_tests = []
336 @@notification_tests.push lambda { |controller, current_user|
337 AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
340 return lambda { |view|
341 view.render partial: 'notifications/ssh_key_notification'
345 #@@notification_tests.push lambda { |controller, current_user|
346 # Job.limit(1).where(created_by: current_user.uuid).each do
349 # return lambda { |view|
350 # view.render partial: 'notifications/jobs_notification'
354 @@notification_tests.push lambda { |controller, current_user|
355 Collection.limit(1).where(created_by: current_user.uuid).each do
358 return lambda { |view|
359 view.render partial: 'notifications/collections_notification'
363 @@notification_tests.push lambda { |controller, current_user|
364 PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
367 return lambda { |view|
368 view.render partial: 'notifications/pipelines_notification'
372 def check_user_notifications
373 @notification_count = 0
377 @showallalerts = false
378 @@notification_tests.each do |t|
379 a = t.call(self, current_user)
381 @notification_count += 1
382 @notifications.push a
387 if @notification_count == 0
388 @notification_count = ''