1 class ApplicationController < ActionController::Base
2 include CurrentApiClient
3 include ThemesForRails::ActionController
5 ERROR_ACTIONS = [:render_error, :render_not_found]
10 around_filter :thread_with_auth_info, except: ERROR_ACTIONS
11 before_filter :respond_with_json_by_default
12 before_filter :remote_ip
13 before_filter :load_read_auths
14 before_filter :require_auth_scope, except: ERROR_ACTIONS
16 before_filter :catch_redirect_hint
17 before_filter(:find_object_by_uuid,
18 except: [:index, :create] + ERROR_ACTIONS)
19 before_filter :load_limit_offset_order_params, only: [:index, :owned_items]
20 before_filter :load_where_param, only: [:index, :owned_items]
21 before_filter :load_filters_param, only: [:index, :owned_items]
22 before_filter :find_objects_for_index, :only => :index
23 before_filter :reload_object_before_update, :only => :update
24 before_filter(:render_404_if_no_object,
25 except: [:index, :create] + ERROR_ACTIONS)
29 attr_accessor :resource_attrs
35 if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
36 @objects.each(&:eager_load_associations)
42 render json: @object.as_api_response
46 @object = model_class.new resource_attrs
52 attrs_to_update = resource_attrs.reject { |k,v|
53 [:kind, :etag, :href].index k
55 @object.update_attributes! attrs_to_update
64 def self._owned_items_requires_parameters
65 _index_requires_parameters.
68 type: 'boolean', required: false, default: false
77 # Trick apply_where_limit_order_params into applying suitable
78 # per-table values. *_all are the real ones we'll apply to the
84 ArvadosModel.descendants.
85 reject(&:abstract_class?).
89 # We might expect klass==Link etc. here, but we would be
90 # disappointed: when Rails reloads model classes, we get two
91 # distinct classes called Link which do not equal each
92 # other. But we can still rely on klass.to_s to be "Link".
93 when 'ApiClientAuthorization'
96 @objects = klass.readable_by(*@read_users)
97 cond_sql = "#{klass.table_name}.owner_uuid = ?"
98 cond_params = [@object.uuid]
99 if params[:include_linked]
101 joins("LEFT JOIN links mng_links"\
102 " ON mng_links.link_class=#{klass.sanitize 'permission'}"\
103 " AND mng_links.name=#{klass.sanitize 'can_manage'}"\
104 " AND mng_links.tail_uuid=#{klass.sanitize @object.uuid}"\
105 " AND mng_links.head_uuid=#{klass.table_name}.uuid")
106 cond_sql += " OR mng_links.uuid IS NOT NULL"
108 @objects = @objects.where(cond_sql, *cond_params).order(:uuid)
109 @limit = limit_all - all_objects.count
110 apply_where_limit_order_params
111 items_available = @objects.
112 except(:limit).except(:offset).
113 count(:id, distinct: true)
114 all_available += items_available
115 @offset = [@offset - items_available, 0].max
117 all_objects += @objects.to_a
120 @objects = all_objects || []
122 :kind => "arvados#objectList",
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(*@read_users)
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
397 if current_api_client_authorization
398 @read_auths << current_api_client_authorization
400 # Load reader tokens if this is a read request.
401 # If there are too many reader tokens, assume the request is malicious
403 if request.get? and params[:reader_tokens] and
404 params[:reader_tokens].size < 100
405 @read_auths += ApiClientAuthorization
407 .where('api_token IN (?) AND
408 (expires_at IS NULL OR expires_at > CURRENT_TIMESTAMP)',
409 params[:reader_tokens])
412 @read_auths.select! { |auth| auth.scopes_allow_request? request }
413 @read_users = @read_auths.map { |auth| auth.user }.uniq
418 respond_to do |format|
420 render :json => { errors: ['Not logged in'] }.to_json, status: 401
423 redirect_to '/auth/joshid'
431 unless current_user and current_user.is_admin
432 render :json => { errors: ['Forbidden'] }.to_json, status: 403
436 def require_auth_scope
437 if @read_auths.empty?
438 if require_login != false
439 render :json => { errors: ['Forbidden'] }.to_json, status: 403
445 def thread_with_auth_info
446 Thread.current[:request_starttime] = Time.now
447 Thread.current[:api_url_base] = root_url.sub(/\/$/,'') + '/arvados/v1'
451 api_client_auth = nil
453 params[:api_token] ||
454 params[:oauth_token] ||
455 request.headers["Authorization"].andand.match(/OAuth2 ([a-z0-9]+)/).andand[1]
457 api_client_auth = ApiClientAuthorization.
458 includes(:api_client, :user).
459 where('api_token=? and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', supplied_token).
461 if api_client_auth.andand.user
462 session[:user_id] = api_client_auth.user.id
463 session[:api_client_uuid] = api_client_auth.api_client.andand.uuid
464 session[:api_client_authorization_id] = api_client_auth.id
465 user = api_client_auth.user
466 api_client = api_client_auth.api_client
468 # Token seems valid, but points to a non-existent (deleted?) user.
469 api_client_auth = nil
471 elsif session[:user_id]
472 user = User.find(session[:user_id]) rescue nil
473 api_client = ApiClient.
474 where('uuid=?',session[:api_client_uuid]).
476 if session[:api_client_authorization_id] then
477 api_client_auth = ApiClientAuthorization.
478 find session[:api_client_authorization_id]
481 Thread.current[:api_client_ip_address] = remote_ip
482 Thread.current[:api_client_authorization] = api_client_auth
483 Thread.current[:api_client_uuid] = api_client.andand.uuid
484 Thread.current[:api_client] = api_client
485 Thread.current[:user] = user
487 api_client_auth.last_used_at = Time.now
488 api_client_auth.last_used_by_ip_address = remote_ip
489 api_client_auth.save validate: false
493 Thread.current[:api_client_ip_address] = nil
494 Thread.current[:api_client_authorization] = nil
495 Thread.current[:api_client_uuid] = nil
496 Thread.current[:api_client] = nil
497 Thread.current[:user] = nil
502 def respond_with_json_by_default
503 html_index = request.accepts.index(Mime::HTML)
504 if html_index.nil? or request.accepts[0...html_index].include?(Mime::JSON)
505 request.format = :json
510 controller_name.classify.constantize
513 def resource_name # params[] key used by client
514 controller_name.singularize
521 def find_object_by_uuid
522 if params[:id] and params[:id].match /\D/
523 params[:uuid] = params.delete :id
525 @where = { uuid: params[:uuid] }
531 find_objects_for_index
532 @object = @objects.first
535 def reload_object_before_update
536 # This is necessary to prevent an ActiveRecord::ReadOnlyRecord
537 # error when updating an object which was retrieved using a join.
538 if @object.andand.readonly?
539 @object = model_class.find_by_uuid(@objects.first.uuid)
543 def load_json_value(hash, key, must_be_class=nil)
544 if hash[key].is_a? String
545 hash[key] = Oj.load(hash[key], symbol_keys: false)
546 if must_be_class and !hash[key].is_a? must_be_class
547 raise TypeError.new("parameter #{key.to_s} must be a #{must_be_class.to_s}")
552 def self.accept_attribute_as_json(attr, must_be_class=nil)
553 before_filter lambda { accept_attribute_as_json attr, must_be_class }
555 accept_attribute_as_json :properties, Hash
556 accept_attribute_as_json :info, Hash
557 def accept_attribute_as_json(attr, must_be_class)
558 if params[resource_name] and resource_attrs.is_a? Hash
559 if resource_attrs[attr].is_a? Hash
560 # Convert symbol keys to strings (in hashes provided by
562 resource_attrs[attr] = resource_attrs[attr].
563 with_indifferent_access.to_hash
565 load_json_value(resource_attrs, attr, must_be_class)
570 def self.accept_param_as_json(key, must_be_class=nil)
571 prepend_before_filter lambda { load_json_value(params, key, must_be_class) }
573 accept_param_as_json :reader_tokens, Array
577 :kind => "arvados##{(@response_resource_name || resource_name).camelize(:lower)}List",
582 :items => @objects.as_api_response(nil)
584 if @objects.respond_to? :except
585 @object_list[:items_available] = @objects.
586 except(:limit).except(:offset).
587 count(:id, distinct: true)
589 render json: @object_list
593 # Caveat: this is highly dependent on the proxy setup. YMMV.
594 if request.headers.has_key?('HTTP_X_REAL_IP') then
595 # We're behind a reverse proxy
596 @remote_ip = request.headers['HTTP_X_REAL_IP']
598 # Hopefully, we are not!
599 @remote_ip = request.env['REMOTE_ADDR']
603 def self._index_requires_parameters
605 filters: { type: 'array', required: false },
606 where: { type: 'object', required: false },
607 order: { type: 'string', required: false },
608 limit: { type: 'integer', required: false, default: DEFAULT_LIMIT },
609 offset: { type: 'integer', required: false, default: 0 },
613 def client_accepts_plain_text_stream
614 (request.headers['Accept'].split(' ') &
615 ['text/plain', '*/*']).count > 0
620 response = opts.first[:json]
621 if response.is_a?(Hash) &&
623 Thread.current[:request_starttime]
624 response[:_profile] = {
625 request_time: Time.now - Thread.current[:request_starttime]
633 return Rails.configuration.arvados_theme