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 :respond_with_json_by_default
10 before_filter :remote_ip
11 before_filter :require_auth_scope, :except => :render_not_found
12 before_filter :catch_redirect_hint
14 before_filter :find_object_by_uuid, :except => [:index, :create,
17 before_filter :load_limit_offset_order_params, only: [:index, :contents]
18 before_filter :load_where_param, only: [:index, :contents]
19 before_filter :load_filters_param, only: [:index, :contents]
20 before_filter :find_objects_for_index, :only => :index
21 before_filter :reload_object_before_update, :only => :update
22 before_filter :render_404_if_no_object, except: [:index, :create,
28 attr_accessor :resource_attrs
34 if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
35 @objects.each(&:eager_load_associations)
41 render json: @object.as_api_response
45 @object = model_class.new resource_attrs
51 attrs_to_update = resource_attrs.reject { |k,v|
52 [:kind, :etag, :href].index k
54 @object.update_attributes! attrs_to_update
63 def self._contents_requires_parameters
64 _index_requires_parameters.
67 type: 'boolean', required: false, default: false
76 # Trick apply_where_limit_order_params into applying suitable
77 # per-table values. *_all are the real ones we'll apply to the
83 ArvadosModel.descendants.
84 reject(&:abstract_class?).
88 # We might expect klass==Link etc. here, but we would be
89 # disappointed: when Rails reloads model classes, we get two
90 # distinct classes called Link which do not equal each
91 # other. But we can still rely on klass.to_s to be "Link".
92 when 'ApiClientAuthorization', 'UserAgreement', 'Link'
95 @objects = klass.readable_by(current_user)
96 cond_sql = "#{klass.table_name}.owner_uuid = ?"
97 cond_params = [@object.uuid]
98 if params[:include_linked]
99 cond_sql += " OR #{klass.table_name}.uuid IN (SELECT head_uuid FROM links WHERE link_class=#{klass.sanitize 'name'} AND links.tail_uuid=#{klass.sanitize @object.uuid})"
101 @objects = @objects.where(cond_sql, *cond_params).order("#{klass.table_name}.uuid")
102 @limit = limit_all - all_objects.count
103 apply_where_limit_order_params
104 items_available = @objects.
105 except(:limit).except(:offset).
106 count(:id, distinct: true)
107 all_available += items_available
108 @offset = [@offset - items_available, 0].max
110 all_objects += @objects.to_a
113 @objects = all_objects || []
114 @links = Link.where('link_class=? and owner_uuid=?'\
115 ' and owner_uuid=tail_uuid'\
116 ' and head_uuid in (?)',
119 @objects.collect(&:uuid))
121 :kind => "arvados#objectList",
124 :links => @links.as_api_response(nil),
125 :offset => offset_all,
127 :items_available => all_available,
128 :items => @objects.as_api_response(nil)
130 render json: @object_list
133 def catch_redirect_hint
135 if params.has_key?('redirect_to') then
136 session[:redirect_to] = params[:redirect_to]
142 rescue_from Exception,
143 :with => :render_error
144 rescue_from ActiveRecord::RecordNotFound,
145 :with => :render_not_found
146 rescue_from ActionController::RoutingError,
147 :with => :render_not_found
148 rescue_from ActionController::UnknownController,
149 :with => :render_not_found
150 rescue_from AbstractController::ActionNotFound,
151 :with => :render_not_found
152 rescue_from ArvadosModel::PermissionDeniedError,
153 :with => :render_error
156 def render_404_if_no_object
157 render_not_found "Object not found" if !@object
161 logger.error e.inspect
162 if e.respond_to? :backtrace and e.backtrace
163 logger.error e.backtrace.collect { |x| x + "\n" }.join('')
165 if @object and @object.errors and @object.errors.full_messages and not @object.errors.full_messages.empty?
166 errors = @object.errors.full_messages
170 status = e.respond_to?(:http_status) ? e.http_status : 422
171 render json: { errors: errors }, status: status
174 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
175 logger.error e.inspect
176 render json: { errors: ["Path not found"] }, status: 404
182 if params[:where].nil? or params[:where] == ""
184 elsif params[:where].is_a? Hash
185 @where = params[:where]
186 elsif params[:where].is_a? String
188 @where = Oj.load(params[:where])
189 raise unless @where.is_a? Hash
191 raise ArgumentError.new("Could not parse \"where\" param as an object")
194 @where = @where.with_indifferent_access
197 def load_filters_param
199 if params[:filters].is_a? Array
200 @filters += params[:filters]
201 elsif params[:filters].is_a? String and !params[:filters].empty?
203 f = Oj.load params[:filters]
204 raise unless f.is_a? Array
207 raise ArgumentError.new("Could not parse \"filters\" param as an array")
213 ["#{table_name}.modified_at desc"]
216 def load_limit_offset_order_params
218 unless params[:limit].to_s.match(/^\d+$/)
219 raise ArgumentError.new("Invalid value for limit parameter")
221 @limit = params[:limit].to_i
223 @limit = DEFAULT_LIMIT
227 unless params[:offset].to_s.match(/^\d+$/)
228 raise ArgumentError.new("Invalid value for offset parameter")
230 @offset = params[:offset].to_i
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 = default_orders
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 |filter|
263 attr, operator, operand = filter
264 if !filter.is_a? Array
265 raise ArgumentError.new("Invalid element in filters array: #{filter.inspect} is not an array")
266 elsif !operator.is_a? String
267 raise ArgumentError.new("Invalid operator '#{operator}' (#{operator.class}) in filter")
268 elsif !model_class.searchable_columns(operator).index attr.to_s
269 raise ArgumentError.new("Invalid attribute '#{attr}' in filter")
271 case operator.downcase
272 when '=', '<', '<=', '>', '>=', 'like'
273 if operand.is_a? String
274 cond_out << "#{ar_table_name}.#{attr} #{operator} ?"
275 if (# any operator that operates on value rather than
277 operator.match(/[<=>]/) and
278 model_class.attribute_column(attr).type == :datetime)
279 operand = Time.parse operand
282 elsif operand.nil? and operator == '='
283 cond_out << "#{ar_table_name}.#{attr} is null"
285 raise ArgumentError.new("Invalid operand type '#{operand.class}' "\
286 "for '#{operator}' operator in filters")
289 if operand.is_a? Array
290 cond_out << "#{ar_table_name}.#{attr} IN (?)"
293 raise ArgumentError.new("Invalid operand type '#{operand.class}' "\
294 "for '#{operator}' operator in filters")
297 operand = [operand] unless operand.is_a? Array
300 cl = ArvadosModel::kind_class op
302 cond << "#{ar_table_name}.#{attr} like ?"
303 param_out << cl.uuid_like_pattern
308 cond_out << cond.join(' OR ')
312 @objects = @objects.where(cond_out.join(' AND '), *param_out)
315 if @where.is_a? Hash and @where.any?
317 @where.each do |attr,value|
318 if attr.to_s == 'any'
319 if value.is_a?(Array) and
320 value.length == 2 and
321 value[0] == 'contains' then
323 model_class.searchable_columns('ilike').each do |column|
324 # Including owner_uuid in an "any column" search will
325 # probably just return a lot of false positives.
326 next if column == 'owner_uuid'
327 ilikes << "#{ar_table_name}.#{column} ilike ?"
328 conditions << "%#{value[1]}%"
331 conditions[0] << ' and (' + ilikes.join(' or ') + ')'
334 elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
335 model_class.columns.collect(&:name).index(attr.to_s)
337 conditions[0] << " and #{ar_table_name}.#{attr} is ?"
339 elsif value.is_a? Array
340 if value[0] == 'contains' and value.length == 2
341 conditions[0] << " and #{ar_table_name}.#{attr} like ?"
342 conditions << "%#{value[1]}%"
344 conditions[0] << " and #{ar_table_name}.#{attr} in (?)"
347 elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
348 conditions[0] << " and #{ar_table_name}.#{attr}=?"
350 elsif value.is_a? Hash
351 # Not quite the same thing as "equal?" but better than nothing?
354 conditions[0] << " and #{ar_table_name}.#{attr} ilike ?"
355 conditions << "%#{k}%#{v}%"
361 if conditions.length > 1
362 conditions[0].sub!(/^1=1 and /, '')
368 @objects = @objects.order(@orders.join ", ") if @orders.any?
369 @objects = @objects.limit(@limit)
370 @objects = @objects.offset(@offset)
374 return @attrs if @attrs
375 @attrs = params[resource_name]
376 if @attrs.is_a? String
377 @attrs = Oj.load @attrs, symbol_keys: true
379 unless @attrs.is_a? Hash
380 message = "No #{resource_name}"
381 if resource_name.index('_')
382 message << " (or #{resource_name.camelcase(:lower)})"
384 message << " hash provided with request"
385 raise ArgumentError.new(message)
387 %w(created_at modified_by_client_uuid modified_by_user_uuid modified_at).each do |x|
388 @attrs.delete x.to_sym
390 @attrs = @attrs.symbolize_keys if @attrs.is_a? HashWithIndifferentAccess
399 respond_to do |format|
401 render :json => { errors: ['Not logged in'] }.to_json, status: 401
404 redirect_to '/auth/joshid'
412 unless current_user and current_user.is_admin
413 render :json => { errors: ['Forbidden'] }.to_json, status: 403
417 def require_auth_scope
418 return false unless require_login
419 unless current_api_client_auth_has_scope("#{request.method} #{request.path}")
420 render :json => { errors: ['Forbidden'] }.to_json, status: 403
424 def thread_with_auth_info
425 Thread.current[:request_starttime] = Time.now
426 Thread.current[:api_url_base] = root_url.sub(/\/$/,'') + '/arvados/v1'
430 api_client_auth = nil
432 params[:api_token] ||
433 params[:oauth_token] ||
434 request.headers["Authorization"].andand.match(/OAuth2 ([a-z0-9]+)/).andand[1]
436 api_client_auth = ApiClientAuthorization.
437 includes(:api_client, :user).
438 where('api_token=? and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', supplied_token).
440 if api_client_auth.andand.user
441 session[:user_id] = api_client_auth.user.id
442 session[:api_client_uuid] = api_client_auth.api_client.andand.uuid
443 session[:api_client_authorization_id] = api_client_auth.id
444 user = api_client_auth.user
445 api_client = api_client_auth.api_client
447 # Token seems valid, but points to a non-existent (deleted?) user.
448 api_client_auth = nil
450 elsif session[:user_id]
451 user = User.find(session[:user_id]) rescue nil
452 api_client = ApiClient.
453 where('uuid=?',session[:api_client_uuid]).
455 if session[:api_client_authorization_id] then
456 api_client_auth = ApiClientAuthorization.
457 find session[:api_client_authorization_id]
460 Thread.current[:api_client_ip_address] = remote_ip
461 Thread.current[:api_client_authorization] = api_client_auth
462 Thread.current[:api_client_uuid] = api_client.andand.uuid
463 Thread.current[:api_client] = api_client
464 Thread.current[:user] = user
466 api_client_auth.last_used_at = Time.now
467 api_client_auth.last_used_by_ip_address = remote_ip
468 api_client_auth.save validate: false
472 Thread.current[:api_client_ip_address] = nil
473 Thread.current[:api_client_authorization] = nil
474 Thread.current[:api_client_uuid] = nil
475 Thread.current[:api_client] = nil
476 Thread.current[:user] = nil
481 def respond_with_json_by_default
482 html_index = request.accepts.index(Mime::HTML)
483 if html_index.nil? or request.accepts[0...html_index].include?(Mime::JSON)
484 request.format = :json
489 controller_name.classify.constantize
492 def resource_name # params[] key used by client
493 controller_name.singularize
500 def find_object_by_uuid
501 if params[:id] and params[:id].match /\D/
502 params[:uuid] = params.delete :id
504 @where = { uuid: params[:uuid] }
510 find_objects_for_index
511 @object = @objects.first
514 def reload_object_before_update
515 # This is necessary to prevent an ActiveRecord::ReadOnlyRecord
516 # error when updating an object which was retrieved using a join.
517 if @object.andand.readonly?
518 @object = model_class.find_by_uuid(@objects.first.uuid)
522 def self.accept_attribute_as_json(attr, force_class=nil)
523 before_filter lambda { accept_attribute_as_json attr, force_class }
525 accept_attribute_as_json :properties, Hash
526 accept_attribute_as_json :info, Hash
527 def accept_attribute_as_json(attr, force_class)
528 if params[resource_name] and resource_attrs.is_a? Hash
529 if resource_attrs[attr].is_a? String
530 resource_attrs[attr] = Oj.load(resource_attrs[attr],
532 if force_class and !resource_attrs[attr].is_a? force_class
533 raise TypeError.new("#{resource_name}[#{attr.to_s}] must be a #{force_class.to_s}")
535 elsif resource_attrs[attr].is_a? Hash
536 # Convert symbol keys to strings (in hashes provided by
538 resource_attrs[attr] = resource_attrs[attr].
539 with_indifferent_access.to_hash
546 :kind => "arvados##{(@response_resource_name || resource_name).camelize(:lower)}List",
551 :items => @objects.as_api_response(nil)
553 if @objects.respond_to? :except
554 @object_list[:items_available] = @objects.
555 except(:limit).except(:offset).
556 count(:id, distinct: true)
558 render json: @object_list
562 # Caveat: this is highly dependent on the proxy setup. YMMV.
563 if request.headers.has_key?('HTTP_X_REAL_IP') then
564 # We're behind a reverse proxy
565 @remote_ip = request.headers['HTTP_X_REAL_IP']
567 # Hopefully, we are not!
568 @remote_ip = request.env['REMOTE_ADDR']
572 def self._index_requires_parameters
574 filters: { type: 'array', required: false },
575 where: { type: 'object', required: false },
576 order: { type: 'string', required: false },
577 limit: { type: 'integer', required: false, default: DEFAULT_LIMIT },
578 offset: { type: 'integer', required: false, default: 0 },
582 def client_accepts_plain_text_stream
583 (request.headers['Accept'].split(' ') &
584 ['text/plain', '*/*']).count > 0
589 response = opts.first[:json]
590 if response.is_a?(Hash) &&
592 Thread.current[:request_starttime]
593 response[:_profile] = {
594 request_time: Time.now - Thread.current[:request_starttime]
602 return Rails.configuration.arvados_theme