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
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 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 (?)"
170 @objects = @objects.where(cond_out.join(' AND '), *param_out)
173 if @where.is_a? Hash and @where.any?
175 @where.each do |attr,value|
177 if value.is_a?(Array) and
178 value.length == 2 and
179 value[0] == 'contains' and
180 model_class.columns.collect(&:name).index('name') then
182 model_class.searchable_columns.each do |column|
183 ilikes << "#{table_name}.#{column} ilike ?"
184 conditions << "%#{value[1]}%"
187 conditions[0] << ' and (' + ilikes.join(' or ') + ')'
190 elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
191 model_class.columns.collect(&:name).index(attr.to_s)
193 conditions[0] << " and #{table_name}.#{attr} is ?"
195 elsif value.is_a? Array
196 if value[0] == 'contains' and value.length == 2
197 conditions[0] << " and #{table_name}.#{attr} like ?"
198 conditions << "%#{value[1]}%"
200 conditions[0] << " and #{table_name}.#{attr} in (?)"
203 elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
204 conditions[0] << " and #{table_name}.#{attr}=?"
206 elsif value.is_a? Hash
207 # Not quite the same thing as "equal?" but better than nothing?
210 conditions[0] << " and #{table_name}.#{attr} ilike ?"
211 conditions << "%#{k}%#{v}%"
217 if conditions.length > 1
218 conditions[0].sub!(/^1=1 and /, '')
225 @objects = @objects.limit(params[:limit].to_i)
227 raise ArgumentError.new("Invalid value for limit parameter")
230 @objects = @objects.limit(100)
234 params[:order].split(',').each do |order|
235 attr, direction = order.strip.split " "
237 if attr.match /^[a-z][_a-z0-9]+$/ and
238 model_class.columns.collect(&:name).index(attr) and
239 ['asc','desc'].index direction.downcase
240 orders << "#{table_name}.#{attr} #{direction.downcase}"
245 orders << "#{table_name}.modified_at desc"
247 @objects = @objects.order(orders.join ", ")
251 return @attrs if @attrs
252 @attrs = params[resource_name]
253 if @attrs.is_a? String
254 @attrs = Oj.load @attrs, symbol_keys: true
256 unless @attrs.is_a? Hash
257 message = "No #{resource_name}"
258 if resource_name.index('_')
259 message << " (or #{resource_name.camelcase(:lower)})"
261 message << " hash provided with request"
262 raise ArgumentError.new(message)
264 %w(created_at modified_by_client_uuid modified_by_user_uuid modified_at).each do |x|
265 @attrs.delete x.to_sym
267 @attrs = @attrs.symbolize_keys if @attrs.is_a? HashWithIndifferentAccess
276 respond_to do |format|
278 render :json => { errors: ['Not logged in'] }.to_json, status: 401
281 redirect_to '/auth/joshid'
289 unless current_user and current_user.is_admin
290 render :json => { errors: ['Forbidden'] }.to_json, status: 403
294 def require_auth_scope_all
295 require_login and require_auth_scope(['all'])
298 def require_auth_scope(ok_scopes)
299 unless current_api_client_auth_has_scope(ok_scopes)
300 render :json => { errors: ['Forbidden'] }.to_json, status: 403
304 def thread_with_auth_info
305 Thread.current[:request_starttime] = Time.now
306 Thread.current[:api_url_base] = root_url.sub(/\/$/,'') + '/arvados/v1'
310 api_client_auth = nil
312 params[:api_token] ||
313 params[:oauth_token] ||
314 request.headers["Authorization"].andand.match(/OAuth2 ([a-z0-9]+)/).andand[1]
316 api_client_auth = ApiClientAuthorization.
317 includes(:api_client, :user).
318 where('api_token=? and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', supplied_token).
320 if api_client_auth.andand.user
321 session[:user_id] = api_client_auth.user.id
322 session[:api_client_uuid] = api_client_auth.api_client.andand.uuid
323 session[:api_client_authorization_id] = api_client_auth.id
324 user = api_client_auth.user
325 api_client = api_client_auth.api_client
327 elsif session[:user_id]
328 user = User.find(session[:user_id]) rescue nil
329 api_client = ApiClient.
330 where('uuid=?',session[:api_client_uuid]).
332 if session[:api_client_authorization_id] then
333 api_client_auth = ApiClientAuthorization.
334 find session[:api_client_authorization_id]
337 Thread.current[:api_client_ip_address] = remote_ip
338 Thread.current[:api_client_authorization] = api_client_auth
339 Thread.current[:api_client_uuid] = api_client.andand.uuid
340 Thread.current[:api_client] = api_client
341 Thread.current[:user] = user
343 api_client_auth.last_used_at = Time.now
344 api_client_auth.last_used_by_ip_address = remote_ip
345 api_client_auth.save validate: false
349 Thread.current[:api_client_ip_address] = nil
350 Thread.current[:api_client_authorization] = nil
351 Thread.current[:api_client_uuid] = nil
352 Thread.current[:api_client] = nil
353 Thread.current[:user] = nil
359 controller_name.classify.constantize
362 def resource_name # params[] key used by client
363 controller_name.singularize
370 def find_object_by_uuid
371 if params[:id] and params[:id].match /\D/
372 params[:uuid] = params.delete :id
374 @where = { uuid: params[:uuid] }
375 find_objects_for_index
376 @object = @objects.first
379 def reload_object_before_update
380 # This is necessary to prevent an ActiveRecord::ReadOnlyRecord
381 # error when updating an object which was retrieved using a join.
382 if @object.andand.readonly?
383 @object = model_class.find_by_uuid(@objects.first.uuid)
387 def self.accept_attribute_as_json(attr, force_class=nil)
388 before_filter lambda { accept_attribute_as_json attr, force_class }
390 accept_attribute_as_json :properties, Hash
391 accept_attribute_as_json :info, Hash
392 def accept_attribute_as_json(attr, force_class)
393 if params[resource_name] and resource_attrs.is_a? Hash
394 if resource_attrs[attr].is_a? String
395 resource_attrs[attr] = Oj.load(resource_attrs[attr],
397 if force_class and !resource_attrs[attr].is_a? force_class
398 raise TypeError.new("#{resource_name}[#{attr.to_s}] must be a #{force_class.to_s}")
400 elsif resource_attrs[attr].is_a? Hash
401 # Convert symbol keys to strings (in hashes provided by
403 resource_attrs[attr] = resource_attrs[attr].
404 with_indifferent_access.to_hash
411 :kind => "arvados##{(@response_resource_name || resource_name).camelize(:lower)}List",
414 :next_page_token => "",
416 :items => @objects.as_api_response(nil)
418 if @objects.respond_to? :except
419 @object_list[:items_available] = @objects.except(:limit).count
421 render json: @object_list
425 # Caveat: this is highly dependent on the proxy setup. YMMV.
426 if request.headers.has_key?('HTTP_X_REAL_IP') then
427 # We're behind a reverse proxy
428 @remote_ip = request.headers['HTTP_X_REAL_IP']
430 # Hopefully, we are not!
431 @remote_ip = request.env['REMOTE_ADDR']
435 def self._index_requires_parameters
437 filters: { type: 'array', required: false },
438 where: { type: 'object', required: false },
439 order: { type: 'string', required: false }
443 def client_accepts_plain_text_stream
444 (request.headers['Accept'].split(' ') &
445 ['text/plain', '*/*']).count > 0
450 response = opts.first[:json]
451 if response.is_a?(Hash) &&
453 Thread.current[:request_starttime]
454 response[:_profile] = {
455 request_time: Time.now - Thread.current[:request_starttime]