1 class ApplicationController < ActionController::Base
2 include CurrentApiClient
5 before_filter :uncamelcase_params_hash_keys
6 around_filter :thread_with_auth_info, :except => [:render_error, :render_not_found]
8 before_filter :remote_ip
9 before_filter :login_required, :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]
16 attr_accessor :resource_attrs
20 if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
21 @objects.each(&:eager_load_associations)
28 render json: @object.as_api_response(:superuser)
30 render_not_found("object not found")
35 @object = model_class.new resource_attrs
41 attrs_to_update = resource_attrs.reject { |k,v| [:kind,:etag].index k }
42 if @object.update_attributes attrs_to_update
45 render json: { errors: @object.errors.full_messages }, status: 422
54 def catch_redirect_hint
56 if params.has_key?('redirect_to') then
57 session[:redirect_to] = params[:redirect_to]
62 unless Rails.application.config.consider_all_requests_local
63 rescue_from Exception,
64 :with => :render_error
65 rescue_from ActiveRecord::RecordNotFound,
66 :with => :render_not_found
67 rescue_from ActionController::RoutingError,
68 :with => :render_not_found
69 rescue_from ActionController::UnknownController,
70 :with => :render_not_found
71 rescue_from ActionController::UnknownAction,
72 :with => :render_not_found
76 logger.error e.inspect
77 logger.error e.backtrace.collect { |x| x + "\n" }.join('') if e.backtrace
78 if @object and @object.errors and @object.errors.full_messages and not @object.errors.full_messages.empty?
79 errors = @object.errors.full_messages
83 render json: { errors: errors }, status: 422
86 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
87 logger.error e.inspect
88 render json: { errors: ["Path not found"] }, status: 404
94 @where = params[:where] || {}
95 @where = Oj.load(@where) if @where.is_a?(String)
98 def find_objects_for_index
99 uuid_list = [current_user.uuid, *current_user.groups_i_can(:read)]
100 sanitized_uuid_list = uuid_list.
101 collect { |uuid| model_class.sanitize(uuid) }.join(', ')
102 or_references_me = ''
103 if model_class == Link and current_user
104 or_references_me = "OR #{model_class.sanitize current_user.uuid} IN (#{table_name}.head_uuid, #{table_name}.tail_uuid)"
106 @objects ||= model_class.
107 joins("LEFT JOIN links permissions ON permissions.head_uuid in (#{table_name}.owner, #{table_name}.uuid) AND permissions.tail_uuid in (#{sanitized_uuid_list}) AND permissions.link_class='permission'").
108 where("?=? OR #{table_name}.owner in (?) OR #{table_name}.uuid=? OR permissions.head_uuid IS NOT NULL #{or_references_me}",
109 true, current_user.is_admin,
114 @where.each do |attr,value|
115 if attr == 'any' or attr == :any
116 if value.is_a?(Array) and
117 value[0] == 'contains' and
118 model_class.columns.collect(&:name).index('name') then
119 conditions[0] << " and #{table_name}.name ilike ?"
120 conditions << "%#{value[1]}%"
122 elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
123 model_class.columns.collect(&:name).index(attr.to_s)
125 conditions[0] << " and #{table_name}.#{attr} is ?"
127 elsif value.is_a? Array
128 conditions[0] << " and #{table_name}.#{attr} in (?)"
130 elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
131 conditions[0] << " and #{table_name}.#{attr}=?"
133 elsif value.is_a? Hash
134 # Not quite the same thing as "equal?" but better than nothing?
137 conditions[0] << " and #{table_name}.#{attr} ilike ?"
138 conditions << "%#{k}%#{v}%"
144 if conditions.length > 1
145 conditions[0].sub!(/^1=1 and /, '')
152 @objects = @objects.limit(params[:limit].to_i)
154 raise ArgumentError.new("Invalid value for limit parameter")
157 @objects = @objects.limit(100)
161 params[:order].split(',').each do |order|
162 attr, direction = order.strip.split " "
164 if attr.match /^[a-z][_a-z0-9]+$/ and
165 model_class.columns.collect(&:name).index(attr) and
166 ['asc','desc'].index direction.downcase
167 orders << "#{table_name}.#{attr} #{direction.downcase}"
172 orders << "#{table_name}.modified_at desc"
174 @objects = @objects.order(orders.join ", ")
178 return @attrs if @attrs
179 @attrs = params[resource_name]
180 if @attrs.is_a? String
181 @attrs = uncamelcase_hash_keys(Oj.load @attrs)
183 unless @attrs.is_a? Hash
184 message = "No #{resource_name}"
185 if resource_name.index('_')
186 message << " (or #{resource_name.camelcase(:lower)})"
188 message << " hash provided with request"
189 raise ArgumentError.new(message)
191 %w(created_at modified_by_client modified_by_user modified_at).each do |x|
200 respond_to do |format|
202 redirect_to '/auth/joshid'
205 render :json => { errors: ['Not logged in'] }.to_json
212 unless current_user and current_user.is_admin
213 render :json => { errors: ['Forbidden'] }.to_json, status: 403
217 def thread_with_auth_info
221 api_client_auth = nil
223 params[:api_token] ||
224 params[:oauth_token] ||
225 request.headers["Authorization"].andand.match(/OAuth2 ([a-z0-9]+)/).andand[1]
227 api_client_auth = ApiClientAuthorization.
228 includes(:api_client, :user).
229 where('api_token=?', supplied_token).
232 session[:user_id] = api_client_auth.user.id
233 session[:api_client_uuid] = api_client_auth.api_client.uuid
234 session[:api_client_authorization_id] = api_client_auth.id
235 user = api_client_auth.user
236 api_client = api_client_auth.api_client
238 elsif session[:user_id]
239 user = User.find(session[:user_id]) rescue nil
240 api_client = ApiClient.
241 where('uuid=?',session[:api_client_uuid]).
243 if session[:api_client_authorization_id] then
244 api_client_auth = ApiClientAuthorization.
245 find session[:api_client_authorization_id]
248 Thread.current[:api_client_trusted] = session[:api_client_trusted]
249 Thread.current[:api_client_ip_address] = remote_ip
250 Thread.current[:api_client_authorization] = api_client_auth
251 Thread.current[:api_client_uuid] = api_client && api_client.uuid
252 Thread.current[:api_client] = api_client
253 Thread.current[:user] = user
256 Thread.current[:api_client_trusted] = nil
257 Thread.current[:api_client_ip_address] = nil
258 Thread.current[:api_client_authorization] = nil
259 Thread.current[:api_client_uuid] = nil
260 Thread.current[:api_client] = nil
261 Thread.current[:user] = nil
267 controller_name.classify.constantize
270 def resource_name # params[] key used by client
271 controller_name.singularize
278 def find_object_by_uuid
279 if params[:id] and params[:id].match /\D/
280 params[:uuid] = params.delete :id
282 @object = model_class.where('uuid=?', params[:uuid]).first
285 def self.accept_attribute_as_json(attr, force_class=nil)
286 before_filter lambda { accept_attribute_as_json attr, force_class }
288 def accept_attribute_as_json(attr, force_class)
289 if params[resource_name].is_a? Hash
290 if params[resource_name][attr].is_a? String
291 params[resource_name][attr] = Oj.load params[resource_name][attr]
292 if force_class and !params[resource_name][attr].is_a? force_class
293 raise TypeError.new("#{resource_name}[#{attr.to_s}] must be a #{force_class.to_s}")
299 def uncamelcase_params_hash_keys
300 self.params = uncamelcase_hash_keys(params)
302 def uncamelcase_hash_keys(h, max_depth=-1)
303 if h.is_a? Hash and max_depth != 0
308 elsif k.class == Symbol
309 nk = k.to_s.underscore.to_sym
313 nh[nk] = uncamelcase_hash_keys(v, max_depth-1)
322 :kind => "arvados##{resource_name}List",
325 :next_page_token => "",
327 :items => @objects.as_api_response(:superuser)
329 render json: @object_list
333 # Caveat: this is highly dependent on the proxy setup. YMMV.
334 if request.headers.has_key?('HTTP_X_REAL_IP') then
335 # We're behind a reverse proxy
336 @remote_ip = request.headers['HTTP_X_REAL_IP']
338 # Hopefully, we are not!
339 @remote_ip = request.env['REMOTE_ADDR']
343 def self._index_requires_parameters
345 where: { type: 'object', required: false },
346 order: { type: 'string', required: false }