1 module ApiTemplateOverride
2 def allowed_to_render?(fieldset, field, model, options)
5 options[:select].include? field.to_s
12 class ActsAsApi::ApiTemplate
13 prepend ApiTemplateOverride
17 require 'record_filters'
19 class ApplicationController < ActionController::Base
20 include CurrentApiClient
21 include ThemesForRails::ActionController
29 ERROR_ACTIONS = [:render_error, :render_not_found]
31 before_filter :set_cors_headers
32 before_filter :respond_with_json_by_default
33 before_filter :remote_ip
34 before_filter :load_read_auths
35 before_filter :require_auth_scope, except: ERROR_ACTIONS
37 before_filter :catch_redirect_hint
38 before_filter(:find_object_by_uuid,
39 except: [:index, :create] + ERROR_ACTIONS)
40 before_filter :load_required_parameters
41 before_filter :load_limit_offset_order_params, only: [:index, :contents]
42 before_filter :load_where_param, only: [:index, :contents]
43 before_filter :load_filters_param, only: [:index, :contents]
44 before_filter :find_objects_for_index, :only => :index
45 before_filter :reload_object_before_update, :only => :update
46 before_filter(:render_404_if_no_object,
47 except: [:index, :create] + ERROR_ACTIONS)
51 attr_accessor :resource_attrs
54 rescue_from(Exception,
55 ArvadosModel::PermissionDeniedError,
56 :with => :render_error)
57 rescue_from(ActiveRecord::RecordNotFound,
58 ActionController::RoutingError,
59 ActionController::UnknownController,
60 AbstractController::ActionNotFound,
61 :with => :render_not_found)
64 def default_url_options
65 if Rails.configuration.host
66 {:host => Rails.configuration.host}
73 @objects.uniq!(&:id) if @select.nil? or @select.include? "id"
74 if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
75 @objects.each(&:eager_load_associations)
81 send_json @object.as_api_response(nil, select: @select)
85 @object = model_class.new resource_attrs
87 if @object.respond_to? :name and params[:ensure_unique_name]
88 # Record the original name. See below.
89 name_stem = @object.name
95 rescue ActiveRecord::RecordNotUnique => rn
96 raise unless params[:ensure_unique_name]
98 # Dig into the error to determine if it is specifically calling out a
99 # (owner_uuid, name) uniqueness violation. In this specific case, and
100 # the client requested a unique name with ensure_unique_name==true,
101 # update the name field and try to save again. Loop as necessary to
102 # discover a unique name. It is necessary to handle name choosing at
103 # this level (as opposed to the client) to ensure that record creation
104 # never fails due to a race condition.
105 raise unless rn.original_exception.is_a? PG::UniqueViolation
107 # Unfortunately ActiveRecord doesn't abstract out any of the
108 # necessary information to figure out if this the error is actually
109 # the specific case where we want to apply the ensure_unique_name
110 # behavior, so the following code is specialized to Postgres.
111 err = rn.original_exception
112 detail = err.result.error_field(PG::Result::PG_DIAG_MESSAGE_DETAIL)
113 raise unless /^Key \(owner_uuid, name\)=\([a-z0-9]{5}-[a-z0-9]{5}-[a-z0-9]{15}, .*?\) already exists\./.match detail
115 # OK, this exception really is just a unique name constraint
116 # violation, and we've been asked to ensure_unique_name.
119 @object.name = "#{name_stem} (#{counter})"
126 attrs_to_update = resource_attrs.reject { |k,v|
127 [:kind, :etag, :href].index k
129 @object.update_attributes! attrs_to_update
138 def catch_redirect_hint
140 if params.has_key?('redirect_to') then
141 session[:redirect_to] = params[:redirect_to]
146 def render_404_if_no_object
147 render_not_found "Object not found" if !@object
151 logger.error e.inspect
152 if e.respond_to? :backtrace and e.backtrace
153 logger.error e.backtrace.collect { |x| x + "\n" }.join('')
155 if (@object.respond_to? :errors and
156 @object.errors.andand.full_messages.andand.any?)
157 errors = @object.errors.full_messages
158 logger.error errors.inspect
162 status = e.respond_to?(:http_status) ? e.http_status : 422
163 send_error(*errors, status: status)
166 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
167 logger.error e.inspect
168 send_error("Path not found", status: 404)
173 def send_error(*args)
174 if args.last.is_a? Hash
179 err[:errors] ||= args
180 err[:error_token] = [db_current_time.utc.to_i, "%08x" % rand(16 ** 8)].join("+")
181 status = err.delete(:status) || 422
182 logger.error "Error #{err[:error_token]}: #{status}"
183 send_json err, status: status
186 def send_json response, opts={}
187 # The obvious render(json: ...) forces a slow JSON encoder. See
188 # #3021 and commit logs. Might be fixed in Rails 4.1.
190 text: Oj.dump(response, mode: :compat).html_safe,
191 content_type: 'application/json'
195 def find_objects_for_index
196 @objects ||= model_class.readable_by(*@read_users)
197 apply_where_limit_order_params
200 def apply_filters model_class=nil
201 model_class ||= self.model_class
202 ft = record_filters @filters, model_class
203 if ft[:cond_out].any?
204 @objects = @objects.where('(' + ft[:cond_out].join(') AND (') + ')',
209 def apply_where_limit_order_params model_class=nil
210 model_class ||= self.model_class
211 apply_filters model_class
213 ar_table_name = @objects.table_name
214 if @where.is_a? Hash and @where.any?
216 @where.each do |attr,value|
217 if attr.to_s == 'any'
218 if value.is_a?(Array) and
219 value.length == 2 and
220 value[0] == 'contains' then
222 model_class.searchable_columns('ilike').each do |column|
223 # Including owner_uuid in an "any column" search will
224 # probably just return a lot of false positives.
225 next if column == 'owner_uuid'
226 ilikes << "#{ar_table_name}.#{column} ilike ?"
227 conditions << "%#{value[1]}%"
230 conditions[0] << ' and (' + ilikes.join(' or ') + ')'
233 elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
234 model_class.columns.collect(&:name).index(attr.to_s)
236 conditions[0] << " and #{ar_table_name}.#{attr} is ?"
238 elsif value.is_a? Array
239 if value[0] == 'contains' and value.length == 2
240 conditions[0] << " and #{ar_table_name}.#{attr} like ?"
241 conditions << "%#{value[1]}%"
243 conditions[0] << " and #{ar_table_name}.#{attr} in (?)"
246 elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
247 conditions[0] << " and #{ar_table_name}.#{attr}=?"
249 elsif value.is_a? Hash
250 # Not quite the same thing as "equal?" but better than nothing?
253 conditions[0] << " and #{ar_table_name}.#{attr} ilike ?"
254 conditions << "%#{k}%#{v}%"
260 if conditions.length > 1
261 conditions[0].sub!(/^1=1 and /, '')
268 unless action_name.in? %w(create update destroy)
269 # Map attribute names in @select to real column names, resolve
270 # those to fully-qualified SQL column names, and pass the
271 # resulting string to the select method.
272 api_column_map = model_class.attributes_required_columns
273 columns_list = @select.
274 flat_map { |attr| api_column_map[attr] }.
276 map { |s| "#{ar_table_name}.#{ActiveRecord::Base.connection.quote_column_name s}" }
277 @objects = @objects.select(columns_list.join(", "))
280 # This information helps clients understand what they're seeing
281 # (Workbench always expects it), but they can't select it explicitly
282 # because it's not an SQL column. Always add it.
283 # (This is harmless, given that clients can deduce what they're
284 # looking at by the returned UUID anyway.)
287 @objects = @objects.order(@orders.join ", ") if @orders.any?
288 @objects = @objects.limit(@limit)
289 @objects = @objects.offset(@offset)
290 @objects = @objects.uniq(@distinct) if not @distinct.nil?
294 return @attrs if @attrs
295 @attrs = params[resource_name]
296 if @attrs.is_a? String
297 @attrs = Oj.load @attrs, symbol_keys: true
299 unless @attrs.is_a? Hash
300 message = "No #{resource_name}"
301 if resource_name.index('_')
302 message << " (or #{resource_name.camelcase(:lower)})"
304 message << " hash provided with request"
305 raise ArgumentError.new(message)
307 %w(created_at modified_by_client_uuid modified_by_user_uuid modified_at).each do |x|
308 @attrs.delete x.to_sym
310 @attrs = @attrs.symbolize_keys if @attrs.is_a? HashWithIndifferentAccess
317 if current_api_client_authorization
318 @read_auths << current_api_client_authorization
320 # Load reader tokens if this is a read request.
321 # If there are too many reader tokens, assume the request is malicious
323 if request.get? and params[:reader_tokens] and
324 params[:reader_tokens].size < 100
325 @read_auths += ApiClientAuthorization
327 .where('api_token IN (?) AND
328 (expires_at IS NULL OR expires_at > CURRENT_TIMESTAMP)',
329 params[:reader_tokens])
332 @read_auths.select! { |auth| auth.scopes_allow_request? request }
333 @read_users = @read_auths.map { |auth| auth.user }.uniq
338 respond_to do |format|
339 format.json { send_error("Not logged in", status: 401) }
340 format.html { redirect_to '/auth/joshid' }
347 unless current_user and current_user.is_admin
348 send_error("Forbidden", status: 403)
352 def require_auth_scope
353 if @read_auths.empty?
354 if require_login != false
355 send_error("Forbidden", status: 403)
362 response.headers['Access-Control-Allow-Origin'] = '*'
363 response.headers['Access-Control-Allow-Methods'] = 'GET, HEAD, PUT, POST, DELETE'
364 response.headers['Access-Control-Allow-Headers'] = 'Authorization'
365 response.headers['Access-Control-Max-Age'] = '86486400'
368 def respond_with_json_by_default
369 html_index = request.accepts.index(Mime::HTML)
370 if html_index.nil? or request.accepts[0...html_index].include?(Mime::JSON)
371 request.format = :json
376 controller_name.classify.constantize
379 def resource_name # params[] key used by client
380 controller_name.singularize
387 def find_object_by_uuid
388 if params[:id] and params[:id].match /\D/
389 params[:uuid] = params.delete :id
391 @where = { uuid: params[:uuid] }
397 find_objects_for_index
398 @object = @objects.first
401 def reload_object_before_update
402 # This is necessary to prevent an ActiveRecord::ReadOnlyRecord
403 # error when updating an object which was retrieved using a join.
404 if @object.andand.readonly?
405 @object = model_class.find_by_uuid(@objects.first.uuid)
409 def load_json_value(hash, key, must_be_class=nil)
410 if hash[key].is_a? String
411 hash[key] = Oj.load(hash[key], symbol_keys: false)
412 if must_be_class and !hash[key].is_a? must_be_class
413 raise TypeError.new("parameter #{key.to_s} must be a #{must_be_class.to_s}")
418 def self.accept_attribute_as_json(attr, must_be_class=nil)
419 before_filter lambda { accept_attribute_as_json attr, must_be_class }
421 accept_attribute_as_json :properties, Hash
422 accept_attribute_as_json :info, Hash
423 def accept_attribute_as_json(attr, must_be_class)
424 if params[resource_name] and resource_attrs.is_a? Hash
425 if resource_attrs[attr].is_a? Hash
426 # Convert symbol keys to strings (in hashes provided by
428 resource_attrs[attr] = resource_attrs[attr].
429 with_indifferent_access.to_hash
431 load_json_value(resource_attrs, attr, must_be_class)
436 def self.accept_param_as_json(key, must_be_class=nil)
437 prepend_before_filter lambda { load_json_value(params, key, must_be_class) }
439 accept_param_as_json :reader_tokens, Array
443 :kind => "arvados##{(@response_resource_name || resource_name).camelize(:lower)}List",
448 :items => @objects.as_api_response(nil, {select: @select})
450 if @objects.respond_to? :except
451 list[:items_available] = @objects.
452 except(:limit).except(:offset).
453 count(:id, distinct: true)
459 send_json object_list
463 # Caveat: this is highly dependent on the proxy setup. YMMV.
464 if request.headers.has_key?('HTTP_X_REAL_IP') then
465 # We're behind a reverse proxy
466 @remote_ip = request.headers['HTTP_X_REAL_IP']
468 # Hopefully, we are not!
469 @remote_ip = request.env['REMOTE_ADDR']
473 def load_required_parameters
474 (self.class.send "_#{params[:action]}_requires_parameters" rescue {}).
476 if info[:required] and not params.include?(key)
477 raise ArgumentError.new("#{key} parameter is required")
478 elsif info[:type] == 'boolean'
479 # Make sure params[key] is either true or false -- not a
480 # string, not nil, etc.
481 if not params.include?(key)
482 params[key] = info[:default]
483 elsif [false, 'false', '0', 0].include? params[key]
485 elsif [true, 'true', '1', 1].include? params[key]
488 raise TypeError.new("#{key} parameter must be a boolean, true or false")
495 def self._create_requires_parameters
497 ensure_unique_name: {
499 description: "Adjust name to ensure uniqueness instead of returning an error on (owner_uuid, name) collision.",
507 def self._index_requires_parameters
509 filters: { type: 'array', required: false },
510 where: { type: 'object', required: false },
511 order: { type: 'array', required: false },
512 select: { type: 'array', required: false },
513 distinct: { type: 'boolean', required: false },
514 limit: { type: 'integer', required: false, default: DEFAULT_LIMIT },
515 offset: { type: 'integer', required: false, default: 0 },
519 def client_accepts_plain_text_stream
520 (request.headers['Accept'].split(' ') &
521 ['text/plain', '*/*']).count > 0
526 response = opts.first[:json]
527 if response.is_a?(Hash) &&
529 Thread.current[:request_starttime]
530 response[:_profile] = {
531 request_time: db_current_time - Thread.current[:request_starttime]
539 return Rails.configuration.arvados_theme