1 class ApplicationController < ActionController::Base
2 include CurrentApiClient
6 around_filter :thread_with_auth_info, :except => [:render_error, :render_not_found]
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,
23 attr_accessor :resource_attrs
27 if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
28 @objects.each(&:eager_load_associations)
34 render json: @object.as_api_response
38 @object = model_class.new resource_attrs
47 attrs_to_update = resource_attrs.reject { |k,v|
48 [:kind, :etag, :href].index k
50 if @object.update_attributes attrs_to_update
62 def catch_redirect_hint
64 if params.has_key?('redirect_to') then
65 session[:redirect_to] = params[:redirect_to]
71 rescue_from Exception,
72 :with => :render_error
73 rescue_from ActiveRecord::RecordNotFound,
74 :with => :render_not_found
75 rescue_from ActionController::RoutingError,
76 :with => :render_not_found
77 rescue_from ActionController::UnknownController,
78 :with => :render_not_found
79 rescue_from AbstractController::ActionNotFound,
80 :with => :render_not_found
81 rescue_from ArvadosModel::PermissionDeniedError,
82 :with => :render_error
85 def render_404_if_no_object
86 render_not_found "Object not found" if !@object
90 logger.error e.inspect
91 if e.respond_to? :backtrace and e.backtrace
92 logger.error e.backtrace.collect { |x| x + "\n" }.join('')
94 if @object and @object.errors and @object.errors.full_messages and not @object.errors.full_messages.empty?
95 errors = @object.errors.full_messages
99 status = e.respond_to?(:http_status) ? e.http_status : 422
100 render json: { errors: errors }, status: status
103 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
104 logger.error e.inspect
105 render json: { errors: ["Path not found"] }, status: 404
111 if params[:where].nil? or params[:where] == ""
113 elsif params[:where].is_a? Hash
114 @where = params[:where]
115 elsif params[:where].is_a? String
117 @where = Oj.load(params[:where])
118 raise unless @where.is_a? Hash
120 raise ArgumentError.new("Could not parse \"where\" param as an object")
123 @where = @where.with_indifferent_access
126 def load_filters_param
127 if params[:filters].is_a? Array
128 @filters = params[:filters]
129 elsif params[:filters].is_a? String and !params[:filters].empty?
131 @filters = Oj.load params[:filters]
132 raise unless @filters.is_a? Array
134 raise ArgumentError.new("Could not parse \"filters\" param as an array")
139 def find_objects_for_index
140 @objects ||= model_class.readable_by(current_user)
141 apply_where_limit_order_params
144 def apply_where_limit_order_params
145 if @filters.is_a? Array and @filters.any?
148 @filters.each do |attr, operator, operand|
149 if !model_class.searchable_columns.index attr.to_s
150 raise ArgumentError.new("Invalid attribute '#{attr}' in condition")
152 case operator.downcase
153 when '=', '<', '<=', '>', '>=', 'like'
154 if operand.is_a? String
155 cond_out << "#{table_name}.#{attr} #{operator} ?"
156 if (# any operator that operates on value rather than
158 operator.match(/[<=>]/) and
159 model_class.attribute_column(attr).type == :datetime)
160 operand = Time.parse operand
165 if operand.is_a? Array
166 cond_out << "#{table_name}.#{attr} IN (?)"
172 @objects = @objects.where(cond_out.join(' AND '), *param_out)
175 if @where.is_a? Hash and @where.any?
177 @where.each do |attr,value|
179 if value.is_a?(Array) and
180 value.length == 2 and
181 value[0] == 'contains' and
182 model_class.columns.collect(&:name).index('name') then
184 model_class.searchable_columns.each do |column|
185 ilikes << "#{table_name}.#{column} ilike ?"
186 conditions << "%#{value[1]}%"
189 conditions[0] << ' and (' + ilikes.join(' or ') + ')'
192 elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
193 model_class.columns.collect(&:name).index(attr.to_s)
195 conditions[0] << " and #{table_name}.#{attr} is ?"
197 elsif value.is_a? Array
198 if value[0] == 'contains' and value.length == 2
199 conditions[0] << " and #{table_name}.#{attr} like ?"
200 conditions << "%#{value[1]}%"
202 conditions[0] << " and #{table_name}.#{attr} in (?)"
205 elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
206 conditions[0] << " and #{table_name}.#{attr}=?"
208 elsif value.is_a? Hash
209 # Not quite the same thing as "equal?" but better than nothing?
212 conditions[0] << " and #{table_name}.#{attr} ilike ?"
213 conditions << "%#{k}%#{v}%"
219 if conditions.length > 1
220 conditions[0].sub!(/^1=1 and /, '')
228 @limit = params[:limit].to_i
230 raise ArgumentError.new("Invalid value for limit parameter")
235 @objects = @objects.limit(@limit)
241 @objects = @objects.offset(params[:offset].to_i)
242 @offset = params[:offset].to_i
244 raise ArgumentError.new("Invalid value for limit parameter")
252 params[:order].split(',').each do |order|
253 attr, direction = order.strip.split " "
255 if attr.match /^[a-z][_a-z0-9]+$/ and
256 model_class.columns.collect(&:name).index(attr) and
257 ['asc','desc'].index direction.downcase
258 orders << "#{table_name}.#{attr} #{direction.downcase}"
263 orders << "#{table_name}.modified_at desc"
265 @objects = @objects.order(orders.join ", ")
269 return @attrs if @attrs
270 @attrs = params[resource_name]
271 if @attrs.is_a? String
272 @attrs = Oj.load @attrs, symbol_keys: true
274 unless @attrs.is_a? Hash
275 message = "No #{resource_name}"
276 if resource_name.index('_')
277 message << " (or #{resource_name.camelcase(:lower)})"
279 message << " hash provided with request"
280 raise ArgumentError.new(message)
282 %w(created_at modified_by_client_uuid modified_by_user_uuid modified_at).each do |x|
283 @attrs.delete x.to_sym
285 @attrs = @attrs.symbolize_keys if @attrs.is_a? HashWithIndifferentAccess
294 respond_to do |format|
296 render :json => { errors: ['Not logged in'] }.to_json, status: 401
299 redirect_to '/auth/joshid'
307 unless current_user and current_user.is_admin
308 render :json => { errors: ['Forbidden'] }.to_json, status: 403
312 def require_auth_scope_all
313 require_login and require_auth_scope(['all'])
316 def require_auth_scope(ok_scopes)
317 unless current_api_client_auth_has_scope(ok_scopes)
318 render :json => { errors: ['Forbidden'] }.to_json, status: 403
322 def thread_with_auth_info
323 Thread.current[:request_starttime] = Time.now
324 Thread.current[:api_url_base] = root_url.sub(/\/$/,'') + '/arvados/v1'
328 api_client_auth = nil
330 params[:api_token] ||
331 params[:oauth_token] ||
332 request.headers["Authorization"].andand.match(/OAuth2 ([a-z0-9]+)/).andand[1]
334 api_client_auth = ApiClientAuthorization.
335 includes(:api_client, :user).
336 where('api_token=? and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', supplied_token).
338 if api_client_auth.andand.user
339 session[:user_id] = api_client_auth.user.id
340 session[:api_client_uuid] = api_client_auth.api_client.andand.uuid
341 session[:api_client_authorization_id] = api_client_auth.id
342 user = api_client_auth.user
343 api_client = api_client_auth.api_client
345 elsif session[:user_id]
346 user = User.find(session[:user_id]) rescue nil
347 api_client = ApiClient.
348 where('uuid=?',session[:api_client_uuid]).
350 if session[:api_client_authorization_id] then
351 api_client_auth = ApiClientAuthorization.
352 find session[:api_client_authorization_id]
355 Thread.current[:api_client_ip_address] = remote_ip
356 Thread.current[:api_client_authorization] = api_client_auth
357 Thread.current[:api_client_uuid] = api_client.andand.uuid
358 Thread.current[:api_client] = api_client
359 Thread.current[:user] = user
361 api_client_auth.last_used_at = Time.now
362 api_client_auth.last_used_by_ip_address = remote_ip
363 api_client_auth.save validate: false
367 Thread.current[:api_client_ip_address] = nil
368 Thread.current[:api_client_authorization] = nil
369 Thread.current[:api_client_uuid] = nil
370 Thread.current[:api_client] = nil
371 Thread.current[:user] = nil
377 controller_name.classify.constantize
380 def resource_name # params[] key used by client
381 controller_name.singularize
388 def find_object_by_uuid
389 if params[:id] and params[:id].match /\D/
390 params[:uuid] = params.delete :id
392 @where = { uuid: params[:uuid] }
393 find_objects_for_index
394 @object = @objects.first
397 def reload_object_before_update
398 # This is necessary to prevent an ActiveRecord::ReadOnlyRecord
399 # error when updating an object which was retrieved using a join.
400 if @object.andand.readonly?
401 @object = model_class.find_by_uuid(@objects.first.uuid)
405 def self.accept_attribute_as_json(attr, force_class=nil)
406 before_filter lambda { accept_attribute_as_json attr, force_class }
408 accept_attribute_as_json :properties, Hash
409 accept_attribute_as_json :info, Hash
410 def accept_attribute_as_json(attr, force_class)
411 if params[resource_name] and resource_attrs.is_a? Hash
412 if resource_attrs[attr].is_a? String
413 resource_attrs[attr] = Oj.load(resource_attrs[attr],
415 if force_class and !resource_attrs[attr].is_a? force_class
416 raise TypeError.new("#{resource_name}[#{attr.to_s}] must be a #{force_class.to_s}")
418 elsif resource_attrs[attr].is_a? Hash
419 # Convert symbol keys to strings (in hashes provided by
421 resource_attrs[attr] = resource_attrs[attr].
422 with_indifferent_access.to_hash
429 :kind => "arvados##{(@response_resource_name || resource_name).camelize(:lower)}List",
434 :items => @objects.as_api_response(nil)
436 if @objects.respond_to? :except
437 @object_list[:items_available] = @objects.except(:limit).except(:offset).count
439 render json: @object_list
443 # Caveat: this is highly dependent on the proxy setup. YMMV.
444 if request.headers.has_key?('HTTP_X_REAL_IP') then
445 # We're behind a reverse proxy
446 @remote_ip = request.headers['HTTP_X_REAL_IP']
448 # Hopefully, we are not!
449 @remote_ip = request.env['REMOTE_ADDR']
453 def self._index_requires_parameters
455 filters: { type: 'array', required: false },
456 where: { type: 'object', required: false },
457 order: { type: 'string', required: false }
461 def client_accepts_plain_text_stream
462 (request.headers['Accept'].split(' ') &
463 ['text/plain', '*/*']).count > 0
468 response = opts.first[:json]
469 if response.is_a?(Hash) &&
471 Thread.current[:request_starttime]
472 response[:_profile] = {
473 request_time: Time.now - Thread.current[:request_starttime]