2 require 'record_filters'
4 class ApplicationController < ActionController::Base
5 include CurrentApiClient
6 include ThemesForRails::ActionController
13 before_filter :remote_ip
14 before_filter :require_auth_scope_all, :except => :render_not_found
15 before_filter :catch_redirect_hint
17 before_filter :load_where_param, :only => :index
18 before_filter :load_filters_param, :only => :index
19 before_filter :find_objects_for_index, :only => :index
20 before_filter :find_object_by_uuid, :except => [:index, :create,
23 before_filter :reload_object_before_update, :only => :update
24 before_filter :render_404_if_no_object, except: [:index, :create,
30 attr_accessor :resource_attrs
34 if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
35 @objects.each(&:eager_load_associations)
41 render json: @object.as_api_response
45 @object = model_class.new resource_attrs
51 attrs_to_update = resource_attrs.reject { |k,v|
52 [:kind, :etag, :href].index k
54 @object.update_attributes! attrs_to_update
63 def catch_redirect_hint
65 if params.has_key?('redirect_to') then
66 session[:redirect_to] = params[:redirect_to]
72 rescue_from Exception,
73 :with => :render_error
74 rescue_from ActiveRecord::RecordNotFound,
75 :with => :render_not_found
76 rescue_from ActionController::RoutingError,
77 :with => :render_not_found
78 rescue_from ActionController::UnknownController,
79 :with => :render_not_found
80 rescue_from AbstractController::ActionNotFound,
81 :with => :render_not_found
82 rescue_from ArvadosModel::PermissionDeniedError,
83 :with => :render_error
86 def render_404_if_no_object
87 render_not_found "Object not found" if !@object
91 logger.error e.inspect
92 if e.respond_to? :backtrace and e.backtrace
93 logger.error e.backtrace.collect { |x| x + "\n" }.join('')
95 if @object and @object.errors and @object.errors.full_messages and not @object.errors.full_messages.empty?
96 errors = @object.errors.full_messages
100 status = e.respond_to?(:http_status) ? e.http_status : 422
101 render json: { errors: errors }, status: status
104 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
105 logger.error e.inspect
106 render json: { errors: ["Path not found"] }, status: 404
111 def apply_where_limit_order_params
112 ft = record_filters @filters
113 if ft[:cond_out].any?
114 @objects = @objects.where(ft[:cond_out].join(' AND '), *ft[:param_out])
117 if @where.is_a? Hash and @where.any?
119 @where.each do |attr,value|
120 if attr.to_s == 'any'
121 if value.is_a?(Array) and
122 value.length == 2 and
123 value[0] == 'contains' then
125 model_class.searchable_columns('ilike').each do |column|
126 ilikes << "#{table_name}.#{column} ilike ?"
127 conditions << "%#{value[1]}%"
130 conditions[0] << ' and (' + ilikes.join(' or ') + ')'
133 elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
134 model_class.columns.collect(&:name).index(attr.to_s)
136 conditions[0] << " and #{table_name}.#{attr} is ?"
138 elsif value.is_a? Array
139 if value[0] == 'contains' and value.length == 2
140 conditions[0] << " and #{table_name}.#{attr} like ?"
141 conditions << "%#{value[1]}%"
143 conditions[0] << " and #{table_name}.#{attr} in (?)"
146 elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
147 conditions[0] << " and #{table_name}.#{attr}=?"
149 elsif value.is_a? Hash
150 # Not quite the same thing as "equal?" but better than nothing?
153 conditions[0] << " and #{table_name}.#{attr} ilike ?"
154 conditions << "%#{k}%#{v}%"
160 if conditions.length > 1
161 conditions[0].sub!(/^1=1 and /, '')
169 @limit = params[:limit].to_i
171 raise ArgumentError.new("Invalid value for limit parameter")
176 @objects = @objects.limit(@limit)
182 @objects = @objects.offset(params[:offset].to_i)
183 @offset = params[:offset].to_i
185 raise ArgumentError.new("Invalid value for limit parameter")
193 params[:order].split(',').each do |order|
194 attr, direction = order.strip.split " "
196 if attr.match /^[a-z][_a-z0-9]+$/ and
197 model_class.columns.collect(&:name).index(attr) and
198 ['asc','desc'].index direction.downcase
199 orders << "#{table_name}.#{attr} #{direction.downcase}"
204 orders << "#{table_name}.modified_at desc"
206 @objects = @objects.order(orders.join ", ")
209 def find_objects_for_index
210 @objects ||= model_class.readable_by(current_user)
211 apply_where_limit_order_params
215 return @attrs if @attrs
216 @attrs = params[resource_name]
217 if @attrs.is_a? String
218 @attrs = Oj.load @attrs, symbol_keys: true
220 unless @attrs.is_a? Hash
221 message = "No #{resource_name}"
222 if resource_name.index('_')
223 message << " (or #{resource_name.camelcase(:lower)})"
225 message << " hash provided with request"
226 raise ArgumentError.new(message)
228 %w(created_at modified_by_client_uuid modified_by_user_uuid modified_at).each do |x|
229 @attrs.delete x.to_sym
231 @attrs = @attrs.symbolize_keys if @attrs.is_a? HashWithIndifferentAccess
240 respond_to do |format|
242 render :json => { errors: ['Not logged in'] }.to_json, status: 401
245 redirect_to '/auth/joshid'
253 unless current_user and current_user.is_admin
254 render :json => { errors: ['Forbidden'] }.to_json, status: 403
258 def require_auth_scope_all
259 require_login and require_auth_scope(['all'])
262 def require_auth_scope(ok_scopes)
263 unless current_api_client_auth_has_scope(ok_scopes)
264 render :json => { errors: ['Forbidden'] }.to_json, status: 403
269 controller_name.classify.constantize
272 def resource_name # params[] key used by client
273 controller_name.singularize
280 def find_object_by_uuid
281 if params[:id] and params[:id].match /\D/
282 params[:uuid] = params.delete :id
284 @where = { uuid: params[:uuid] }
285 find_objects_for_index
286 @object = @objects.first
289 def reload_object_before_update
290 # This is necessary to prevent an ActiveRecord::ReadOnlyRecord
291 # error when updating an object which was retrieved using a join.
292 if @object.andand.readonly?
293 @object = model_class.find_by_uuid(@objects.first.uuid)
297 def self.accept_attribute_as_json(attr, force_class=nil)
298 before_filter lambda { accept_attribute_as_json attr, force_class }
300 accept_attribute_as_json :properties, Hash
301 accept_attribute_as_json :info, Hash
302 def accept_attribute_as_json(attr, force_class)
303 if params[resource_name] and resource_attrs.is_a? Hash
304 if resource_attrs[attr].is_a? String
305 resource_attrs[attr] = Oj.load(resource_attrs[attr],
307 if force_class and !resource_attrs[attr].is_a? force_class
308 raise TypeError.new("#{resource_name}[#{attr.to_s}] must be a #{force_class.to_s}")
310 elsif resource_attrs[attr].is_a? Hash
311 # Convert symbol keys to strings (in hashes provided by
313 resource_attrs[attr] = resource_attrs[attr].
314 with_indifferent_access.to_hash
321 :kind => "arvados##{(@response_resource_name || resource_name).camelize(:lower)}List",
326 :items => @objects.as_api_response(nil)
328 if @objects.respond_to? :except
329 @object_list[:items_available] = @objects.
330 except(:limit).except(:offset).
331 count(:id, distinct: true)
333 render json: @object_list
337 # Caveat: this is highly dependent on the proxy setup. YMMV.
338 if request.headers.has_key?('HTTP_X_REAL_IP') then
339 # We're behind a reverse proxy
340 @remote_ip = request.headers['HTTP_X_REAL_IP']
342 # Hopefully, we are not!
343 @remote_ip = request.env['REMOTE_ADDR']
347 def self._index_requires_parameters
349 filters: { type: 'array', required: false },
350 where: { type: 'object', required: false },
351 order: { type: 'string', required: false }
355 def client_accepts_plain_text_stream
356 (request.headers['Accept'].split(' ') &
357 ['text/plain', '*/*']).count > 0
362 response = opts.first[:json]
363 if response.is_a?(Hash) &&
365 Thread.current[:request_starttime]
366 response[:_profile] = {
367 request_time: Time.now - Thread.current[:request_starttime]
375 return Rails.configuration.arvados_theme