3 module ApiTemplateOverride
4 def allowed_to_render?(fieldset, field, model, options)
7 options[:select].include? field.to_s
14 class ActsAsApi::ApiTemplate
15 prepend ApiTemplateOverride
20 class ApplicationController < ActionController::Base
21 include ThemesForRails::ActionController
22 include CurrentApiClient
29 ERROR_ACTIONS = [:render_error, :render_not_found]
31 before_filter :disable_api_methods
32 before_filter :set_cors_headers
33 before_filter :respond_with_json_by_default
34 before_filter :remote_ip
35 before_filter :load_read_auths
36 before_filter :require_auth_scope, except: ERROR_ACTIONS
38 before_filter :catch_redirect_hint
39 before_filter(:find_object_by_uuid,
40 except: [:index, :create] + ERROR_ACTIONS)
41 before_filter :load_required_parameters
42 before_filter :load_limit_offset_order_params, only: [:index, :contents]
43 before_filter :load_where_param, only: [:index, :contents]
44 before_filter :load_filters_param, only: [:index, :contents]
45 before_filter :find_objects_for_index, :only => :index
46 before_filter :reload_object_before_update, :only => :update
47 before_filter(:render_404_if_no_object,
48 except: [:index, :create] + ERROR_ACTIONS)
50 theme Rails.configuration.arvados_theme
52 attr_writer :resource_attrs
55 rescue_from(Exception,
56 ArvadosModel::PermissionDeniedError,
57 :with => :render_error)
58 rescue_from(ActiveRecord::RecordNotFound,
59 ActionController::RoutingError,
60 ActionController::UnknownController,
61 AbstractController::ActionNotFound,
62 :with => :render_not_found)
73 @response_resource_name = nil
77 def default_url_options
78 if Rails.configuration.host
79 {:host => Rails.configuration.host}
86 if @select.nil? || @select.include?("id")
87 @objects = @objects.uniq(&:id)
89 if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
90 @objects.each(&:eager_load_associations)
96 send_json @object.as_api_response(nil, select: @select)
100 @object = model_class.new resource_attrs
102 if @object.respond_to?(:name) && params[:ensure_unique_name]
103 @object.save_with_unique_name!
112 attrs_to_update = resource_attrs.reject { |k,v|
113 [:kind, :etag, :href].index k
115 @object.update_attributes! attrs_to_update
124 def catch_redirect_hint
126 if params.has_key?('redirect_to') then
127 session[:redirect_to] = params[:redirect_to]
132 def render_404_if_no_object
133 render_not_found "Object not found" if !@object
137 logger.error e.inspect
138 if e.respond_to? :backtrace and e.backtrace
139 logger.error e.backtrace.collect { |x| x + "\n" }.join('')
141 if (@object.respond_to? :errors and
142 @object.errors.andand.full_messages.andand.any?)
143 errors = @object.errors.full_messages
144 logger.error errors.inspect
148 status = e.respond_to?(:http_status) ? e.http_status : 422
149 send_error(*errors, status: status)
152 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
153 logger.error e.inspect
154 send_error("Path not found", status: 404)
159 def send_error(*args)
160 if args.last.is_a? Hash
165 err[:errors] ||= args
166 err[:error_token] = [Time.now.utc.to_i, "%08x" % rand(16 ** 8)].join("+")
167 status = err.delete(:status) || 422
168 logger.error "Error #{err[:error_token]}: #{status}"
169 send_json err, status: status
172 def send_json response, opts={}
173 # The obvious render(json: ...) forces a slow JSON encoder. See
174 # #3021 and commit logs. Might be fixed in Rails 4.1.
176 text: SafeJSON.dump(response).html_safe,
177 content_type: 'application/json'
181 def self.limit_index_columns_read
182 # This method returns a list of column names.
183 # If an index request reads that column from the database,
184 # find_objects_for_index will only fetch objects until it reads
185 # max_index_database_read bytes of data from those columns.
189 def find_objects_for_index
190 @objects ||= model_class.readable_by(*@read_users)
191 apply_where_limit_order_params
192 limit_database_read if (action_name == "index")
195 def apply_filters model_class=nil
196 model_class ||= self.model_class
197 @objects = model_class.apply_filters(@objects, @filters)
200 def apply_where_limit_order_params model_class=nil
201 model_class ||= self.model_class
202 apply_filters model_class
204 ar_table_name = @objects.table_name
205 if @where.is_a? Hash and @where.any?
207 @where.each do |attr,value|
208 if attr.to_s == 'any'
209 if value.is_a?(Array) and
210 value.length == 2 and
211 value[0] == 'contains' then
213 model_class.searchable_columns('ilike').each do |column|
214 # Including owner_uuid in an "any column" search will
215 # probably just return a lot of false positives.
216 next if column == 'owner_uuid'
217 ilikes << "#{ar_table_name}.#{column} ilike ?"
218 conditions << "%#{value[1]}%"
221 conditions[0] << ' and (' + ilikes.join(' or ') + ')'
224 elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
225 model_class.columns.collect(&:name).index(attr.to_s)
227 conditions[0] << " and #{ar_table_name}.#{attr} is ?"
229 elsif value.is_a? Array
230 if value[0] == 'contains' and value.length == 2
231 conditions[0] << " and #{ar_table_name}.#{attr} like ?"
232 conditions << "%#{value[1]}%"
234 conditions[0] << " and #{ar_table_name}.#{attr} in (?)"
237 elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
238 conditions[0] << " and #{ar_table_name}.#{attr}=?"
240 elsif value.is_a? Hash
241 # Not quite the same thing as "equal?" but better than nothing?
244 conditions[0] << " and #{ar_table_name}.#{attr} ilike ?"
245 conditions << "%#{k}%#{v}%"
251 if conditions.length > 1
252 conditions[0].sub!(/^1=1 and /, '')
259 unless action_name.in? %w(create update destroy)
260 # Map attribute names in @select to real column names, resolve
261 # those to fully-qualified SQL column names, and pass the
262 # resulting string to the select method.
263 columns_list = model_class.columns_for_attributes(@select).
264 map { |s| "#{ar_table_name}.#{ActiveRecord::Base.connection.quote_column_name s}" }
265 @objects = @objects.select(columns_list.join(", "))
268 # This information helps clients understand what they're seeing
269 # (Workbench always expects it), but they can't select it explicitly
270 # because it's not an SQL column. Always add it.
271 # (This is harmless, given that clients can deduce what they're
272 # looking at by the returned UUID anyway.)
275 @objects = @objects.order(@orders.join ", ") if @orders.any?
276 @objects = @objects.limit(@limit)
277 @objects = @objects.offset(@offset)
278 @objects = @objects.uniq(@distinct) if not @distinct.nil?
281 def limit_database_read
282 limit_columns = self.class.limit_index_columns_read
283 limit_columns &= model_class.columns_for_attributes(@select) if @select
284 return if limit_columns.empty?
285 model_class.transaction do
286 limit_query = @objects.
288 select("(%s) as read_length" %
289 limit_columns.map { |s| "octet_length(#{s})" }.join(" + "))
292 limit_query.each do |record|
294 read_total += record.read_length.to_i
295 if read_total >= Rails.configuration.max_index_database_read
296 new_limit -= 1 if new_limit > 1
298 elsif new_limit >= @limit
303 @objects = @objects.limit(@limit)
304 # Force @objects to run its query inside this transaction.
305 @objects.each { |_| break }
310 return @attrs if @attrs
311 @attrs = params[resource_name]
312 if @attrs.is_a? String
313 @attrs = Oj.strict_load @attrs, symbol_keys: true
315 unless @attrs.is_a? Hash
316 message = "No #{resource_name}"
317 if resource_name.index('_')
318 message << " (or #{resource_name.camelcase(:lower)})"
320 message << " hash provided with request"
321 raise ArgumentError.new(message)
323 %w(created_at modified_by_client_uuid modified_by_user_uuid modified_at).each do |x|
324 @attrs.delete x.to_sym
326 @attrs = @attrs.symbolize_keys if @attrs.is_a? HashWithIndifferentAccess
333 if current_api_client_authorization
334 @read_auths << current_api_client_authorization
336 # Load reader tokens if this is a read request.
337 # If there are too many reader tokens, assume the request is malicious
339 if request.get? and params[:reader_tokens] and
340 params[:reader_tokens].size < 100
341 @read_auths += ApiClientAuthorization
343 .where('api_token IN (?) AND
344 (expires_at IS NULL OR expires_at > CURRENT_TIMESTAMP)',
345 params[:reader_tokens])
348 @read_auths.select! { |auth| auth.scopes_allow_request? request }
349 @read_users = @read_auths.map { |auth| auth.user }.uniq
354 respond_to do |format|
355 format.json { send_error("Not logged in", status: 401) }
356 format.html { redirect_to '/auth/joshid' }
363 unless current_user and current_user.is_admin
364 send_error("Forbidden", status: 403)
368 def require_auth_scope
369 if @read_auths.empty?
370 if require_login != false
371 send_error("Forbidden", status: 403)
377 def disable_api_methods
378 if Rails.configuration.disable_api_methods.
379 include?(controller_name + "." + action_name)
380 send_error("Disabled", status: 404)
385 response.headers['Access-Control-Allow-Origin'] = '*'
386 response.headers['Access-Control-Allow-Methods'] = 'GET, HEAD, PUT, POST, DELETE'
387 response.headers['Access-Control-Allow-Headers'] = 'Authorization'
388 response.headers['Access-Control-Max-Age'] = '86486400'
391 def respond_with_json_by_default
392 html_index = request.accepts.index(Mime::HTML)
393 if html_index.nil? or request.accepts[0...html_index].include?(Mime::JSON)
394 request.format = :json
399 controller_name.classify.constantize
402 def resource_name # params[] key used by client
403 controller_name.singularize
410 def find_object_by_uuid
411 if params[:id] and params[:id].match(/\D/)
412 params[:uuid] = params.delete :id
414 @where = { uuid: params[:uuid] }
420 find_objects_for_index
421 @object = @objects.first
424 def reload_object_before_update
425 # This is necessary to prevent an ActiveRecord::ReadOnlyRecord
426 # error when updating an object which was retrieved using a join.
427 if @object.andand.readonly?
428 @object = model_class.find_by_uuid(@objects.first.uuid)
432 def load_json_value(hash, key, must_be_class=nil)
433 if hash[key].is_a? String
434 hash[key] = SafeJSON.load(hash[key])
435 if must_be_class and !hash[key].is_a? must_be_class
436 raise TypeError.new("parameter #{key.to_s} must be a #{must_be_class.to_s}")
441 def self.accept_attribute_as_json(attr, must_be_class=nil)
442 before_filter lambda { accept_attribute_as_json attr, must_be_class }
444 accept_attribute_as_json :properties, Hash
445 accept_attribute_as_json :info, Hash
446 def accept_attribute_as_json(attr, must_be_class)
447 if params[resource_name] and resource_attrs.is_a? Hash
448 if resource_attrs[attr].is_a? Hash
449 # Convert symbol keys to strings (in hashes provided by
451 resource_attrs[attr] = resource_attrs[attr].
452 with_indifferent_access.to_hash
454 load_json_value(resource_attrs, attr, must_be_class)
459 def self.accept_param_as_json(key, must_be_class=nil)
460 prepend_before_filter lambda { load_json_value(params, key, must_be_class) }
462 accept_param_as_json :reader_tokens, Array
466 :kind => "arvados##{(@response_resource_name || resource_name).camelize(:lower)}List",
471 :items => @objects.as_api_response(nil, {select: @select})
474 when nil, '', 'exact'
475 if @objects.respond_to? :except
476 list[:items_available] = @objects.
477 except(:limit).except(:offset).
478 count(:id, distinct: true)
482 raise ArgumentError.new("count parameter must be 'exact' or 'none'")
488 send_json object_list
492 # Caveat: this is highly dependent on the proxy setup. YMMV.
493 if request.headers.key?('HTTP_X_REAL_IP') then
494 # We're behind a reverse proxy
495 @remote_ip = request.headers['HTTP_X_REAL_IP']
497 # Hopefully, we are not!
498 @remote_ip = request.env['REMOTE_ADDR']
502 def load_required_parameters
503 (self.class.send "_#{params[:action]}_requires_parameters" rescue {}).
505 if info[:required] and not params.include?(key)
506 raise ArgumentError.new("#{key} parameter is required")
507 elsif info[:type] == 'boolean'
508 # Make sure params[key] is either true or false -- not a
509 # string, not nil, etc.
510 if not params.include?(key)
511 params[key] = info[:default]
512 elsif [false, 'false', '0', 0].include? params[key]
514 elsif [true, 'true', '1', 1].include? params[key]
517 raise TypeError.new("#{key} parameter must be a boolean, true or false")
524 def self._create_requires_parameters
526 ensure_unique_name: {
528 description: "Adjust name to ensure uniqueness instead of returning an error on (owner_uuid, name) collision.",
536 def self._index_requires_parameters
538 filters: { type: 'array', required: false },
539 where: { type: 'object', required: false },
540 order: { type: 'array', required: false },
541 select: { type: 'array', required: false },
542 distinct: { type: 'boolean', required: false },
543 limit: { type: 'integer', required: false, default: DEFAULT_LIMIT },
544 offset: { type: 'integer', required: false, default: 0 },
545 count: { type: 'string', required: false, default: 'exact' },
549 def client_accepts_plain_text_stream
550 (request.headers['Accept'].split(' ') &
551 ['text/plain', '*/*']).count > 0
556 response = opts.first[:json]
557 if response.is_a?(Hash) &&
559 Thread.current[:request_starttime]
560 response[:_profile] = {
561 request_time: Time.now - Thread.current[:request_starttime]