1 class ApplicationController < ActionController::Base
2 include CurrentApiClient
3 include ThemesForRails::ActionController
8 before_filter :remote_ip
9 before_filter :require_auth_scope_all, :except => :render_not_found
10 before_filter :catch_redirect_hint
12 before_filter :load_where_param, :only => :index
13 before_filter :load_filters_param, :only => :index
14 before_filter :find_objects_for_index, :only => :index
15 before_filter :find_object_by_uuid, :except => [:index, :create,
18 before_filter :reload_object_before_update, :only => :update
19 before_filter :render_404_if_no_object, except: [:index, :create,
25 attr_accessor :resource_attrs
29 if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
30 @objects.each(&:eager_load_associations)
36 render json: @object.as_api_response
40 @object = model_class.new resource_attrs
46 attrs_to_update = resource_attrs.reject { |k,v|
47 [:kind, :etag, :href].index k
49 @object.update_attributes! attrs_to_update
58 def catch_redirect_hint
60 if params.has_key?('redirect_to') then
61 session[:redirect_to] = params[:redirect_to]
67 rescue_from Exception,
68 :with => :render_error
69 rescue_from ActiveRecord::RecordNotFound,
70 :with => :render_not_found
71 rescue_from ActionController::RoutingError,
72 :with => :render_not_found
73 rescue_from ActionController::UnknownController,
74 :with => :render_not_found
75 rescue_from AbstractController::ActionNotFound,
76 :with => :render_not_found
77 rescue_from ArvadosModel::PermissionDeniedError,
78 :with => :render_error
81 def render_404_if_no_object
82 render_not_found "Object not found" if !@object
86 logger.error e.inspect
87 if e.respond_to? :backtrace and e.backtrace
88 logger.error e.backtrace.collect { |x| x + "\n" }.join('')
90 if @object and @object.errors and @object.errors.full_messages and not @object.errors.full_messages.empty?
91 errors = @object.errors.full_messages
95 status = e.respond_to?(:http_status) ? e.http_status : 422
96 render json: { errors: errors }, status: status
99 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
100 logger.error e.inspect
101 render json: { errors: ["Path not found"] }, status: 404
107 if params[:where].nil? or params[:where] == ""
109 elsif params[:where].is_a? Hash
110 @where = params[:where]
111 elsif params[:where].is_a? String
113 @where = Oj.load(params[:where])
114 raise unless @where.is_a? Hash
116 raise ArgumentError.new("Could not parse \"where\" param as an object")
119 @where = @where.with_indifferent_access
122 def load_filters_param
124 if params[:filters].is_a? Array
125 @filters += params[:filters]
126 elsif params[:filters].is_a? String and !params[:filters].empty?
128 f = Oj.load params[:filters]
129 raise unless f.is_a? Array
132 raise ArgumentError.new("Could not parse \"filters\" param as an array")
137 def find_objects_for_index
138 @objects ||= model_class.readable_by(current_user)
139 apply_where_limit_order_params
142 def apply_where_limit_order_params
143 if @filters.is_a? Array and @filters.any?
146 @filters.each do |attr, operator, operand|
147 if !model_class.searchable_columns(operator).index attr.to_s
148 raise ArgumentError.new("Invalid attribute '#{attr}' in condition")
150 case operator.downcase
151 when '=', '<', '<=', '>', '>=', 'like'
152 if operand.is_a? String
153 cond_out << "#{table_name}.#{attr} #{operator} ?"
154 if (# any operator that operates on value rather than
156 operator.match(/[<=>]/) and
157 model_class.attribute_column(attr).type == :datetime)
158 operand = Time.parse operand
163 if operand.is_a? Array
164 cond_out << "#{table_name}.#{attr} IN (?)"
168 operand = [operand] unless operand.is_a? Array
171 cl = ArvadosModel::kind_class op
173 cond << "#{table_name}.#{attr} like ?"
174 param_out << cl.uuid_like_pattern
179 cond_out << cond.join(' OR ')
183 @objects = @objects.where(cond_out.join(' AND '), *param_out)
186 if @where.is_a? Hash and @where.any?
188 @where.each do |attr,value|
189 if attr.to_s == 'any'
190 if value.is_a?(Array) and
191 value.length == 2 and
192 value[0] == 'contains' then
194 model_class.searchable_columns('ilike').each do |column|
195 ilikes << "#{table_name}.#{column} ilike ?"
196 conditions << "%#{value[1]}%"
199 conditions[0] << ' and (' + ilikes.join(' or ') + ')'
202 elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
203 model_class.columns.collect(&:name).index(attr.to_s)
205 conditions[0] << " and #{table_name}.#{attr} is ?"
207 elsif value.is_a? Array
208 if value[0] == 'contains' and value.length == 2
209 conditions[0] << " and #{table_name}.#{attr} like ?"
210 conditions << "%#{value[1]}%"
212 conditions[0] << " and #{table_name}.#{attr} in (?)"
215 elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
216 conditions[0] << " and #{table_name}.#{attr}=?"
218 elsif value.is_a? Hash
219 # Not quite the same thing as "equal?" but better than nothing?
222 conditions[0] << " and #{table_name}.#{attr} ilike ?"
223 conditions << "%#{k}%#{v}%"
229 if conditions.length > 1
230 conditions[0].sub!(/^1=1 and /, '')
238 @limit = params[:limit].to_i
240 raise ArgumentError.new("Invalid value for limit parameter")
245 @objects = @objects.limit(@limit)
251 @objects = @objects.offset(params[:offset].to_i)
252 @offset = params[:offset].to_i
254 raise ArgumentError.new("Invalid value for limit parameter")
262 params[:order].split(',').each do |order|
263 attr, direction = order.strip.split " "
265 if attr.match /^[a-z][_a-z0-9]+$/ and
266 model_class.columns.collect(&:name).index(attr) and
267 ['asc','desc'].index direction.downcase
268 orders << "#{table_name}.#{attr} #{direction.downcase}"
273 orders << "#{table_name}.modified_at desc"
275 @objects = @objects.order(orders.join ", ")
279 return @attrs if @attrs
280 @attrs = params[resource_name]
281 if @attrs.is_a? String
282 @attrs = Oj.load @attrs, symbol_keys: true
284 unless @attrs.is_a? Hash
285 message = "No #{resource_name}"
286 if resource_name.index('_')
287 message << " (or #{resource_name.camelcase(:lower)})"
289 message << " hash provided with request"
290 raise ArgumentError.new(message)
292 %w(created_at modified_by_client_uuid modified_by_user_uuid modified_at).each do |x|
293 @attrs.delete x.to_sym
295 @attrs = @attrs.symbolize_keys if @attrs.is_a? HashWithIndifferentAccess
304 respond_to do |format|
306 render :json => { errors: ['Not logged in'] }.to_json, status: 401
309 redirect_to '/auth/joshid'
317 unless current_user and current_user.is_admin
318 render :json => { errors: ['Forbidden'] }.to_json, status: 403
322 def require_auth_scope_all
323 require_login and require_auth_scope(['all'])
326 def require_auth_scope(ok_scopes)
327 unless current_api_client_auth_has_scope(ok_scopes)
328 render :json => { errors: ['Forbidden'] }.to_json, status: 403
333 controller_name.classify.constantize
336 def resource_name # params[] key used by client
337 controller_name.singularize
344 def find_object_by_uuid
345 if params[:id] and params[:id].match /\D/
346 params[:uuid] = params.delete :id
348 @where = { uuid: params[:uuid] }
349 find_objects_for_index
350 @object = @objects.first
353 def reload_object_before_update
354 # This is necessary to prevent an ActiveRecord::ReadOnlyRecord
355 # error when updating an object which was retrieved using a join.
356 if @object.andand.readonly?
357 @object = model_class.find_by_uuid(@objects.first.uuid)
361 def self.accept_attribute_as_json(attr, force_class=nil)
362 before_filter lambda { accept_attribute_as_json attr, force_class }
364 accept_attribute_as_json :properties, Hash
365 accept_attribute_as_json :info, Hash
366 def accept_attribute_as_json(attr, force_class)
367 if params[resource_name] and resource_attrs.is_a? Hash
368 if resource_attrs[attr].is_a? String
369 resource_attrs[attr] = Oj.load(resource_attrs[attr],
371 if force_class and !resource_attrs[attr].is_a? force_class
372 raise TypeError.new("#{resource_name}[#{attr.to_s}] must be a #{force_class.to_s}")
374 elsif resource_attrs[attr].is_a? Hash
375 # Convert symbol keys to strings (in hashes provided by
377 resource_attrs[attr] = resource_attrs[attr].
378 with_indifferent_access.to_hash
385 :kind => "arvados##{(@response_resource_name || resource_name).camelize(:lower)}List",
390 :items => @objects.as_api_response(nil)
392 if @objects.respond_to? :except
393 @object_list[:items_available] = @objects.
394 except(:limit).except(:offset).
395 count(:id, distinct: true)
397 render json: @object_list
401 # Caveat: this is highly dependent on the proxy setup. YMMV.
402 if request.headers.has_key?('HTTP_X_REAL_IP') then
403 # We're behind a reverse proxy
404 @remote_ip = request.headers['HTTP_X_REAL_IP']
406 # Hopefully, we are not!
407 @remote_ip = request.env['REMOTE_ADDR']
411 def self._index_requires_parameters
413 filters: { type: 'array', required: false },
414 where: { type: 'object', required: false },
415 order: { type: 'string', required: false }
419 def client_accepts_plain_text_stream
420 (request.headers['Accept'].split(' ') &
421 ['text/plain', '*/*']).count > 0
426 response = opts.first[:json]
427 if response.is_a?(Hash) &&
429 Thread.current[:request_starttime]
430 response[:_profile] = {
431 request_time: Time.now - Thread.current[:request_starttime]
439 return Rails.configuration.arvados_theme