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 catch_redirect_hint
82 if params.has_key?('redirect_to') then
83 session[:redirect_to] = params[:redirect_to]
89 rescue_from Exception,
90 :with => :render_error
91 rescue_from ActiveRecord::RecordNotFound,
92 :with => :render_not_found
93 rescue_from ActionController::RoutingError,
94 :with => :render_not_found
95 rescue_from ActionController::UnknownController,
96 :with => :render_not_found
97 rescue_from AbstractController::ActionNotFound,
98 :with => :render_not_found
99 rescue_from ArvadosModel::PermissionDeniedError,
100 :with => :render_error
103 def render_404_if_no_object
104 render_not_found "Object not found" if !@object
108 logger.error e.inspect
109 if e.respond_to? :backtrace and e.backtrace
110 logger.error e.backtrace.collect { |x| x + "\n" }.join('')
112 if @object and @object.errors and @object.errors.full_messages and not @object.errors.full_messages.empty?
113 errors = @object.errors.full_messages
117 status = e.respond_to?(:http_status) ? e.http_status : 422
118 render json: { errors: errors }, status: status
121 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
122 logger.error e.inspect
123 render json: { errors: ["Path not found"] }, status: 404
128 def find_objects_for_index
129 @objects ||= model_class.readable_by(*@read_users)
130 apply_where_limit_order_params
133 def apply_where_limit_order_params
134 ar_table_name = @objects.table_name
136 ft = record_filters @filters, ar_table_name
137 if ft[:cond_out].any?
138 @objects = @objects.where(ft[:cond_out].join(' AND '), *ft[:param_out])
141 if @where.is_a? Hash and @where.any?
143 @where.each do |attr,value|
144 if attr.to_s == 'any'
145 if value.is_a?(Array) and
146 value.length == 2 and
147 value[0] == 'contains' then
149 model_class.searchable_columns('ilike').each do |column|
150 # Including owner_uuid in an "any column" search will
151 # probably just return a lot of false positives.
152 next if column == 'owner_uuid'
153 ilikes << "#{ar_table_name}.#{column} ilike ?"
154 conditions << "%#{value[1]}%"
157 conditions[0] << ' and (' + ilikes.join(' or ') + ')'
160 elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
161 model_class.columns.collect(&:name).index(attr.to_s)
163 conditions[0] << " and #{ar_table_name}.#{attr} is ?"
165 elsif value.is_a? Array
166 if value[0] == 'contains' and value.length == 2
167 conditions[0] << " and #{ar_table_name}.#{attr} like ?"
168 conditions << "%#{value[1]}%"
170 conditions[0] << " and #{ar_table_name}.#{attr} in (?)"
173 elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
174 conditions[0] << " and #{ar_table_name}.#{attr}=?"
176 elsif value.is_a? Hash
177 # Not quite the same thing as "equal?" but better than nothing?
180 conditions[0] << " and #{ar_table_name}.#{attr} ilike ?"
181 conditions << "%#{k}%#{v}%"
187 if conditions.length > 1
188 conditions[0].sub!(/^1=1 and /, '')
194 @objects = @objects.select(@select.map { |s| "#{table_name}.#{ActiveRecord::Base.connection.quote_column_name s.to_s}" }.join ", ") if @select
195 @objects = @objects.order(@orders.join ", ") if @orders.any?
196 @objects = @objects.limit(@limit)
197 @objects = @objects.offset(@offset)
198 @objects = @objects.uniq(@distinct) if not @distinct.nil?
202 return @attrs if @attrs
203 @attrs = params[resource_name]
204 if @attrs.is_a? String
205 @attrs = Oj.load @attrs, symbol_keys: true
207 unless @attrs.is_a? Hash
208 message = "No #{resource_name}"
209 if resource_name.index('_')
210 message << " (or #{resource_name.camelcase(:lower)})"
212 message << " hash provided with request"
213 raise ArgumentError.new(message)
215 %w(created_at modified_by_client_uuid modified_by_user_uuid modified_at).each do |x|
216 @attrs.delete x.to_sym
218 @attrs = @attrs.symbolize_keys if @attrs.is_a? HashWithIndifferentAccess
225 if current_api_client_authorization
226 @read_auths << current_api_client_authorization
228 # Load reader tokens if this is a read request.
229 # If there are too many reader tokens, assume the request is malicious
231 if request.get? and params[:reader_tokens] and
232 params[:reader_tokens].size < 100
233 @read_auths += ApiClientAuthorization
235 .where('api_token IN (?) AND
236 (expires_at IS NULL OR expires_at > CURRENT_TIMESTAMP)',
237 params[:reader_tokens])
240 @read_auths.select! { |auth| auth.scopes_allow_request? request }
241 @read_users = @read_auths.map { |auth| auth.user }.uniq
246 respond_to do |format|
248 render :json => { errors: ['Not logged in'] }.to_json, status: 401
251 redirect_to '/auth/joshid'
259 unless current_user and current_user.is_admin
260 render :json => { errors: ['Forbidden'] }.to_json, status: 403
264 def require_auth_scope
265 if @read_auths.empty?
266 if require_login != false
267 render :json => { errors: ['Forbidden'] }.to_json, status: 403
273 def respond_with_json_by_default
274 html_index = request.accepts.index(Mime::HTML)
275 if html_index.nil? or request.accepts[0...html_index].include?(Mime::JSON)
276 request.format = :json
281 controller_name.classify.constantize
284 def resource_name # params[] key used by client
285 controller_name.singularize
292 def find_object_by_uuid
293 if params[:id] and params[:id].match /\D/
294 params[:uuid] = params.delete :id
296 @where = { uuid: params[:uuid] }
302 find_objects_for_index
303 @object = @objects.first
306 def reload_object_before_update
307 # This is necessary to prevent an ActiveRecord::ReadOnlyRecord
308 # error when updating an object which was retrieved using a join.
309 if @object.andand.readonly?
310 @object = model_class.find_by_uuid(@objects.first.uuid)
314 def load_json_value(hash, key, must_be_class=nil)
315 if hash[key].is_a? String
316 hash[key] = Oj.load(hash[key], symbol_keys: false)
317 if must_be_class and !hash[key].is_a? must_be_class
318 raise TypeError.new("parameter #{key.to_s} must be a #{must_be_class.to_s}")
323 def self.accept_attribute_as_json(attr, must_be_class=nil)
324 before_filter lambda { accept_attribute_as_json attr, must_be_class }
326 accept_attribute_as_json :properties, Hash
327 accept_attribute_as_json :info, Hash
328 def accept_attribute_as_json(attr, must_be_class)
329 if params[resource_name] and resource_attrs.is_a? Hash
330 if resource_attrs[attr].is_a? Hash
331 # Convert symbol keys to strings (in hashes provided by
333 resource_attrs[attr] = resource_attrs[attr].
334 with_indifferent_access.to_hash
336 load_json_value(resource_attrs, attr, must_be_class)
341 def self.accept_param_as_json(key, must_be_class=nil)
342 prepend_before_filter lambda { load_json_value(params, key, must_be_class) }
344 accept_param_as_json :reader_tokens, Array
348 :kind => "arvados##{(@response_resource_name || resource_name).camelize(:lower)}List",
353 :items => @objects.as_api_response(nil, {select: @select})
355 if @objects.respond_to? :except
356 @object_list[:items_available] = @objects.
357 except(:limit).except(:offset).
358 count(:id, distinct: true)
360 render json: @object_list
364 # Caveat: this is highly dependent on the proxy setup. YMMV.
365 if request.headers.has_key?('HTTP_X_REAL_IP') then
366 # We're behind a reverse proxy
367 @remote_ip = request.headers['HTTP_X_REAL_IP']
369 # Hopefully, we are not!
370 @remote_ip = request.env['REMOTE_ADDR']
374 def self._index_requires_parameters
376 filters: { type: 'array', required: false },
377 where: { type: 'object', required: false },
378 order: { type: 'array', required: false },
379 select: { type: 'array', required: false },
380 distinct: { type: 'boolean', required: false },
381 limit: { type: 'integer', required: false, default: DEFAULT_LIMIT },
382 offset: { type: 'integer', required: false, default: 0 },
386 def client_accepts_plain_text_stream
387 (request.headers['Accept'].split(' ') &
388 ['text/plain', '*/*']).count > 0
393 response = opts.first[:json]
394 if response.is_a?(Hash) &&
396 Thread.current[:request_starttime]
397 response[:_profile] = {
398 request_time: Time.now - Thread.current[:request_starttime]
406 return Rails.configuration.arvados_theme