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, :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 # Trick apply_where_limit_order_params into applying suitable
76 # per-table values. *_all are the real ones we'll apply to the
82 ArvadosModel.descendants.
83 reject(&:abstract_class?).
87 # We might expect klass==Link etc. here, but we would be
88 # disappointed: when Rails reloads model classes, we get two
89 # distinct classes called Link which do not equal each
90 # other. But we can still rely on klass.to_s to be "Link".
91 when 'ApiClientAuthorization'
94 @objects = klass.readable_by(current_user)
95 cond_sql = "#{klass.table_name}.owner_uuid = ?"
96 cond_params = [@object.uuid]
97 if params[:include_linked]
99 joins("LEFT JOIN links mng_links"\
100 " ON mng_links.link_class=#{klass.sanitize 'permission'}"\
101 " AND mng_links.name=#{klass.sanitize 'can_manage'}"\
102 " AND mng_links.tail_uuid=#{klass.sanitize @object.uuid}"\
103 " AND mng_links.head_uuid=#{klass.table_name}.uuid")
104 cond_sql += " OR mng_links.uuid IS NOT NULL"
106 @objects = @objects.where(cond_sql, *cond_params).order(:uuid)
107 @limit = limit_all - all_objects.count
108 apply_where_limit_order_params
109 items_available = @objects.
110 except(:limit).except(:offset).
111 count(:id, distinct: true)
112 all_available += items_available
113 @offset = [@offset - items_available, 0].max
115 all_objects += @objects.to_a
118 @objects = all_objects || []
120 :kind => "arvados#objectList",
123 :offset => offset_all,
125 :items_available => all_available,
126 :items => @objects.as_api_response(nil)
128 render json: @object_list
131 def catch_redirect_hint
133 if params.has_key?('redirect_to') then
134 session[:redirect_to] = params[:redirect_to]
140 rescue_from Exception,
141 :with => :render_error
142 rescue_from ActiveRecord::RecordNotFound,
143 :with => :render_not_found
144 rescue_from ActionController::RoutingError,
145 :with => :render_not_found
146 rescue_from ActionController::UnknownController,
147 :with => :render_not_found
148 rescue_from AbstractController::ActionNotFound,
149 :with => :render_not_found
150 rescue_from ArvadosModel::PermissionDeniedError,
151 :with => :render_error
154 def render_404_if_no_object
155 render_not_found "Object not found" if !@object
159 logger.error e.inspect
160 if e.respond_to? :backtrace and e.backtrace
161 logger.error e.backtrace.collect { |x| x + "\n" }.join('')
163 if @object and @object.errors and @object.errors.full_messages and not @object.errors.full_messages.empty?
164 errors = @object.errors.full_messages
168 status = e.respond_to?(:http_status) ? e.http_status : 422
169 render json: { errors: errors }, status: status
172 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
173 logger.error e.inspect
174 render json: { errors: ["Path not found"] }, status: 404
180 if params[:where].nil? or params[:where] == ""
182 elsif params[:where].is_a? Hash
183 @where = params[:where]
184 elsif params[:where].is_a? String
186 @where = Oj.load(params[:where])
187 raise unless @where.is_a? Hash
189 raise ArgumentError.new("Could not parse \"where\" param as an object")
192 @where = @where.with_indifferent_access
195 def load_filters_param
197 if params[:filters].is_a? Array
198 @filters += params[:filters]
199 elsif params[:filters].is_a? String and !params[:filters].empty?
201 f = Oj.load params[:filters]
202 raise unless f.is_a? Array
205 raise ArgumentError.new("Could not parse \"filters\" param as an array")
211 ["#{table_name}.modified_at desc"]
214 def load_limit_offset_order_params
216 unless params[:limit].to_s.match(/^\d+$/)
217 raise ArgumentError.new("Invalid value for limit parameter")
219 @limit = params[:limit].to_i
221 @limit = DEFAULT_LIMIT
225 unless params[:offset].to_s.match(/^\d+$/)
226 raise ArgumentError.new("Invalid value for offset parameter")
228 @offset = params[:offset].to_i
235 params[:order].split(',').each do |order|
236 attr, direction = order.strip.split " "
238 if attr.match /^[a-z][_a-z0-9]+$/ and
239 model_class.columns.collect(&:name).index(attr) and
240 ['asc','desc'].index direction.downcase
241 @orders << "#{table_name}.#{attr} #{direction.downcase}"
246 @orders = default_orders
250 def find_objects_for_index
251 @objects ||= model_class.readable_by(current_user)
252 apply_where_limit_order_params
255 def apply_where_limit_order_params
256 ar_table_name = @objects.table_name
257 if @filters.is_a? Array and @filters.any?
260 @filters.each do |filter|
261 attr, operator, operand = filter
262 if !filter.is_a? Array
263 raise ArgumentError.new("Invalid element in filters array: #{filter.inspect} is not an array")
264 elsif !operator.is_a? String
265 raise ArgumentError.new("Invalid operator '#{operator}' (#{operator.class}) in filter")
266 elsif !model_class.searchable_columns(operator).index attr.to_s
267 raise ArgumentError.new("Invalid attribute '#{attr}' in filter")
269 case operator.downcase
270 when '=', '<', '<=', '>', '>=', 'like'
271 if operand.is_a? String
272 cond_out << "#{ar_table_name}.#{attr} #{operator} ?"
273 if (# any operator that operates on value rather than
275 operator.match(/[<=>]/) and
276 model_class.attribute_column(attr).type == :datetime)
277 operand = Time.parse operand
280 elsif operand.nil? and operator == '='
281 cond_out << "#{ar_table_name}.#{attr} is null"
283 raise ArgumentError.new("Invalid operand type '#{operand.class}' "\
284 "for '#{operator}' operator in filters")
287 if operand.is_a? Array
288 cond_out << "#{ar_table_name}.#{attr} IN (?)"
291 raise ArgumentError.new("Invalid operand type '#{operand.class}' "\
292 "for '#{operator}' operator in filters")
295 operand = [operand] unless operand.is_a? Array
298 cl = ArvadosModel::kind_class op
300 cond << "#{ar_table_name}.#{attr} like ?"
301 param_out << cl.uuid_like_pattern
306 cond_out << cond.join(' OR ')
310 @objects = @objects.where(cond_out.join(' AND '), *param_out)
313 if @where.is_a? Hash and @where.any?
315 @where.each do |attr,value|
316 if attr.to_s == 'any'
317 if value.is_a?(Array) and
318 value.length == 2 and
319 value[0] == 'contains' then
321 model_class.searchable_columns('ilike').each do |column|
322 # Including owner_uuid in an "any column" search will
323 # probably just return a lot of false positives.
324 next if column == 'owner_uuid'
325 ilikes << "#{ar_table_name}.#{column} ilike ?"
326 conditions << "%#{value[1]}%"
329 conditions[0] << ' and (' + ilikes.join(' or ') + ')'
332 elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
333 model_class.columns.collect(&:name).index(attr.to_s)
335 conditions[0] << " and #{ar_table_name}.#{attr} is ?"
337 elsif value.is_a? Array
338 if value[0] == 'contains' and value.length == 2
339 conditions[0] << " and #{ar_table_name}.#{attr} like ?"
340 conditions << "%#{value[1]}%"
342 conditions[0] << " and #{ar_table_name}.#{attr} in (?)"
345 elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
346 conditions[0] << " and #{ar_table_name}.#{attr}=?"
348 elsif value.is_a? Hash
349 # Not quite the same thing as "equal?" but better than nothing?
352 conditions[0] << " and #{ar_table_name}.#{attr} ilike ?"
353 conditions << "%#{k}%#{v}%"
359 if conditions.length > 1
360 conditions[0].sub!(/^1=1 and /, '')
366 @objects = @objects.order(@orders.join ", ") if @orders.any?
367 @objects = @objects.limit(@limit)
368 @objects = @objects.offset(@offset)
372 return @attrs if @attrs
373 @attrs = params[resource_name]
374 if @attrs.is_a? String
375 @attrs = Oj.load @attrs, symbol_keys: true
377 unless @attrs.is_a? Hash
378 message = "No #{resource_name}"
379 if resource_name.index('_')
380 message << " (or #{resource_name.camelcase(:lower)})"
382 message << " hash provided with request"
383 raise ArgumentError.new(message)
385 %w(created_at modified_by_client_uuid modified_by_user_uuid modified_at).each do |x|
386 @attrs.delete x.to_sym
388 @attrs = @attrs.symbolize_keys if @attrs.is_a? HashWithIndifferentAccess
397 respond_to do |format|
399 render :json => { errors: ['Not logged in'] }.to_json, status: 401
402 redirect_to '/auth/joshid'
410 unless current_user and current_user.is_admin
411 render :json => { errors: ['Forbidden'] }.to_json, status: 403
415 def require_auth_scope
416 return false unless require_login
417 unless current_api_client_auth_has_scope("#{request.method} #{request.path}")
418 render :json => { errors: ['Forbidden'] }.to_json, status: 403
422 def thread_with_auth_info
423 Thread.current[:request_starttime] = Time.now
424 Thread.current[:api_url_base] = root_url.sub(/\/$/,'') + '/arvados/v1'
428 api_client_auth = nil
430 params[:api_token] ||
431 params[:oauth_token] ||
432 request.headers["Authorization"].andand.match(/OAuth2 ([a-z0-9]+)/).andand[1]
434 api_client_auth = ApiClientAuthorization.
435 includes(:api_client, :user).
436 where('api_token=? and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', supplied_token).
438 if api_client_auth.andand.user
439 session[:user_id] = api_client_auth.user.id
440 session[:api_client_uuid] = api_client_auth.api_client.andand.uuid
441 session[:api_client_authorization_id] = api_client_auth.id
442 user = api_client_auth.user
443 api_client = api_client_auth.api_client
445 # Token seems valid, but points to a non-existent (deleted?) user.
446 api_client_auth = nil
448 elsif session[:user_id]
449 user = User.find(session[:user_id]) rescue nil
450 api_client = ApiClient.
451 where('uuid=?',session[:api_client_uuid]).
453 if session[:api_client_authorization_id] then
454 api_client_auth = ApiClientAuthorization.
455 find session[:api_client_authorization_id]
458 Thread.current[:api_client_ip_address] = remote_ip
459 Thread.current[:api_client_authorization] = api_client_auth
460 Thread.current[:api_client_uuid] = api_client.andand.uuid
461 Thread.current[:api_client] = api_client
462 Thread.current[:user] = user
464 api_client_auth.last_used_at = Time.now
465 api_client_auth.last_used_by_ip_address = remote_ip
466 api_client_auth.save validate: false
470 Thread.current[:api_client_ip_address] = nil
471 Thread.current[:api_client_authorization] = nil
472 Thread.current[:api_client_uuid] = nil
473 Thread.current[:api_client] = nil
474 Thread.current[:user] = nil
480 controller_name.classify.constantize
483 def resource_name # params[] key used by client
484 controller_name.singularize
491 def find_object_by_uuid
492 if params[:id] and params[:id].match /\D/
493 params[:uuid] = params.delete :id
495 @where = { uuid: params[:uuid] }
501 find_objects_for_index
502 @object = @objects.first
505 def reload_object_before_update
506 # This is necessary to prevent an ActiveRecord::ReadOnlyRecord
507 # error when updating an object which was retrieved using a join.
508 if @object.andand.readonly?
509 @object = model_class.find_by_uuid(@objects.first.uuid)
513 def self.accept_attribute_as_json(attr, force_class=nil)
514 before_filter lambda { accept_attribute_as_json attr, force_class }
516 accept_attribute_as_json :properties, Hash
517 accept_attribute_as_json :info, Hash
518 def accept_attribute_as_json(attr, force_class)
519 if params[resource_name] and resource_attrs.is_a? Hash
520 if resource_attrs[attr].is_a? String
521 resource_attrs[attr] = Oj.load(resource_attrs[attr],
523 if force_class and !resource_attrs[attr].is_a? force_class
524 raise TypeError.new("#{resource_name}[#{attr.to_s}] must be a #{force_class.to_s}")
526 elsif resource_attrs[attr].is_a? Hash
527 # Convert symbol keys to strings (in hashes provided by
529 resource_attrs[attr] = resource_attrs[attr].
530 with_indifferent_access.to_hash
537 :kind => "arvados##{(@response_resource_name || resource_name).camelize(:lower)}List",
542 :items => @objects.as_api_response(nil)
544 if @objects.respond_to? :except
545 @object_list[:items_available] = @objects.
546 except(:limit).except(:offset).
547 count(:id, distinct: true)
549 render json: @object_list
553 # Caveat: this is highly dependent on the proxy setup. YMMV.
554 if request.headers.has_key?('HTTP_X_REAL_IP') then
555 # We're behind a reverse proxy
556 @remote_ip = request.headers['HTTP_X_REAL_IP']
558 # Hopefully, we are not!
559 @remote_ip = request.env['REMOTE_ADDR']
563 def self._index_requires_parameters
565 filters: { type: 'array', required: false },
566 where: { type: 'object', required: false },
567 order: { type: 'string', required: false },
568 limit: { type: 'integer', required: false, default: DEFAULT_LIMIT },
569 offset: { type: 'integer', required: false, default: 0 },
573 def client_accepts_plain_text_stream
574 (request.headers['Accept'].split(' ') &
575 ['text/plain', '*/*']).count > 0
580 response = opts.first[:json]
581 if response.is_a?(Hash) &&
583 Thread.current[:request_starttime]
584 response[:_profile] = {
585 request_time: Time.now - Thread.current[:request_starttime]
593 return Rails.configuration.arvados_theme