1 class ApplicationController < ActionController::Base
2 include CurrentApiClient
3 include ThemesForRails::ActionController
7 around_filter :thread_with_auth_info, :except => [:render_error, :render_not_found]
9 before_filter :remote_ip
10 before_filter :require_auth_scope_all, :except => :render_not_found
11 before_filter :catch_redirect_hint
13 before_filter :find_object_by_uuid, :except => [:index, :create,
16 before_filter :load_limit_offset_order_params, only: [:index, :owned_items]
17 before_filter :load_where_param, only: [:index, :owned_items]
18 before_filter :load_filters_param, only: [:index, :owned_items]
19 before_filter :find_objects_for_index, :only => :index
20 before_filter :reload_object_before_update, :only => :update
21 before_filter :render_404_if_no_object, except: [:index, :create,
27 attr_accessor :resource_attrs
33 if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
34 @objects.each(&:eager_load_associations)
40 render json: @object.as_api_response
44 @object = model_class.new resource_attrs
50 attrs_to_update = resource_attrs.reject { |k,v|
51 [:kind, :etag, :href].index k
53 @object.update_attributes! attrs_to_update
62 def self._owned_items_requires_parameters
63 _index_requires_parameters.
66 type: 'boolean', required: false, default: false
75 # We stuffed params[:uuid] into @where in find_object_by_uuid,
76 # but we don't want it there any more.
79 # Trick apply_where_limit_order_params into applying suitable
80 # per-table values. *_all are the real ones we'll apply to the
86 ArvadosModel.descendants.
87 reject(&:abstract_class?).
91 # We might expect klass==Link etc. here, but we would be
92 # disappointed: when Rails reloads model classes, we get two
93 # distinct classes called Link which do not equal each
94 # other. But we can still rely on klass.to_s to be "Link".
95 when 'ApiClientAuthorization'
98 @objects = klass.readable_by(current_user)
99 cond_sql = "#{klass.table_name}.owner_uuid = ?"
100 cond_params = [@object.uuid]
101 if params[:include_managed]
103 joins("LEFT JOIN links mng_links"\
104 " ON mng_links.link_class=#{klass.sanitize 'permission'}"\
105 " AND mng_links.name=#{klass.sanitize 'can_manage'}"\
106 " AND mng_links.tail_uuid=#{klass.sanitize @object.uuid}"\
107 " AND mng_links.head_uuid=#{klass.table_name}.uuid")
108 cond_sql += " OR mng_links.uuid IS NOT NULL"
110 @objects = @objects.where(cond_sql, *cond_params)
111 @limit = limit_all - all_objects.count
112 apply_where_limit_order_params
113 items_available = @objects.
114 except(:limit).except(:offset).
115 count(:id, distinct: true)
116 all_available += items_available
117 @offset = [@offset - items_available, 0].max
119 all_objects += @objects.to_a
122 @objects = all_objects || []
124 :kind => "arvados#objectList",
127 :offset => offset_all,
129 :items_available => all_available,
130 :items => @objects.as_api_response(nil)
132 render json: @object_list
135 def catch_redirect_hint
137 if params.has_key?('redirect_to') then
138 session[:redirect_to] = params[:redirect_to]
144 rescue_from Exception,
145 :with => :render_error
146 rescue_from ActiveRecord::RecordNotFound,
147 :with => :render_not_found
148 rescue_from ActionController::RoutingError,
149 :with => :render_not_found
150 rescue_from ActionController::UnknownController,
151 :with => :render_not_found
152 rescue_from AbstractController::ActionNotFound,
153 :with => :render_not_found
154 rescue_from ArvadosModel::PermissionDeniedError,
155 :with => :render_error
158 def render_404_if_no_object
159 render_not_found "Object not found" if !@object
163 logger.error e.inspect
164 if e.respond_to? :backtrace and e.backtrace
165 logger.error e.backtrace.collect { |x| x + "\n" }.join('')
167 if @object and @object.errors and @object.errors.full_messages and not @object.errors.full_messages.empty?
168 errors = @object.errors.full_messages
172 status = e.respond_to?(:http_status) ? e.http_status : 422
173 render json: { errors: errors }, status: status
176 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
177 logger.error e.inspect
178 render json: { errors: ["Path not found"] }, status: 404
184 if params[:where].nil? or params[:where] == ""
186 elsif params[:where].is_a? Hash
187 @where = params[:where]
188 elsif params[:where].is_a? String
190 @where = Oj.load(params[:where])
191 raise unless @where.is_a? Hash
193 raise ArgumentError.new("Could not parse \"where\" param as an object")
196 @where = @where.with_indifferent_access
199 def load_filters_param
201 if params[:filters].is_a? Array
202 @filters += params[:filters]
203 elsif params[:filters].is_a? String and !params[:filters].empty?
205 f = Oj.load params[:filters]
206 raise unless f.is_a? Array
209 raise ArgumentError.new("Could not parse \"filters\" param as an array")
214 def load_limit_offset_order_params
217 @limit = params[:limit].to_i
219 raise ArgumentError.new("Invalid value for limit parameter")
222 @limit = DEFAULT_LIMIT
227 @offset = params[:offset].to_i
229 raise ArgumentError.new("Invalid value for offset parameter")
237 params[:order].split(',').each do |order|
238 attr, direction = order.strip.split " "
240 if attr.match /^[a-z][_a-z0-9]+$/ and
241 model_class.columns.collect(&:name).index(attr) and
242 ['asc','desc'].index direction.downcase
243 @orders << "#{table_name}.#{attr} #{direction.downcase}"
248 @orders << "#{table_name}.modified_at desc"
252 def find_objects_for_index
253 @objects ||= model_class.readable_by(current_user)
254 apply_where_limit_order_params
257 def apply_where_limit_order_params
258 ar_table_name = @objects.table_name
259 if @filters.is_a? Array and @filters.any?
262 @filters.each do |attr, operator, operand|
263 if !model_class.searchable_columns(operator).index attr.to_s
264 raise ArgumentError.new("Invalid attribute '#{attr}' in condition")
266 case operator.downcase
267 when '=', '<', '<=', '>', '>=', 'like'
268 if operand.is_a? String
269 cond_out << "#{ar_table_name}.#{attr} #{operator} ?"
270 if (# any operator that operates on value rather than
272 operator.match(/[<=>]/) and
273 model_class.attribute_column(attr).type == :datetime)
274 operand = Time.parse operand
279 if operand.is_a? Array
280 cond_out << "#{ar_table_name}.#{attr} IN (?)"
284 operand = [operand] unless operand.is_a? Array
287 cl = ArvadosModel::kind_class op
289 cond << "#{ar_table_name}.#{attr} like ?"
290 param_out << cl.uuid_like_pattern
295 cond_out << cond.join(' OR ')
299 @objects = @objects.where(cond_out.join(' AND '), *param_out)
302 if @where.is_a? Hash and @where.any?
304 @where.each do |attr,value|
305 if attr.to_s == 'any'
306 if value.is_a?(Array) and
307 value.length == 2 and
308 value[0] == 'contains' then
310 model_class.searchable_columns('ilike').each do |column|
311 ilikes << "#{ar_table_name}.#{column} ilike ?"
312 conditions << "%#{value[1]}%"
315 conditions[0] << ' and (' + ilikes.join(' or ') + ')'
318 elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
319 model_class.columns.collect(&:name).index(attr.to_s)
321 conditions[0] << " and #{ar_table_name}.#{attr} is ?"
323 elsif value.is_a? Array
324 if value[0] == 'contains' and value.length == 2
325 conditions[0] << " and #{ar_table_name}.#{attr} like ?"
326 conditions << "%#{value[1]}%"
328 conditions[0] << " and #{ar_table_name}.#{attr} in (?)"
331 elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
332 conditions[0] << " and #{ar_table_name}.#{attr}=?"
334 elsif value.is_a? Hash
335 # Not quite the same thing as "equal?" but better than nothing?
338 conditions[0] << " and #{ar_table_name}.#{attr} ilike ?"
339 conditions << "%#{k}%#{v}%"
345 if conditions.length > 1
346 conditions[0].sub!(/^1=1 and /, '')
352 @objects = @objects.order(@orders.join ", ") if @orders.any?
353 @objects = @objects.limit(@limit)
354 @objects = @objects.offset(@offset)
358 return @attrs if @attrs
359 @attrs = params[resource_name]
360 if @attrs.is_a? String
361 @attrs = Oj.load @attrs, symbol_keys: true
363 unless @attrs.is_a? Hash
364 message = "No #{resource_name}"
365 if resource_name.index('_')
366 message << " (or #{resource_name.camelcase(:lower)})"
368 message << " hash provided with request"
369 raise ArgumentError.new(message)
371 %w(created_at modified_by_client_uuid modified_by_user_uuid modified_at).each do |x|
372 @attrs.delete x.to_sym
374 @attrs = @attrs.symbolize_keys if @attrs.is_a? HashWithIndifferentAccess
383 respond_to do |format|
385 render :json => { errors: ['Not logged in'] }.to_json, status: 401
388 redirect_to '/auth/joshid'
396 unless current_user and current_user.is_admin
397 render :json => { errors: ['Forbidden'] }.to_json, status: 403
401 def require_auth_scope_all
402 require_login and require_auth_scope(['all'])
405 def require_auth_scope(ok_scopes)
406 unless current_api_client_auth_has_scope(ok_scopes)
407 render :json => { errors: ['Forbidden'] }.to_json, status: 403
411 def thread_with_auth_info
412 Thread.current[:request_starttime] = Time.now
413 Thread.current[:api_url_base] = root_url.sub(/\/$/,'') + '/arvados/v1'
417 api_client_auth = nil
419 params[:api_token] ||
420 params[:oauth_token] ||
421 request.headers["Authorization"].andand.match(/OAuth2 ([a-z0-9]+)/).andand[1]
423 api_client_auth = ApiClientAuthorization.
424 includes(:api_client, :user).
425 where('api_token=? and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', supplied_token).
427 if api_client_auth.andand.user
428 session[:user_id] = api_client_auth.user.id
429 session[:api_client_uuid] = api_client_auth.api_client.andand.uuid
430 session[:api_client_authorization_id] = api_client_auth.id
431 user = api_client_auth.user
432 api_client = api_client_auth.api_client
434 # Token seems valid, but points to a non-existent (deleted?) user.
435 api_client_auth = nil
437 elsif session[:user_id]
438 user = User.find(session[:user_id]) rescue nil
439 api_client = ApiClient.
440 where('uuid=?',session[:api_client_uuid]).
442 if session[:api_client_authorization_id] then
443 api_client_auth = ApiClientAuthorization.
444 find session[:api_client_authorization_id]
447 Thread.current[:api_client_ip_address] = remote_ip
448 Thread.current[:api_client_authorization] = api_client_auth
449 Thread.current[:api_client_uuid] = api_client.andand.uuid
450 Thread.current[:api_client] = api_client
451 Thread.current[:user] = user
453 api_client_auth.last_used_at = Time.now
454 api_client_auth.last_used_by_ip_address = remote_ip
455 api_client_auth.save validate: false
459 Thread.current[:api_client_ip_address] = nil
460 Thread.current[:api_client_authorization] = nil
461 Thread.current[:api_client_uuid] = nil
462 Thread.current[:api_client] = nil
463 Thread.current[:user] = nil
469 controller_name.classify.constantize
472 def resource_name # params[] key used by client
473 controller_name.singularize
480 def find_object_by_uuid
481 if params[:id] and params[:id].match /\D/
482 params[:uuid] = params.delete :id
484 @where = { uuid: params[:uuid] }
490 find_objects_for_index
491 @object = @objects.first
494 def reload_object_before_update
495 # This is necessary to prevent an ActiveRecord::ReadOnlyRecord
496 # error when updating an object which was retrieved using a join.
497 if @object.andand.readonly?
498 @object = model_class.find_by_uuid(@objects.first.uuid)
502 def self.accept_attribute_as_json(attr, force_class=nil)
503 before_filter lambda { accept_attribute_as_json attr, force_class }
505 accept_attribute_as_json :properties, Hash
506 accept_attribute_as_json :info, Hash
507 def accept_attribute_as_json(attr, force_class)
508 if params[resource_name] and resource_attrs.is_a? Hash
509 if resource_attrs[attr].is_a? String
510 resource_attrs[attr] = Oj.load(resource_attrs[attr],
512 if force_class and !resource_attrs[attr].is_a? force_class
513 raise TypeError.new("#{resource_name}[#{attr.to_s}] must be a #{force_class.to_s}")
515 elsif resource_attrs[attr].is_a? Hash
516 # Convert symbol keys to strings (in hashes provided by
518 resource_attrs[attr] = resource_attrs[attr].
519 with_indifferent_access.to_hash
526 :kind => "arvados##{(@response_resource_name || resource_name).camelize(:lower)}List",
531 :items => @objects.as_api_response(nil)
533 if @objects.respond_to? :except
534 @object_list[:items_available] = @objects.
535 except(:limit).except(:offset).
536 count(:id, distinct: true)
538 render json: @object_list
542 # Caveat: this is highly dependent on the proxy setup. YMMV.
543 if request.headers.has_key?('HTTP_X_REAL_IP') then
544 # We're behind a reverse proxy
545 @remote_ip = request.headers['HTTP_X_REAL_IP']
547 # Hopefully, we are not!
548 @remote_ip = request.env['REMOTE_ADDR']
552 def self._index_requires_parameters
554 filters: { type: 'array', required: false },
555 where: { type: 'object', required: false },
556 order: { type: 'string', required: false },
557 limit: { type: 'integer', required: false, default: DEFAULT_LIMIT },
558 offset: { type: 'integer', required: false, default: 0 },
562 def client_accepts_plain_text_stream
563 (request.headers['Accept'].split(' ') &
564 ['text/plain', '*/*']).count > 0
569 response = opts.first[:json]
570 if response.is_a?(Hash) &&
572 Thread.current[:request_starttime]
573 response[:_profile] = {
574 request_time: Time.now - Thread.current[:request_starttime]
582 return Rails.configuration.arvados_theme