2 require 'record_filters'
4 class ApplicationController < ActionController::Base
5 include CurrentApiClient
6 include ThemesForRails::ActionController
13 before_filter :respond_with_json_by_default
14 before_filter :remote_ip
15 before_filter :require_auth_scope, :except => :render_not_found
16 before_filter :catch_redirect_hint
18 before_filter :find_object_by_uuid, :except => [:index, :create,
21 before_filter :load_limit_offset_order_params, only: [:index, :owned_items]
22 before_filter :load_where_param, only: [:index, :owned_items]
23 before_filter :load_filters_param, only: [:index, :owned_items]
24 before_filter :find_objects_for_index, :only => :index
25 before_filter :reload_object_before_update, :only => :update
26 before_filter :render_404_if_no_object, except: [:index, :create,
32 attr_accessor :resource_attrs
36 if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
37 @objects.each(&:eager_load_associations)
43 render json: @object.as_api_response
47 @object = model_class.new resource_attrs
53 attrs_to_update = resource_attrs.reject { |k,v|
54 [:kind, :etag, :href].index k
56 @object.update_attributes! attrs_to_update
65 def self._owned_items_requires_parameters
66 _index_requires_parameters.
69 type: 'boolean', required: false, default: false
78 # Trick apply_where_limit_order_params into applying suitable
79 # per-table values. *_all are the real ones we'll apply to the
85 ArvadosModel.descendants.
86 reject(&:abstract_class?).
90 # We might expect klass==Link etc. here, but we would be
91 # disappointed: when Rails reloads model classes, we get two
92 # distinct classes called Link which do not equal each
93 # other. But we can still rely on klass.to_s to be "Link".
94 when 'ApiClientAuthorization'
97 @objects = klass.readable_by(current_user)
98 cond_sql = "#{klass.table_name}.owner_uuid = ?"
99 cond_params = [@object.uuid]
100 if params[:include_linked]
102 joins("LEFT JOIN links mng_links"\
103 " ON mng_links.link_class=#{klass.sanitize 'permission'}"\
104 " AND mng_links.name=#{klass.sanitize 'can_manage'}"\
105 " AND mng_links.tail_uuid=#{klass.sanitize @object.uuid}"\
106 " AND mng_links.head_uuid=#{klass.table_name}.uuid")
107 cond_sql += " OR mng_links.uuid IS NOT NULL"
109 @objects = @objects.where(cond_sql, *cond_params).order(:uuid)
110 @limit = limit_all - all_objects.count
111 apply_where_limit_order_params
112 items_available = @objects.
113 except(:limit).except(:offset).
114 count(:id, distinct: true)
115 all_available += items_available
116 @offset = [@offset - items_available, 0].max
118 all_objects += @objects.to_a
121 @objects = all_objects || []
123 :kind => "arvados#objectList",
126 :offset => offset_all,
128 :items_available => all_available,
129 :items => @objects.as_api_response(nil)
131 render json: @object_list
134 def catch_redirect_hint
136 if params.has_key?('redirect_to') then
137 session[:redirect_to] = params[:redirect_to]
143 rescue_from Exception,
144 :with => :render_error
145 rescue_from ActiveRecord::RecordNotFound,
146 :with => :render_not_found
147 rescue_from ActionController::RoutingError,
148 :with => :render_not_found
149 rescue_from ActionController::UnknownController,
150 :with => :render_not_found
151 rescue_from AbstractController::ActionNotFound,
152 :with => :render_not_found
153 rescue_from ArvadosModel::PermissionDeniedError,
154 :with => :render_error
157 def render_404_if_no_object
158 render_not_found "Object not found" if !@object
162 logger.error e.inspect
163 if e.respond_to? :backtrace and e.backtrace
164 logger.error e.backtrace.collect { |x| x + "\n" }.join('')
166 if @object and @object.errors and @object.errors.full_messages and not @object.errors.full_messages.empty?
167 errors = @object.errors.full_messages
171 status = e.respond_to?(:http_status) ? e.http_status : 422
172 render json: { errors: errors }, status: status
175 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
176 logger.error e.inspect
177 render json: { errors: ["Path not found"] }, status: 404
182 def find_objects_for_index
183 @objects ||= model_class.readable_by(current_user)
184 apply_where_limit_order_params
187 def apply_where_limit_order_params
188 ar_table_name = @objects.table_name
190 ft = record_filters @filters, ar_table_name
191 if ft[:cond_out].any?
192 @objects = @objects.where(ft[:cond_out].join(' AND '), *ft[:param_out])
195 if @where.is_a? Hash and @where.any?
197 @where.each do |attr,value|
198 if attr.to_s == 'any'
199 if value.is_a?(Array) and
200 value.length == 2 and
201 value[0] == 'contains' then
203 model_class.searchable_columns('ilike').each do |column|
204 # Including owner_uuid in an "any column" search will
205 # probably just return a lot of false positives.
206 next if column == 'owner_uuid'
207 ilikes << "#{ar_table_name}.#{column} ilike ?"
208 conditions << "%#{value[1]}%"
211 conditions[0] << ' and (' + ilikes.join(' or ') + ')'
214 elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
215 model_class.columns.collect(&:name).index(attr.to_s)
217 conditions[0] << " and #{ar_table_name}.#{attr} is ?"
219 elsif value.is_a? Array
220 if value[0] == 'contains' and value.length == 2
221 conditions[0] << " and #{ar_table_name}.#{attr} like ?"
222 conditions << "%#{value[1]}%"
224 conditions[0] << " and #{ar_table_name}.#{attr} in (?)"
227 elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
228 conditions[0] << " and #{ar_table_name}.#{attr}=?"
230 elsif value.is_a? Hash
231 # Not quite the same thing as "equal?" but better than nothing?
234 conditions[0] << " and #{ar_table_name}.#{attr} ilike ?"
235 conditions << "%#{k}%#{v}%"
241 if conditions.length > 1
242 conditions[0].sub!(/^1=1 and /, '')
248 @objects = @objects.order(@orders.join ", ") if @orders.any?
249 @objects = @objects.limit(@limit)
250 @objects = @objects.offset(@offset)
254 return @attrs if @attrs
255 @attrs = params[resource_name]
256 if @attrs.is_a? String
257 @attrs = Oj.load @attrs, symbol_keys: true
259 unless @attrs.is_a? Hash
260 message = "No #{resource_name}"
261 if resource_name.index('_')
262 message << " (or #{resource_name.camelcase(:lower)})"
264 message << " hash provided with request"
265 raise ArgumentError.new(message)
267 %w(created_at modified_by_client_uuid modified_by_user_uuid modified_at).each do |x|
268 @attrs.delete x.to_sym
270 @attrs = @attrs.symbolize_keys if @attrs.is_a? HashWithIndifferentAccess
279 respond_to do |format|
281 render :json => { errors: ['Not logged in'] }.to_json, status: 401
284 redirect_to '/auth/joshid'
292 unless current_user and current_user.is_admin
293 render :json => { errors: ['Forbidden'] }.to_json, status: 403
297 def require_auth_scope
298 return false unless require_login
299 unless current_api_client_auth_has_scope("#{request.method} #{request.path}")
300 render :json => { errors: ['Forbidden'] }.to_json, status: 403
304 def respond_with_json_by_default
305 html_index = request.accepts.index(Mime::HTML)
306 if html_index.nil? or request.accepts[0...html_index].include?(Mime::JSON)
307 request.format = :json
312 controller_name.classify.constantize
315 def resource_name # params[] key used by client
316 controller_name.singularize
323 def find_object_by_uuid
324 if params[:id] and params[:id].match /\D/
325 params[:uuid] = params.delete :id
327 @where = { uuid: params[:uuid] }
333 find_objects_for_index
334 @object = @objects.first
337 def reload_object_before_update
338 # This is necessary to prevent an ActiveRecord::ReadOnlyRecord
339 # error when updating an object which was retrieved using a join.
340 if @object.andand.readonly?
341 @object = model_class.find_by_uuid(@objects.first.uuid)
345 def self.accept_attribute_as_json(attr, force_class=nil)
346 before_filter lambda { accept_attribute_as_json attr, force_class }
348 accept_attribute_as_json :properties, Hash
349 accept_attribute_as_json :info, Hash
350 def accept_attribute_as_json(attr, force_class)
351 if params[resource_name] and resource_attrs.is_a? Hash
352 if resource_attrs[attr].is_a? String
353 resource_attrs[attr] = Oj.load(resource_attrs[attr],
355 if force_class and !resource_attrs[attr].is_a? force_class
356 raise TypeError.new("#{resource_name}[#{attr.to_s}] must be a #{force_class.to_s}")
358 elsif resource_attrs[attr].is_a? Hash
359 # Convert symbol keys to strings (in hashes provided by
361 resource_attrs[attr] = resource_attrs[attr].
362 with_indifferent_access.to_hash
369 :kind => "arvados##{(@response_resource_name || resource_name).camelize(:lower)}List",
374 :items => @objects.as_api_response(nil)
376 if @objects.respond_to? :except
377 @object_list[:items_available] = @objects.
378 except(:limit).except(:offset).
379 count(:id, distinct: true)
381 render json: @object_list
385 # Caveat: this is highly dependent on the proxy setup. YMMV.
386 if request.headers.has_key?('HTTP_X_REAL_IP') then
387 # We're behind a reverse proxy
388 @remote_ip = request.headers['HTTP_X_REAL_IP']
390 # Hopefully, we are not!
391 @remote_ip = request.env['REMOTE_ADDR']
395 def self._index_requires_parameters
397 filters: { type: 'array', required: false },
398 where: { type: 'object', required: false },
399 order: { type: 'string', required: false },
400 limit: { type: 'integer', required: false, default: DEFAULT_LIMIT },
401 offset: { type: 'integer', required: false, default: 0 },
405 def client_accepts_plain_text_stream
406 (request.headers['Accept'].split(' ') &
407 ['text/plain', '*/*']).count > 0
412 response = opts.first[:json]
413 if response.is_a?(Hash) &&
415 Thread.current[:request_starttime]
416 response[:_profile] = {
417 request_time: Time.now - Thread.current[:request_starttime]
425 return Rails.configuration.arvados_theme