1 class ApplicationController < ActionController::Base
2 include CurrentApiClient
3 include ThemesForRails::ActionController
7 around_filter :thread_with_auth_info, :except => [:render_error, :render_not_found]
9 before_filter :remote_ip
10 before_filter :require_auth_scope_all, :except => :render_not_found
11 before_filter :catch_redirect_hint
13 before_filter :load_where_param, :only => :index
14 before_filter :load_filters_param, :only => :index
15 before_filter :find_objects_for_index, :only => :index
16 before_filter :find_object_by_uuid, :except => [:index, :create,
19 before_filter :reload_object_before_update, :only => :update
20 before_filter :render_404_if_no_object, except: [:index, :create,
26 attr_accessor :resource_attrs
30 if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
31 @objects.each(&:eager_load_associations)
37 render json: @object.as_api_response
41 @object = model_class.new resource_attrs
47 attrs_to_update = resource_attrs.reject { |k,v|
48 [:kind, :etag, :href].index k
50 @object.update_attributes! attrs_to_update
59 def catch_redirect_hint
61 if params.has_key?('redirect_to') then
62 session[:redirect_to] = params[:redirect_to]
68 rescue_from Exception,
69 :with => :render_error
70 rescue_from ActiveRecord::RecordNotFound,
71 :with => :render_not_found
72 rescue_from ActionController::RoutingError,
73 :with => :render_not_found
74 rescue_from ActionController::UnknownController,
75 :with => :render_not_found
76 rescue_from AbstractController::ActionNotFound,
77 :with => :render_not_found
78 rescue_from ArvadosModel::PermissionDeniedError,
79 :with => :render_error
82 def render_404_if_no_object
83 render_not_found "Object not found" if !@object
87 logger.error e.inspect
88 if e.respond_to? :backtrace and e.backtrace
89 logger.error e.backtrace.collect { |x| x + "\n" }.join('')
91 if @object and @object.errors and @object.errors.full_messages and not @object.errors.full_messages.empty?
92 errors = @object.errors.full_messages
96 status = e.respond_to?(:http_status) ? e.http_status : 422
97 render json: { errors: errors }, status: status
100 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
101 logger.error e.inspect
102 render json: { errors: ["Path not found"] }, status: 404
108 if params[:where].nil? or params[:where] == ""
110 elsif params[:where].is_a? Hash
111 @where = params[:where]
112 elsif params[:where].is_a? String
114 @where = Oj.load(params[:where])
115 raise unless @where.is_a? Hash
117 raise ArgumentError.new("Could not parse \"where\" param as an object")
120 @where = @where.with_indifferent_access
123 def load_filters_param
125 if params[:filters].is_a? Array
126 @filters += params[:filters]
127 elsif params[:filters].is_a? String and !params[:filters].empty?
129 f = Oj.load params[:filters]
130 raise unless f.is_a? Array
133 raise ArgumentError.new("Could not parse \"filters\" param as an array")
138 def find_objects_for_index
139 @objects ||= model_class.readable_by(current_user)
140 apply_where_limit_order_params
143 def apply_where_limit_order_params
144 if @filters.is_a? Array and @filters.any?
147 @filters.each do |attr, operator, operand|
148 if !model_class.searchable_columns(operator).index attr.to_s
149 raise ArgumentError.new("Invalid attribute '#{attr}' in condition")
151 case operator.downcase
152 when '=', '<', '<=', '>', '>=', 'like'
153 if operand.is_a? String
154 cond_out << "#{table_name}.#{attr} #{operator} ?"
155 if (# any operator that operates on value rather than
157 operator.match(/[<=>]/) and
158 model_class.attribute_column(attr).type == :datetime)
159 operand = Time.parse operand
164 if operand.is_a? Array
165 cond_out << "#{table_name}.#{attr} IN (?)"
169 operand = [operand] unless operand.is_a? Array
172 cl = ArvadosModel::kind_class op
174 cond << "#{table_name}.#{attr} like ?"
175 param_out << cl.uuid_like_pattern
180 cond_out << cond.join(' OR ')
184 @objects = @objects.where(cond_out.join(' AND '), *param_out)
187 if @where.is_a? Hash and @where.any?
189 @where.each do |attr,value|
190 if attr.to_s == 'any'
191 if value.is_a?(Array) and
192 value.length == 2 and
193 value[0] == 'contains' then
195 model_class.searchable_columns('ilike').each do |column|
196 ilikes << "#{table_name}.#{column} ilike ?"
197 conditions << "%#{value[1]}%"
200 conditions[0] << ' and (' + ilikes.join(' or ') + ')'
203 elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
204 model_class.columns.collect(&:name).index(attr.to_s)
206 conditions[0] << " and #{table_name}.#{attr} is ?"
208 elsif value.is_a? Array
209 if value[0] == 'contains' and value.length == 2
210 conditions[0] << " and #{table_name}.#{attr} like ?"
211 conditions << "%#{value[1]}%"
213 conditions[0] << " and #{table_name}.#{attr} in (?)"
216 elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
217 conditions[0] << " and #{table_name}.#{attr}=?"
219 elsif value.is_a? Hash
220 # Not quite the same thing as "equal?" but better than nothing?
223 conditions[0] << " and #{table_name}.#{attr} ilike ?"
224 conditions << "%#{k}%#{v}%"
230 if conditions.length > 1
231 conditions[0].sub!(/^1=1 and /, '')
239 @limit = params[:limit].to_i
241 raise ArgumentError.new("Invalid value for limit parameter")
246 @objects = @objects.limit(@limit)
252 @objects = @objects.offset(params[:offset].to_i)
253 @offset = params[:offset].to_i
255 raise ArgumentError.new("Invalid value for limit parameter")
263 params[:order].split(',').each do |order|
264 attr, direction = order.strip.split " "
266 if attr.match /^[a-z][_a-z0-9]+$/ and
267 model_class.columns.collect(&:name).index(attr) and
268 ['asc','desc'].index direction.downcase
269 orders << "#{table_name}.#{attr} #{direction.downcase}"
274 orders << "#{table_name}.modified_at desc"
276 @objects = @objects.order(orders.join ", ")
280 return @attrs if @attrs
281 @attrs = params[resource_name]
282 if @attrs.is_a? String
283 @attrs = Oj.load @attrs, symbol_keys: true
285 unless @attrs.is_a? Hash
286 message = "No #{resource_name}"
287 if resource_name.index('_')
288 message << " (or #{resource_name.camelcase(:lower)})"
290 message << " hash provided with request"
291 raise ArgumentError.new(message)
293 %w(created_at modified_by_client_uuid modified_by_user_uuid modified_at).each do |x|
294 @attrs.delete x.to_sym
296 @attrs = @attrs.symbolize_keys if @attrs.is_a? HashWithIndifferentAccess
305 respond_to do |format|
307 render :json => { errors: ['Not logged in'] }.to_json, status: 401
310 redirect_to '/auth/joshid'
318 unless current_user and current_user.is_admin
319 render :json => { errors: ['Forbidden'] }.to_json, status: 403
323 def require_auth_scope_all
324 require_login and require_auth_scope(['all'])
327 def require_auth_scope(ok_scopes)
328 unless current_api_client_auth_has_scope(ok_scopes)
329 render :json => { errors: ['Forbidden'] }.to_json, status: 403
333 def thread_with_auth_info
334 Thread.current[:request_starttime] = Time.now
335 Thread.current[:api_url_base] = root_url.sub(/\/$/,'') + '/arvados/v1'
339 api_client_auth = nil
341 params[:api_token] ||
342 params[:oauth_token] ||
343 request.headers["Authorization"].andand.match(/OAuth2 ([a-z0-9]+)/).andand[1]
345 api_client_auth = ApiClientAuthorization.
346 includes(:api_client, :user).
347 where('api_token=? and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', supplied_token).
349 if api_client_auth.andand.user
350 session[:user_id] = api_client_auth.user.id
351 session[:api_client_uuid] = api_client_auth.api_client.andand.uuid
352 session[:api_client_authorization_id] = api_client_auth.id
353 user = api_client_auth.user
354 api_client = api_client_auth.api_client
356 # Token seems valid, but points to a non-existent (deleted?) user.
357 api_client_auth = nil
359 elsif session[:user_id]
360 user = User.find(session[:user_id]) rescue nil
361 api_client = ApiClient.
362 where('uuid=?',session[:api_client_uuid]).
364 if session[:api_client_authorization_id] then
365 api_client_auth = ApiClientAuthorization.
366 find session[:api_client_authorization_id]
369 Thread.current[:api_client_ip_address] = remote_ip
370 Thread.current[:api_client_authorization] = api_client_auth
371 Thread.current[:api_client_uuid] = api_client.andand.uuid
372 Thread.current[:api_client] = api_client
373 Thread.current[:user] = user
375 api_client_auth.last_used_at = Time.now
376 api_client_auth.last_used_by_ip_address = remote_ip
377 api_client_auth.save validate: false
381 Thread.current[:api_client_ip_address] = nil
382 Thread.current[:api_client_authorization] = nil
383 Thread.current[:api_client_uuid] = nil
384 Thread.current[:api_client] = nil
385 Thread.current[:user] = nil
391 controller_name.classify.constantize
394 def resource_name # params[] key used by client
395 controller_name.singularize
402 def find_object_by_uuid
403 if params[:id] and params[:id].match /\D/
404 params[:uuid] = params.delete :id
406 @where = { uuid: params[:uuid] }
407 find_objects_for_index
408 @object = @objects.first
411 def reload_object_before_update
412 # This is necessary to prevent an ActiveRecord::ReadOnlyRecord
413 # error when updating an object which was retrieved using a join.
414 if @object.andand.readonly?
415 @object = model_class.find_by_uuid(@objects.first.uuid)
419 def self.accept_attribute_as_json(attr, force_class=nil)
420 before_filter lambda { accept_attribute_as_json attr, force_class }
422 accept_attribute_as_json :properties, Hash
423 accept_attribute_as_json :info, Hash
424 def accept_attribute_as_json(attr, force_class)
425 if params[resource_name] and resource_attrs.is_a? Hash
426 if resource_attrs[attr].is_a? String
427 resource_attrs[attr] = Oj.load(resource_attrs[attr],
429 if force_class and !resource_attrs[attr].is_a? force_class
430 raise TypeError.new("#{resource_name}[#{attr.to_s}] must be a #{force_class.to_s}")
432 elsif resource_attrs[attr].is_a? Hash
433 # Convert symbol keys to strings (in hashes provided by
435 resource_attrs[attr] = resource_attrs[attr].
436 with_indifferent_access.to_hash
443 :kind => "arvados##{(@response_resource_name || resource_name).camelize(:lower)}List",
448 :items => @objects.as_api_response(nil)
450 if @objects.respond_to? :except
451 @object_list[:items_available] = @objects.
452 except(:limit).except(:offset).
453 count(:id, distinct: true)
455 render json: @object_list
459 # Caveat: this is highly dependent on the proxy setup. YMMV.
460 if request.headers.has_key?('HTTP_X_REAL_IP') then
461 # We're behind a reverse proxy
462 @remote_ip = request.headers['HTTP_X_REAL_IP']
464 # Hopefully, we are not!
465 @remote_ip = request.env['REMOTE_ADDR']
469 def self._index_requires_parameters
471 filters: { type: 'array', required: false },
472 where: { type: 'object', required: false },
473 order: { type: 'string', required: false }
477 def client_accepts_plain_text_stream
478 (request.headers['Accept'].split(' ') &
479 ['text/plain', '*/*']).count > 0
484 response = opts.first[:json]
485 if response.is_a?(Hash) &&
487 Thread.current[:request_starttime]
488 response[:_profile] = {
489 request_time: Time.now - Thread.current[:request_starttime]
497 return Rails.configuration.arvados_theme