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
42 render_error "Save failed"
47 attrs_to_update = resource_attrs.reject { |k,v|
48 [:kind, :etag, :href].index k
50 if @object.update_attributes attrs_to_update
53 render_error "Update failed"
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 logger.error e.backtrace.collect { |x| x + "\n" }.join('') if e.backtrace
92 if @object and @object.errors and @object.errors.full_messages and not @object.errors.full_messages.empty?
93 errors = @object.errors.full_messages
97 status = e.respond_to?(:http_status) ? e.http_status : 422
98 render json: { errors: errors }, status: status
101 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
102 logger.error e.inspect
103 render json: { errors: ["Path not found"] }, status: 404
109 if params[:where].nil? or params[:where] == ""
111 elsif params[:where].is_a? Hash
112 @where = params[:where]
113 elsif params[:where].is_a? String
115 @where = Oj.load(params[:where])
116 raise unless @where.is_a? Hash
118 raise ArgumentError.new("Could not parse \"where\" param as an object")
121 @where = @where.with_indifferent_access
124 def load_filters_param
125 if params[:filters].is_a? Array
126 @filters = params[:filters]
127 elsif params[:filters].is_a? String
129 @filters = Oj.load params[:filters]
130 raise unless @filters.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.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 operator.match(/[<=>]/) and
155 model_class.attribute_column(attr).type == :datetime
156 operand = Time.parse operand
161 if operand.is_a? Array
162 cond_out << "#{table_name}.#{attr} IN (?)"
168 @objects = @objects.where(cond_out.join(' AND '), *param_out)
171 if @where.is_a? Hash and @where.any?
173 @where.each do |attr,value|
175 if value.is_a?(Array) and
176 value.length == 2 and
177 value[0] == 'contains' and
178 model_class.columns.collect(&:name).index('name') then
180 model_class.searchable_columns.each do |column|
181 ilikes << "#{table_name}.#{column} ilike ?"
182 conditions << "%#{value[1]}%"
185 conditions[0] << ' and (' + ilikes.join(' or ') + ')'
188 elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
189 model_class.columns.collect(&:name).index(attr.to_s)
191 conditions[0] << " and #{table_name}.#{attr} is ?"
193 elsif value.is_a? Array
194 if value[0] == 'contains' and value.length == 2
195 conditions[0] << " and #{table_name}.#{attr} like ?"
196 conditions << "%#{value[1]}%"
198 conditions[0] << " and #{table_name}.#{attr} in (?)"
201 elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
202 conditions[0] << " and #{table_name}.#{attr}=?"
204 elsif value.is_a? Hash
205 # Not quite the same thing as "equal?" but better than nothing?
208 conditions[0] << " and #{table_name}.#{attr} ilike ?"
209 conditions << "%#{k}%#{v}%"
215 if conditions.length > 1
216 conditions[0].sub!(/^1=1 and /, '')
223 @objects = @objects.limit(params[:limit].to_i)
225 raise ArgumentError.new("Invalid value for limit parameter")
228 @objects = @objects.limit(100)
232 params[:order].split(',').each do |order|
233 attr, direction = order.strip.split " "
235 if attr.match /^[a-z][_a-z0-9]+$/ and
236 model_class.columns.collect(&:name).index(attr) and
237 ['asc','desc'].index direction.downcase
238 orders << "#{table_name}.#{attr} #{direction.downcase}"
243 orders << "#{table_name}.modified_at desc"
245 @objects = @objects.order(orders.join ", ")
249 return @attrs if @attrs
250 @attrs = params[resource_name]
251 if @attrs.is_a? String
252 @attrs = Oj.load @attrs, symbol_keys: true
254 unless @attrs.is_a? Hash
255 message = "No #{resource_name}"
256 if resource_name.index('_')
257 message << " (or #{resource_name.camelcase(:lower)})"
259 message << " hash provided with request"
260 raise ArgumentError.new(message)
262 %w(created_at modified_by_client_uuid modified_by_user_uuid modified_at).each do |x|
263 @attrs.delete x.to_sym
265 @attrs = @attrs.symbolize_keys if @attrs.is_a? HashWithIndifferentAccess
274 respond_to do |format|
276 render :json => { errors: ['Not logged in'] }.to_json, status: 401
279 redirect_to '/auth/joshid'
287 unless current_user and current_user.is_admin
288 render :json => { errors: ['Forbidden'] }.to_json, status: 403
292 def require_auth_scope_all
293 require_login and require_auth_scope(['all'])
296 def require_auth_scope(ok_scopes)
297 unless current_api_client_auth_has_scope(ok_scopes)
298 render :json => { errors: ['Forbidden'] }.to_json, status: 403
302 def thread_with_auth_info
303 Thread.current[:request_starttime] = Time.now
304 Thread.current[:api_url_base] = root_url.sub(/\/$/,'') + '/arvados/v1'
308 api_client_auth = nil
310 params[:api_token] ||
311 params[:oauth_token] ||
312 request.headers["Authorization"].andand.match(/OAuth2 ([a-z0-9]+)/).andand[1]
314 api_client_auth = ApiClientAuthorization.
315 includes(:api_client, :user).
316 where('api_token=? and (expires_at is null or expires_at > now())', supplied_token).
318 if api_client_auth.andand.user
319 session[:user_id] = api_client_auth.user.id
320 session[:api_client_uuid] = api_client_auth.api_client.andand.uuid
321 session[:api_client_authorization_id] = api_client_auth.id
322 user = api_client_auth.user
323 api_client = api_client_auth.api_client
325 elsif session[:user_id]
326 user = User.find(session[:user_id]) rescue nil
327 api_client = ApiClient.
328 where('uuid=?',session[:api_client_uuid]).
330 if session[:api_client_authorization_id] then
331 api_client_auth = ApiClientAuthorization.
332 find session[:api_client_authorization_id]
335 Thread.current[:api_client_ip_address] = remote_ip
336 Thread.current[:api_client_authorization] = api_client_auth
337 Thread.current[:api_client_uuid] = api_client.andand.uuid
338 Thread.current[:api_client] = api_client
339 Thread.current[:user] = user
341 api_client_auth.last_used_at = Time.now
342 api_client_auth.last_used_by_ip_address = remote_ip
343 api_client_auth.save validate: false
347 Thread.current[:api_client_ip_address] = nil
348 Thread.current[:api_client_authorization] = nil
349 Thread.current[:api_client_uuid] = nil
350 Thread.current[:api_client] = nil
351 Thread.current[:user] = nil
357 controller_name.classify.constantize
360 def resource_name # params[] key used by client
361 controller_name.singularize
368 def find_object_by_uuid
369 if params[:id] and params[:id].match /\D/
370 params[:uuid] = params.delete :id
372 @where = { uuid: params[:uuid] }
373 find_objects_for_index
374 @object = @objects.first
377 def reload_object_before_update
378 # This is necessary to prevent an ActiveRecord::ReadOnlyRecord
379 # error when updating an object which was retrieved using a join.
380 if @object.andand.readonly?
381 @object = model_class.find_by_uuid(@objects.first.uuid)
385 def self.accept_attribute_as_json(attr, force_class=nil)
386 before_filter lambda { accept_attribute_as_json attr, force_class }
388 accept_attribute_as_json :properties, Hash
389 accept_attribute_as_json :info, Hash
390 def accept_attribute_as_json(attr, force_class)
391 if params[resource_name] and resource_attrs.is_a? Hash
392 if resource_attrs[attr].is_a? String
393 resource_attrs[attr] = Oj.load(resource_attrs[attr],
395 if force_class and !resource_attrs[attr].is_a? force_class
396 raise TypeError.new("#{resource_name}[#{attr.to_s}] must be a #{force_class.to_s}")
398 elsif resource_attrs[attr].is_a? Hash
399 # Convert symbol keys to strings (in hashes provided by
401 resource_attrs[attr] = resource_attrs[attr].
402 with_indifferent_access.to_hash
409 :kind => "arvados##{(@response_resource_name || resource_name).camelize(:lower)}List",
412 :next_page_token => "",
414 :items => @objects.as_api_response(nil)
416 if @objects.respond_to? :except
417 @object_list[:items_available] = @objects.except(:limit).count
419 render json: @object_list
423 # Caveat: this is highly dependent on the proxy setup. YMMV.
424 if request.headers.has_key?('HTTP_X_REAL_IP') then
425 # We're behind a reverse proxy
426 @remote_ip = request.headers['HTTP_X_REAL_IP']
428 # Hopefully, we are not!
429 @remote_ip = request.env['REMOTE_ADDR']
433 def self._index_requires_parameters
435 filters: { type: 'array', required: false },
436 where: { type: 'object', required: false },
437 order: { type: 'string', required: false }
441 def client_accepts_plain_text_stream
442 (request.headers['Accept'].split(' ') &
443 ['text/plain', '*/*']).count > 0
447 response = opts.first[:json]
448 if response.is_a?(Hash) &&
450 Thread.current[:request_starttime]
451 response[:_profile] = {
452 request_time: Time.now - Thread.current[:request_starttime]