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 :find_objects_for_index, :only => :index
14 before_filter :find_object_by_uuid, :except => [:index, :create,
17 before_filter :reload_object_before_update, :only => :update
18 before_filter :render_404_if_no_object, except: [:index, :create,
22 attr_accessor :resource_attrs
26 if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
27 @objects.each(&:eager_load_associations)
33 render json: @object.as_api_response
37 @object = model_class.new resource_attrs
41 render_error "Save failed"
46 attrs_to_update = resource_attrs.reject { |k,v|
47 [:kind, :etag, :href].index k
49 if @object.update_attributes attrs_to_update
52 render_error "Update failed"
61 def catch_redirect_hint
63 if params.has_key?('redirect_to') then
64 session[:redirect_to] = params[:redirect_to]
70 rescue_from Exception,
71 :with => :render_error
72 rescue_from ActiveRecord::RecordNotFound,
73 :with => :render_not_found
74 rescue_from ActionController::RoutingError,
75 :with => :render_not_found
76 rescue_from ActionController::UnknownController,
77 :with => :render_not_found
78 rescue_from AbstractController::ActionNotFound,
79 :with => :render_not_found
80 rescue_from ArvadosModel::PermissionDeniedError,
81 :with => :render_error
84 def render_404_if_no_object
85 render_not_found "Object not found" if !@object
89 logger.error e.inspect
90 logger.error e.backtrace.collect { |x| x + "\n" }.join('') if e.backtrace
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], symbol_keys: true)
116 raise ArgumentError.new("Could not parse \"where\" param as an object")
121 def find_objects_for_index
122 @objects ||= model_class.readable_by(current_user)
125 @where.each do |attr,value|
127 if value.is_a?(Array) and
128 value[0] == 'contains' and
129 model_class.columns.collect(&:name).index('name') then
131 model_class.searchable_columns.each do |column|
132 ilikes << "#{table_name}.#{column} ilike ?"
133 conditions << "%#{value[1]}%"
136 conditions[0] << ' and (' + ilikes.join(' or ') + ')'
139 elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
140 model_class.columns.collect(&:name).index(attr.to_s)
142 conditions[0] << " and #{table_name}.#{attr} is ?"
144 elsif value.is_a? Array
145 conditions[0] << " and #{table_name}.#{attr} in (?)"
147 elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
148 conditions[0] << " and #{table_name}.#{attr}=?"
150 elsif value.is_a? Hash
151 # Not quite the same thing as "equal?" but better than nothing?
154 conditions[0] << " and #{table_name}.#{attr} ilike ?"
155 conditions << "%#{k}%#{v}%"
161 if conditions.length > 1
162 conditions[0].sub!(/^1=1 and /, '')
169 @objects = @objects.limit(params[:limit].to_i)
171 raise ArgumentError.new("Invalid value for limit parameter")
174 @objects = @objects.limit(100)
178 params[:order].split(',').each do |order|
179 attr, direction = order.strip.split " "
181 if attr.match /^[a-z][_a-z0-9]+$/ and
182 model_class.columns.collect(&:name).index(attr) and
183 ['asc','desc'].index direction.downcase
184 orders << "#{table_name}.#{attr} #{direction.downcase}"
189 orders << "#{table_name}.modified_at desc"
191 @objects = @objects.order(orders.join ", ")
195 return @attrs if @attrs
196 @attrs = params[resource_name]
197 if @attrs.is_a? String
198 @attrs = Oj.load @attrs, symbol_keys: true
200 unless @attrs.is_a? Hash
201 message = "No #{resource_name}"
202 if resource_name.index('_')
203 message << " (or #{resource_name.camelcase(:lower)})"
205 message << " hash provided with request"
206 raise ArgumentError.new(message)
208 %w(created_at modified_by_client_uuid modified_by_user_uuid modified_at).each do |x|
209 @attrs.delete x.to_sym
211 @attrs = @attrs.symbolize_keys if @attrs.is_a? HashWithIndifferentAccess
220 respond_to do |format|
222 render :json => { errors: ['Not logged in'] }.to_json, status: 401
225 redirect_to '/auth/joshid'
233 unless current_user and current_user.is_admin
234 render :json => { errors: ['Forbidden'] }.to_json, status: 403
238 def require_auth_scope_all
239 require_login and require_auth_scope(['all'])
242 def require_auth_scope(ok_scopes)
243 unless current_api_client_auth_has_scope(ok_scopes)
244 render :json => { errors: ['Forbidden'] }.to_json, status: 403
248 def thread_with_auth_info
249 Thread.current[:request_starttime] = Time.now
250 Thread.current[:api_url_base] = root_url.sub(/\/$/,'') + '/arvados/v1'
254 api_client_auth = nil
256 params[:api_token] ||
257 params[:oauth_token] ||
258 request.headers["Authorization"].andand.match(/OAuth2 ([a-z0-9]+)/).andand[1]
260 api_client_auth = ApiClientAuthorization.
261 includes(:api_client, :user).
262 where('api_token=? and (expires_at is null or expires_at > now())', supplied_token).
264 if api_client_auth.andand.user
265 session[:user_id] = api_client_auth.user.id
266 session[:api_client_uuid] = api_client_auth.api_client.andand.uuid
267 session[:api_client_authorization_id] = api_client_auth.id
268 user = api_client_auth.user
269 api_client = api_client_auth.api_client
271 elsif session[:user_id]
272 user = User.find(session[:user_id]) rescue nil
273 api_client = ApiClient.
274 where('uuid=?',session[:api_client_uuid]).
276 if session[:api_client_authorization_id] then
277 api_client_auth = ApiClientAuthorization.
278 find session[:api_client_authorization_id]
281 Thread.current[:api_client_ip_address] = remote_ip
282 Thread.current[:api_client_authorization] = api_client_auth
283 Thread.current[:api_client_uuid] = api_client.andand.uuid
284 Thread.current[:api_client] = api_client
285 Thread.current[:user] = user
287 api_client_auth.last_used_at = Time.now
288 api_client_auth.last_used_by_ip_address = remote_ip
289 api_client_auth.save validate: false
293 Thread.current[:api_client_ip_address] = nil
294 Thread.current[:api_client_authorization] = nil
295 Thread.current[:api_client_uuid] = nil
296 Thread.current[:api_client] = nil
297 Thread.current[:user] = nil
303 controller_name.classify.constantize
306 def resource_name # params[] key used by client
307 controller_name.singularize
314 def find_object_by_uuid
315 if params[:id] and params[:id].match /\D/
316 params[:uuid] = params.delete :id
318 @where = { uuid: params[:uuid] }
319 find_objects_for_index
320 @object = @objects.first
323 def reload_object_before_update
324 # This is necessary to prevent an ActiveRecord::ReadOnlyRecord
325 # error when updating an object which was retrieved using a join.
326 if @object.andand.readonly?
327 @object = model_class.find_by_uuid(@objects.first.uuid)
331 def self.accept_attribute_as_json(attr, force_class=nil)
332 before_filter lambda { accept_attribute_as_json attr, force_class }
334 accept_attribute_as_json :properties, Hash
335 accept_attribute_as_json :info, Hash
336 def accept_attribute_as_json(attr, force_class)
337 if params[resource_name] and resource_attrs.is_a? Hash
338 if resource_attrs[attr].is_a? String
339 resource_attrs[attr] = Oj.load(resource_attrs[attr],
341 if force_class and !resource_attrs[attr].is_a? force_class
342 raise TypeError.new("#{resource_name}[#{attr.to_s}] must be a #{force_class.to_s}")
344 elsif resource_attrs[attr].is_a? Hash
345 # Convert symbol keys to strings (in hashes provided by
347 resource_attrs[attr] = resource_attrs[attr].
348 with_indifferent_access.to_hash
355 :kind => "arvados##{(@response_resource_name || resource_name).camelize(:lower)}List",
358 :next_page_token => "",
360 :items => @objects.as_api_response(nil)
362 if @objects.respond_to? :except
363 @object_list[:items_available] = @objects.except(:limit).count
365 render json: @object_list
369 # Caveat: this is highly dependent on the proxy setup. YMMV.
370 if request.headers.has_key?('HTTP_X_REAL_IP') then
371 # We're behind a reverse proxy
372 @remote_ip = request.headers['HTTP_X_REAL_IP']
374 # Hopefully, we are not!
375 @remote_ip = request.env['REMOTE_ADDR']
379 def self._index_requires_parameters
381 where: { type: 'object', required: false },
382 order: { type: 'string', required: false }
386 def client_accepts_plain_text_stream
387 (request.headers['Accept'].split(' ') &
388 ['text/plain', '*/*']).count > 0
392 response = opts.first[:json]
393 if response.is_a?(Hash) &&
395 Thread.current[:request_starttime]
396 response[:_profile] = {
397 request_time: Time.now - Thread.current[:request_starttime]