2 require 'record_filters'
4 class ApplicationController < ActionController::Base
5 include CurrentApiClient
6 include ThemesForRails::ActionController
10 ERROR_ACTIONS = [:render_error, :render_not_found]
15 before_filter :respond_with_json_by_default
16 before_filter :remote_ip
17 before_filter :load_read_auths
18 before_filter :require_auth_scope, except: ERROR_ACTIONS
20 before_filter :catch_redirect_hint
21 before_filter(:find_object_by_uuid,
22 except: [:index, :create] + ERROR_ACTIONS)
23 before_filter :load_limit_offset_order_params, only: [:index, :owned_items]
24 before_filter :load_where_param, only: [:index, :owned_items]
25 before_filter :load_filters_param, only: [:index, :owned_items]
26 before_filter :find_objects_for_index, :only => :index
27 before_filter :reload_object_before_update, :only => :update
28 before_filter(:render_404_if_no_object,
29 except: [:index, :create] + ERROR_ACTIONS)
33 attr_accessor :resource_attrs
37 if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
38 @objects.each(&:eager_load_associations)
44 render json: @object.as_api_response
48 @object = model_class.new resource_attrs
54 attrs_to_update = resource_attrs.reject { |k,v|
55 [:kind, :etag, :href].index k
57 @object.update_attributes! attrs_to_update
66 def self._owned_items_requires_parameters
67 _index_requires_parameters.
70 type: 'boolean', required: false, default: false
79 # Trick apply_where_limit_order_params into applying suitable
80 # per-table values. *_all are the real ones we'll apply to the
86 ArvadosModel.descendants.
87 reject(&:abstract_class?).
91 # We might expect klass==Link etc. here, but we would be
92 # disappointed: when Rails reloads model classes, we get two
93 # distinct classes called Link which do not equal each
94 # other. But we can still rely on klass.to_s to be "Link".
95 when 'ApiClientAuthorization'
98 @objects = klass.readable_by(*@read_users)
99 cond_sql = "#{klass.table_name}.owner_uuid = ?"
100 cond_params = [@object.uuid]
101 if params[:include_linked]
103 joins("LEFT JOIN links mng_links"\
104 " ON mng_links.link_class=#{klass.sanitize 'permission'}"\
105 " AND mng_links.name=#{klass.sanitize 'can_manage'}"\
106 " AND mng_links.tail_uuid=#{klass.sanitize @object.uuid}"\
107 " AND mng_links.head_uuid=#{klass.table_name}.uuid")
108 cond_sql += " OR mng_links.uuid IS NOT NULL"
110 @objects = @objects.where(cond_sql, *cond_params).order(:uuid)
111 @limit = limit_all - all_objects.count
112 apply_where_limit_order_params
113 items_available = @objects.
114 except(:limit).except(:offset).
115 count(:id, distinct: true)
116 all_available += items_available
117 @offset = [@offset - items_available, 0].max
119 all_objects += @objects.to_a
122 @objects = all_objects || []
124 :kind => "arvados#objectList",
127 :offset => offset_all,
129 :items_available => all_available,
130 :items => @objects.as_api_response(nil)
132 render json: @object_list
135 def catch_redirect_hint
137 if params.has_key?('redirect_to') then
138 session[:redirect_to] = params[:redirect_to]
144 rescue_from Exception,
145 :with => :render_error
146 rescue_from ActiveRecord::RecordNotFound,
147 :with => :render_not_found
148 rescue_from ActionController::RoutingError,
149 :with => :render_not_found
150 rescue_from ActionController::UnknownController,
151 :with => :render_not_found
152 rescue_from AbstractController::ActionNotFound,
153 :with => :render_not_found
154 rescue_from ArvadosModel::PermissionDeniedError,
155 :with => :render_error
158 def render_404_if_no_object
159 render_not_found "Object not found" if !@object
163 logger.error e.inspect
164 if e.respond_to? :backtrace and e.backtrace
165 logger.error e.backtrace.collect { |x| x + "\n" }.join('')
167 if @object and @object.errors and @object.errors.full_messages and not @object.errors.full_messages.empty?
168 errors = @object.errors.full_messages
172 status = e.respond_to?(:http_status) ? e.http_status : 422
173 render json: { errors: errors }, status: status
176 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
177 logger.error e.inspect
178 render json: { errors: ["Path not found"] }, status: 404
183 def find_objects_for_index
184 @objects ||= model_class.readable_by(*@read_users)
185 apply_where_limit_order_params
188 def apply_where_limit_order_params
189 ar_table_name = @objects.table_name
191 ft = record_filters @filters, ar_table_name
192 if ft[:cond_out].any?
193 @objects = @objects.where(ft[:cond_out].join(' AND '), *ft[:param_out])
196 if @where.is_a? Hash and @where.any?
198 @where.each do |attr,value|
199 if attr.to_s == 'any'
200 if value.is_a?(Array) and
201 value.length == 2 and
202 value[0] == 'contains' then
204 model_class.searchable_columns('ilike').each do |column|
205 # Including owner_uuid in an "any column" search will
206 # probably just return a lot of false positives.
207 next if column == 'owner_uuid'
208 ilikes << "#{ar_table_name}.#{column} ilike ?"
209 conditions << "%#{value[1]}%"
212 conditions[0] << ' and (' + ilikes.join(' or ') + ')'
215 elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
216 model_class.columns.collect(&:name).index(attr.to_s)
218 conditions[0] << " and #{ar_table_name}.#{attr} is ?"
220 elsif value.is_a? Array
221 if value[0] == 'contains' and value.length == 2
222 conditions[0] << " and #{ar_table_name}.#{attr} like ?"
223 conditions << "%#{value[1]}%"
225 conditions[0] << " and #{ar_table_name}.#{attr} in (?)"
228 elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
229 conditions[0] << " and #{ar_table_name}.#{attr}=?"
231 elsif value.is_a? Hash
232 # Not quite the same thing as "equal?" but better than nothing?
235 conditions[0] << " and #{ar_table_name}.#{attr} ilike ?"
236 conditions << "%#{k}%#{v}%"
242 if conditions.length > 1
243 conditions[0].sub!(/^1=1 and /, '')
249 @objects = @objects.order(@orders.join ", ") if @orders.any?
250 @objects = @objects.limit(@limit)
251 @objects = @objects.offset(@offset)
255 return @attrs if @attrs
256 @attrs = params[resource_name]
257 if @attrs.is_a? String
258 @attrs = Oj.load @attrs, symbol_keys: true
260 unless @attrs.is_a? Hash
261 message = "No #{resource_name}"
262 if resource_name.index('_')
263 message << " (or #{resource_name.camelcase(:lower)})"
265 message << " hash provided with request"
266 raise ArgumentError.new(message)
268 %w(created_at modified_by_client_uuid modified_by_user_uuid modified_at).each do |x|
269 @attrs.delete x.to_sym
271 @attrs = @attrs.symbolize_keys if @attrs.is_a? HashWithIndifferentAccess
278 if current_api_client_authorization
279 @read_auths << current_api_client_authorization
281 # Load reader tokens if this is a read request.
282 # If there are too many reader tokens, assume the request is malicious
284 if request.get? and params[:reader_tokens] and
285 params[:reader_tokens].size < 100
286 @read_auths += ApiClientAuthorization
288 .where('api_token IN (?) AND
289 (expires_at IS NULL OR expires_at > CURRENT_TIMESTAMP)',
290 params[:reader_tokens])
293 @read_auths.select! { |auth| auth.scopes_allow_request? request }
294 @read_users = @read_auths.map { |auth| auth.user }.uniq
299 respond_to do |format|
301 render :json => { errors: ['Not logged in'] }.to_json, status: 401
304 redirect_to '/auth/joshid'
312 unless current_user and current_user.is_admin
313 render :json => { errors: ['Forbidden'] }.to_json, status: 403
317 def require_auth_scope
318 if @read_auths.empty?
319 if require_login != false
320 render :json => { errors: ['Forbidden'] }.to_json, status: 403
326 def respond_with_json_by_default
327 html_index = request.accepts.index(Mime::HTML)
328 if html_index.nil? or request.accepts[0...html_index].include?(Mime::JSON)
329 request.format = :json
334 controller_name.classify.constantize
337 def resource_name # params[] key used by client
338 controller_name.singularize
345 def find_object_by_uuid
346 if params[:id] and params[:id].match /\D/
347 params[:uuid] = params.delete :id
349 @where = { uuid: params[:uuid] }
355 find_objects_for_index
356 @object = @objects.first
359 def reload_object_before_update
360 # This is necessary to prevent an ActiveRecord::ReadOnlyRecord
361 # error when updating an object which was retrieved using a join.
362 if @object.andand.readonly?
363 @object = model_class.find_by_uuid(@objects.first.uuid)
367 def load_json_value(hash, key, must_be_class=nil)
368 if hash[key].is_a? String
369 hash[key] = Oj.load(hash[key], symbol_keys: false)
370 if must_be_class and !hash[key].is_a? must_be_class
371 raise TypeError.new("parameter #{key.to_s} must be a #{must_be_class.to_s}")
376 def self.accept_attribute_as_json(attr, must_be_class=nil)
377 before_filter lambda { accept_attribute_as_json attr, must_be_class }
379 accept_attribute_as_json :properties, Hash
380 accept_attribute_as_json :info, Hash
381 def accept_attribute_as_json(attr, must_be_class)
382 if params[resource_name] and resource_attrs.is_a? Hash
383 if resource_attrs[attr].is_a? Hash
384 # Convert symbol keys to strings (in hashes provided by
386 resource_attrs[attr] = resource_attrs[attr].
387 with_indifferent_access.to_hash
389 load_json_value(resource_attrs, attr, must_be_class)
394 def self.accept_param_as_json(key, must_be_class=nil)
395 prepend_before_filter lambda { load_json_value(params, key, must_be_class) }
397 accept_param_as_json :reader_tokens, Array
401 :kind => "arvados##{(@response_resource_name || resource_name).camelize(:lower)}List",
406 :items => @objects.as_api_response(nil)
408 if @objects.respond_to? :except
409 @object_list[:items_available] = @objects.
410 except(:limit).except(:offset).
411 count(:id, distinct: true)
413 render json: @object_list
417 # Caveat: this is highly dependent on the proxy setup. YMMV.
418 if request.headers.has_key?('HTTP_X_REAL_IP') then
419 # We're behind a reverse proxy
420 @remote_ip = request.headers['HTTP_X_REAL_IP']
422 # Hopefully, we are not!
423 @remote_ip = request.env['REMOTE_ADDR']
427 def self._index_requires_parameters
429 filters: { type: 'array', required: false },
430 where: { type: 'object', required: false },
431 order: { type: 'string', required: false },
432 limit: { type: 'integer', required: false, default: DEFAULT_LIMIT },
433 offset: { type: 'integer', required: false, default: 0 },
437 def client_accepts_plain_text_stream
438 (request.headers['Accept'].split(' ') &
439 ['text/plain', '*/*']).count > 0
444 response = opts.first[:json]
445 if response.is_a?(Hash) &&
447 Thread.current[:request_starttime]
448 response[:_profile] = {
449 request_time: Time.now - Thread.current[:request_starttime]
457 return Rails.configuration.arvados_theme