1 class ApplicationController < ActionController::Base
2 include CurrentApiClient
5 around_filter :thread_with_auth_info, :except => [:render_error, :render_not_found]
7 before_filter :remote_ip
8 before_filter :require_auth_scope_all, :except => :render_not_found
9 before_filter :catch_redirect_hint
11 before_filter :load_where_param, :only => :index
12 before_filter :find_objects_for_index, :only => :index
13 before_filter :find_object_by_uuid, :except => [:index, :create,
16 before_filter :reload_object_before_update, :only => :update
17 before_filter :render_404_if_no_object, except: [:index, :create,
21 attr_accessor :resource_attrs
25 if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
26 @objects.each(&:eager_load_associations)
32 render json: @object.as_api_response
36 @object = model_class.new resource_attrs
40 render_error "Save failed"
45 attrs_to_update = resource_attrs.reject { |k,v|
46 [:kind, :etag, :href].index k
48 if @object.update_attributes attrs_to_update
51 render_error "Update failed"
60 def catch_redirect_hint
62 if params.has_key?('redirect_to') then
63 session[:redirect_to] = params[:redirect_to]
69 rescue_from Exception,
70 :with => :render_error
71 rescue_from ActiveRecord::RecordNotFound,
72 :with => :render_not_found
73 rescue_from ActionController::RoutingError,
74 :with => :render_not_found
75 rescue_from ActionController::UnknownController,
76 :with => :render_not_found
77 rescue_from AbstractController::ActionNotFound,
78 :with => :render_not_found
79 rescue_from ArvadosModel::PermissionDeniedError,
80 :with => :render_error
83 def render_404_if_no_object
84 render_not_found "Object not found" if !@object
88 logger.error e.inspect
89 logger.error e.backtrace.collect { |x| x + "\n" }.join('') if e.backtrace
90 if @object and @object.errors and @object.errors.full_messages and not @object.errors.full_messages.empty?
91 errors = @object.errors.full_messages
95 status = e.respond_to?(:http_status) ? e.http_status : 422
96 render json: { errors: errors }, status: status
99 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
100 logger.error e.inspect
101 render json: { errors: ["Path not found"] }, status: 404
107 if params[:where].nil? or params[:where] == ""
109 elsif params[:where].is_a? Hash
110 @where = params[:where]
111 elsif params[:where].is_a? String
113 @where = Oj.load(params[:where], symbol_keys: true)
115 raise ArgumentError.new("Could not parse \"where\" param as an object")
120 def find_objects_for_index
121 uuid_list = [current_user.uuid, *current_user.groups_i_can(:read)]
122 sanitized_uuid_list = uuid_list.
123 collect { |uuid| model_class.sanitize(uuid) }.join(', ')
124 or_references_me = ''
125 if model_class == Link and current_user
126 or_references_me = "OR (#{table_name}.link_class in (#{model_class.sanitize 'permission'}, #{model_class.sanitize 'resources'}) AND #{model_class.sanitize current_user.uuid} IN (#{table_name}.head_uuid, #{table_name}.tail_uuid))"
128 @objects ||= model_class.
129 joins("LEFT JOIN links permissions ON permissions.head_uuid in (#{table_name}.owner_uuid, #{table_name}.uuid) AND permissions.tail_uuid in (#{sanitized_uuid_list}) AND permissions.link_class='permission'").
130 where("?=? OR #{table_name}.owner_uuid in (?) OR #{table_name}.uuid=? OR permissions.head_uuid IS NOT NULL #{or_references_me}",
131 true, current_user.is_admin,
136 @where.each do |attr,value|
138 if value.is_a?(Array) and
139 value[0] == 'contains' and
140 model_class.columns.collect(&:name).index('name') then
142 model_class.searchable_columns.each do |column|
143 ilikes << "#{table_name}.#{column} ilike ?"
144 conditions << "%#{value[1]}%"
147 conditions[0] << ' and (' + ilikes.join(' or ') + ')'
150 elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
151 model_class.columns.collect(&:name).index(attr.to_s)
153 conditions[0] << " and #{table_name}.#{attr} is ?"
155 elsif value.is_a? Array
156 conditions[0] << " and #{table_name}.#{attr} in (?)"
158 elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
159 conditions[0] << " and #{table_name}.#{attr}=?"
161 elsif value.is_a? Hash
162 # Not quite the same thing as "equal?" but better than nothing?
165 conditions[0] << " and #{table_name}.#{attr} ilike ?"
166 conditions << "%#{k}%#{v}%"
172 if conditions.length > 1
173 conditions[0].sub!(/^1=1 and /, '')
180 @objects = @objects.limit(params[:limit].to_i)
182 raise ArgumentError.new("Invalid value for limit parameter")
185 @objects = @objects.limit(100)
189 params[:order].split(',').each do |order|
190 attr, direction = order.strip.split " "
192 if attr.match /^[a-z][_a-z0-9]+$/ and
193 model_class.columns.collect(&:name).index(attr) and
194 ['asc','desc'].index direction.downcase
195 orders << "#{table_name}.#{attr} #{direction.downcase}"
200 orders << "#{table_name}.modified_at desc"
202 @objects = @objects.order(orders.join ", ")
206 return @attrs if @attrs
207 @attrs = params[resource_name]
208 if @attrs.is_a? String
209 @attrs = Oj.load @attrs, symbol_keys: true
211 unless @attrs.is_a? Hash
212 message = "No #{resource_name}"
213 if resource_name.index('_')
214 message << " (or #{resource_name.camelcase(:lower)})"
216 message << " hash provided with request"
217 raise ArgumentError.new(message)
219 %w(created_at modified_by_client_uuid modified_by_user_uuid modified_at).each do |x|
220 @attrs.delete x.to_sym
230 respond_to do |format|
232 render :json => { errors: ['Not logged in'] }.to_json, status: 401
235 redirect_to '/auth/joshid'
243 unless current_user and current_user.is_admin
244 render :json => { errors: ['Forbidden'] }.to_json, status: 403
248 def require_auth_scope_all
249 require_login and require_auth_scope(['all'])
252 def require_auth_scope(ok_scopes)
253 unless current_api_client_auth_has_scope(ok_scopes)
254 render :json => { errors: ['Forbidden'] }.to_json, status: 403
258 def thread_with_auth_info
259 Thread.current[:request_starttime] = Time.now
260 Thread.current[:api_url_base] = root_url.sub(/\/$/,'') + '/arvados/v1'
264 api_client_auth = nil
266 params[:api_token] ||
267 params[:oauth_token] ||
268 request.headers["Authorization"].andand.match(/OAuth2 ([a-z0-9]+)/).andand[1]
270 api_client_auth = ApiClientAuthorization.
271 includes(:api_client, :user).
272 where('api_token=? and (expires_at is null or expires_at > now())', supplied_token).
274 if api_client_auth.andand.user
275 session[:user_id] = api_client_auth.user.id
276 session[:api_client_uuid] = api_client_auth.api_client.andand.uuid
277 session[:api_client_authorization_id] = api_client_auth.id
278 user = api_client_auth.user
279 api_client = api_client_auth.api_client
281 elsif session[:user_id]
282 user = User.find(session[:user_id]) rescue nil
283 api_client = ApiClient.
284 where('uuid=?',session[:api_client_uuid]).
286 if session[:api_client_authorization_id] then
287 api_client_auth = ApiClientAuthorization.
288 find session[:api_client_authorization_id]
291 Thread.current[:api_client_ip_address] = remote_ip
292 Thread.current[:api_client_authorization] = api_client_auth
293 Thread.current[:api_client_uuid] = api_client.andand.uuid
294 Thread.current[:api_client] = api_client
295 Thread.current[:user] = user
297 api_client_auth.last_used_at = Time.now
298 api_client_auth.last_used_by_ip_address = remote_ip
299 api_client_auth.save validate: false
303 Thread.current[:api_client_ip_address] = nil
304 Thread.current[:api_client_authorization] = nil
305 Thread.current[:api_client_uuid] = nil
306 Thread.current[:api_client] = nil
307 Thread.current[:user] = nil
313 controller_name.classify.constantize
316 def resource_name # params[] key used by client
317 controller_name.singularize
324 def find_object_by_uuid
325 if params[:id] and params[:id].match /\D/
326 params[:uuid] = params.delete :id
328 @where = { uuid: params[:uuid] }
329 find_objects_for_index
330 @object = @objects.first
333 def reload_object_before_update
334 # This is necessary to prevent an ActiveRecord::ReadOnlyRecord
335 # error when updating an object which was retrieved using a join.
336 if @object.andand.readonly?
337 @object = model_class.find_by_uuid(@objects.first.uuid)
341 def self.accept_attribute_as_json(attr, force_class=nil)
342 before_filter lambda { accept_attribute_as_json attr, force_class }
344 accept_attribute_as_json :properties, Hash
345 accept_attribute_as_json :info, Hash
346 def accept_attribute_as_json(attr, force_class)
347 if params[resource_name] and resource_attrs.is_a? Hash
348 if resource_attrs[attr].is_a? String
349 resource_attrs[attr] = Oj.load(resource_attrs[attr],
351 if force_class and !resource_attrs[attr].is_a? force_class
352 raise TypeError.new("#{resource_name}[#{attr.to_s}] must be a #{force_class.to_s}")
354 elsif resource_attrs[attr].is_a? Hash
355 # Convert symbol keys to strings (in hashes provided by
357 resource_attrs[attr] = resource_attrs[attr].
358 with_indifferent_access.to_hash
365 :kind => "arvados##{(@response_resource_name || resource_name).camelize(:lower)}List",
368 :next_page_token => "",
370 :items => @objects.as_api_response(nil)
372 if @objects.respond_to? :except
373 @object_list[:items_available] = @objects.except(:limit).count
375 render json: @object_list
379 # Caveat: this is highly dependent on the proxy setup. YMMV.
380 if request.headers.has_key?('HTTP_X_REAL_IP') then
381 # We're behind a reverse proxy
382 @remote_ip = request.headers['HTTP_X_REAL_IP']
384 # Hopefully, we are not!
385 @remote_ip = request.env['REMOTE_ADDR']
389 def self._index_requires_parameters
391 where: { type: 'object', required: false },
392 order: { type: 'string', required: false }
396 def client_accepts_plain_text_stream
397 (request.headers['Accept'].split(' ') &
398 ['text/plain', '*/*']).count > 0
402 response = opts.first[:json]
403 if response.is_a?(Hash) &&
405 Thread.current[:request_starttime]
406 response[:_profile] = {
407 request_time: Time.now - Thread.current[:request_starttime]