1 module ApiTemplateOverride
2 def allowed_to_render?(fieldset, field, model, options)
4 return options[:select].include? field.to_s
10 class ActsAsApi::ApiTemplate
11 prepend ApiTemplateOverride
15 require 'record_filters'
17 class ApplicationController < ActionController::Base
18 include CurrentApiClient
19 include ThemesForRails::ActionController
23 ERROR_ACTIONS = [:render_error, :render_not_found]
29 before_filter :respond_with_json_by_default
30 before_filter :remote_ip
31 before_filter :load_read_auths
32 before_filter :require_auth_scope, except: ERROR_ACTIONS
34 before_filter :catch_redirect_hint
35 before_filter(:find_object_by_uuid,
36 except: [:index, :create] + ERROR_ACTIONS)
37 before_filter :load_limit_offset_order_params, only: [:index, :contents]
38 before_filter :load_where_param, only: [:index, :contents]
39 before_filter :load_filters_param, only: [:index, :contents]
40 before_filter :find_objects_for_index, :only => :index
41 before_filter :reload_object_before_update, :only => :update
42 before_filter(:render_404_if_no_object,
43 except: [:index, :create] + ERROR_ACTIONS)
47 attr_accessor :resource_attrs
50 @objects.uniq!(&:id) if @select.nil? or @select.include? "id"
51 if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
52 @objects.each(&:eager_load_associations)
58 render json: @object.as_api_response
62 @object = model_class.new resource_attrs
68 attrs_to_update = resource_attrs.reject { |k,v|
69 [:kind, :etag, :href].index k
71 @object.update_attributes! attrs_to_update
80 def self._contents_requires_parameters
81 _index_requires_parameters.
84 type: 'boolean', required: false, default: false
93 # Trick apply_where_limit_order_params into applying suitable
94 # per-table values. *_all are the real ones we'll apply to the
100 ArvadosModel.descendants.reject(&:abstract_class?).sort_by(&:to_s).
103 # We might expect klass==Link etc. here, but we would be
104 # disappointed: when Rails reloads model classes, we get two
105 # distinct classes called Link which do not equal each
106 # other. But we can still rely on klass.to_s to be "Link".
107 when 'ApiClientAuthorization', 'UserAgreement'
110 @objects = klass.readable_by(*@read_users)
111 cond_sql = "#{klass.table_name}.owner_uuid = ?"
112 cond_params = [@object.uuid]
113 if params[:include_linked]
114 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})"
116 @objects = @objects.where(cond_sql, *cond_params).order("#{klass.table_name}.uuid")
117 @limit = limit_all - all_objects.count
118 apply_where_limit_order_params
119 items_available = @objects.
120 except(:limit).except(:offset).
121 count(:id, distinct: true)
122 all_available += items_available
123 @offset = [@offset - items_available, 0].max
125 all_objects += @objects.to_a
128 @objects = all_objects || []
129 @links = Link.where('link_class=? and tail_uuid=?'\
130 ' and head_uuid in (?)',
133 @objects.collect(&:uuid))
135 :kind => "arvados#objectList",
138 :links => @links.as_api_response(nil),
139 :offset => offset_all,
141 :items_available => all_available,
142 :items => @objects.as_api_response(nil)
144 render json: @object_list
147 def catch_redirect_hint
149 if params.has_key?('redirect_to') then
150 session[:redirect_to] = params[:redirect_to]
156 rescue_from Exception,
157 :with => :render_error
158 rescue_from ActiveRecord::RecordNotFound,
159 :with => :render_not_found
160 rescue_from ActionController::RoutingError,
161 :with => :render_not_found
162 rescue_from ActionController::UnknownController,
163 :with => :render_not_found
164 rescue_from AbstractController::ActionNotFound,
165 :with => :render_not_found
166 rescue_from ArvadosModel::PermissionDeniedError,
167 :with => :render_error
170 def render_404_if_no_object
171 render_not_found "Object not found" if !@object
175 logger.error e.inspect
176 if e.respond_to? :backtrace and e.backtrace
177 logger.error e.backtrace.collect { |x| x + "\n" }.join('')
179 if @object and @object.errors and @object.errors.full_messages and not @object.errors.full_messages.empty?
180 errors = @object.errors.full_messages
184 status = e.respond_to?(:http_status) ? e.http_status : 422
185 render json: { errors: errors }, status: status
188 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
189 logger.error e.inspect
190 render json: { errors: ["Path not found"] }, status: 404
195 def find_objects_for_index
196 @objects ||= model_class.readable_by(*@read_users)
197 apply_where_limit_order_params
200 def apply_where_limit_order_params
201 ar_table_name = @objects.table_name
203 ft = record_filters @filters, ar_table_name
204 if ft[:cond_out].any?
205 @objects = @objects.where(ft[:cond_out].join(' AND '), *ft[:param_out])
208 if @where.is_a? Hash and @where.any?
210 @where.each do |attr,value|
211 if attr.to_s == 'any'
212 if value.is_a?(Array) and
213 value.length == 2 and
214 value[0] == 'contains' then
216 model_class.searchable_columns('ilike').each do |column|
217 # Including owner_uuid in an "any column" search will
218 # probably just return a lot of false positives.
219 next if column == 'owner_uuid'
220 ilikes << "#{ar_table_name}.#{column} ilike ?"
221 conditions << "%#{value[1]}%"
224 conditions[0] << ' and (' + ilikes.join(' or ') + ')'
227 elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
228 model_class.columns.collect(&:name).index(attr.to_s)
230 conditions[0] << " and #{ar_table_name}.#{attr} is ?"
232 elsif value.is_a? Array
233 if value[0] == 'contains' and value.length == 2
234 conditions[0] << " and #{ar_table_name}.#{attr} like ?"
235 conditions << "%#{value[1]}%"
237 conditions[0] << " and #{ar_table_name}.#{attr} in (?)"
240 elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
241 conditions[0] << " and #{ar_table_name}.#{attr}=?"
243 elsif value.is_a? Hash
244 # Not quite the same thing as "equal?" but better than nothing?
247 conditions[0] << " and #{ar_table_name}.#{attr} ilike ?"
248 conditions << "%#{k}%#{v}%"
254 if conditions.length > 1
255 conditions[0].sub!(/^1=1 and /, '')
261 @objects = @objects.select(@select.map { |s| "#{table_name}.#{ActiveRecord::Base.connection.quote_column_name s.to_s}" }.join ", ") if @select
262 @objects = @objects.order(@orders.join ", ") if @orders.any?
263 @objects = @objects.limit(@limit)
264 @objects = @objects.offset(@offset)
265 @objects = @objects.uniq(@distinct) if not @distinct.nil?
269 return @attrs if @attrs
270 @attrs = params[resource_name]
271 if @attrs.is_a? String
272 @attrs = Oj.load @attrs, symbol_keys: true
274 unless @attrs.is_a? Hash
275 message = "No #{resource_name}"
276 if resource_name.index('_')
277 message << " (or #{resource_name.camelcase(:lower)})"
279 message << " hash provided with request"
280 raise ArgumentError.new(message)
282 %w(created_at modified_by_client_uuid modified_by_user_uuid modified_at).each do |x|
283 @attrs.delete x.to_sym
285 @attrs = @attrs.symbolize_keys if @attrs.is_a? HashWithIndifferentAccess
292 if current_api_client_authorization
293 @read_auths << current_api_client_authorization
295 # Load reader tokens if this is a read request.
296 # If there are too many reader tokens, assume the request is malicious
298 if request.get? and params[:reader_tokens] and
299 params[:reader_tokens].size < 100
300 @read_auths += ApiClientAuthorization
302 .where('api_token IN (?) AND
303 (expires_at IS NULL OR expires_at > CURRENT_TIMESTAMP)',
304 params[:reader_tokens])
307 @read_auths.select! { |auth| auth.scopes_allow_request? request }
308 @read_users = @read_auths.map { |auth| auth.user }.uniq
313 respond_to do |format|
315 render :json => { errors: ['Not logged in'] }.to_json, status: 401
318 redirect_to '/auth/joshid'
326 unless current_user and current_user.is_admin
327 render :json => { errors: ['Forbidden'] }.to_json, status: 403
331 def require_auth_scope
332 if @read_auths.empty?
333 if require_login != false
334 render :json => { errors: ['Forbidden'] }.to_json, status: 403
340 def respond_with_json_by_default
341 html_index = request.accepts.index(Mime::HTML)
342 if html_index.nil? or request.accepts[0...html_index].include?(Mime::JSON)
343 request.format = :json
348 controller_name.classify.constantize
351 def resource_name # params[] key used by client
352 controller_name.singularize
359 def find_object_by_uuid
360 if params[:id] and params[:id].match /\D/
361 params[:uuid] = params.delete :id
363 @where = { uuid: params[:uuid] }
369 find_objects_for_index
370 @object = @objects.first
373 def reload_object_before_update
374 # This is necessary to prevent an ActiveRecord::ReadOnlyRecord
375 # error when updating an object which was retrieved using a join.
376 if @object.andand.readonly?
377 @object = model_class.find_by_uuid(@objects.first.uuid)
381 def load_json_value(hash, key, must_be_class=nil)
382 if hash[key].is_a? String
383 hash[key] = Oj.load(hash[key], symbol_keys: false)
384 if must_be_class and !hash[key].is_a? must_be_class
385 raise TypeError.new("parameter #{key.to_s} must be a #{must_be_class.to_s}")
390 def self.accept_attribute_as_json(attr, must_be_class=nil)
391 before_filter lambda { accept_attribute_as_json attr, must_be_class }
393 accept_attribute_as_json :properties, Hash
394 accept_attribute_as_json :info, Hash
395 def accept_attribute_as_json(attr, must_be_class)
396 if params[resource_name] and resource_attrs.is_a? Hash
397 if resource_attrs[attr].is_a? Hash
398 # Convert symbol keys to strings (in hashes provided by
400 resource_attrs[attr] = resource_attrs[attr].
401 with_indifferent_access.to_hash
403 load_json_value(resource_attrs, attr, must_be_class)
408 def self.accept_param_as_json(key, must_be_class=nil)
409 prepend_before_filter lambda { load_json_value(params, key, must_be_class) }
411 accept_param_as_json :reader_tokens, Array
415 :kind => "arvados##{(@response_resource_name || resource_name).camelize(:lower)}List",
420 :items => @objects.as_api_response(nil, {select: @select})
422 if @objects.respond_to? :except
423 @object_list[:items_available] = @objects.
424 except(:limit).except(:offset).
425 count(:id, distinct: true)
427 render json: @object_list
431 # Caveat: this is highly dependent on the proxy setup. YMMV.
432 if request.headers.has_key?('HTTP_X_REAL_IP') then
433 # We're behind a reverse proxy
434 @remote_ip = request.headers['HTTP_X_REAL_IP']
436 # Hopefully, we are not!
437 @remote_ip = request.env['REMOTE_ADDR']
441 def self._index_requires_parameters
443 filters: { type: 'array', required: false },
444 where: { type: 'object', required: false },
445 order: { type: 'array', required: false },
446 select: { type: 'array', required: false },
447 distinct: { type: 'boolean', required: false },
448 limit: { type: 'integer', required: false, default: DEFAULT_LIMIT },
449 offset: { type: 'integer', required: false, default: 0 },
453 def client_accepts_plain_text_stream
454 (request.headers['Accept'].split(' ') &
455 ['text/plain', '*/*']).count > 0
460 response = opts.first[:json]
461 if response.is_a?(Hash) &&
463 Thread.current[:request_starttime]
464 response[:_profile] = {
465 request_time: Time.now - Thread.current[:request_starttime]
473 return Rails.configuration.arvados_theme