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 if @object.update_attributes resource_attrs
44 render json: { errors: @object.errors.full_messages }, status: 422
53 def catch_redirect_hint
55 if params.has_key?('redirect_to') then
56 session[:redirect_to] = params[:redirect_to]
61 unless Rails.application.config.consider_all_requests_local
62 rescue_from Exception,
63 :with => :render_error
64 rescue_from ActiveRecord::RecordNotFound,
65 :with => :render_not_found
66 rescue_from ActionController::RoutingError,
67 :with => :render_not_found
68 rescue_from ActionController::UnknownController,
69 :with => :render_not_found
70 rescue_from ActionController::UnknownAction,
71 :with => :render_not_found
75 logger.error e.inspect
76 logger.error e.backtrace.collect { |x| x + "\n" }.join('') if e.backtrace
77 if @object and @object.errors and @object.errors.full_messages
78 errors = @object.errors.full_messages
82 render json: { errors: errors }, status: 422
85 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
86 logger.error e.inspect
87 render json: { errors: ["Path not found"] }, status: 404
93 @where = params[:where] || {}
94 @where = Oj.load(@where) if @where.is_a?(String)
97 def find_objects_for_index
98 uuid_list = [current_user.uuid, *current_user.groups_i_can(:read)]
99 sanitized_uuid_list = uuid_list.
100 collect { |uuid| model_class.sanitize(uuid) }.join(', ')
101 @objects ||= model_class.
102 joins("LEFT JOIN links permissions ON permissions.head_uuid=#{table_name}.owner AND permissions.tail_uuid in (#{sanitized_uuid_list}) AND permissions.link_class='permission'").
103 where("?=? OR #{table_name}.owner in (?) OR #{table_name}.uuid=? OR permissions.head_uuid IS NOT NULL",
104 true, current_user.is_admin,
109 @where.each do |attr,value|
110 if attr == 'any' or attr == :any
111 if value.is_a?(Array) and
112 value[0] == 'contains' and
113 model_class.columns.collect(&:name).index('name') then
114 conditions[0] << " and #{table_name}.name ilike ?"
115 conditions << "%#{value[1]}%"
117 elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
118 model_class.columns.collect(&:name).index(attr.to_s)
120 conditions[0] << " and #{table_name}.#{attr} is ?"
122 elsif value.is_a? Array
123 conditions[0] << " and #{table_name}.#{attr} in (?)"
125 elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
126 conditions[0] << " and #{table_name}.#{attr}=?"
128 elsif value.is_a? Hash
129 # Not quite the same thing as "equal?" but better than nothing?
132 conditions[0] << " and #{table_name}.#{attr} ilike ?"
133 conditions << "%#{k}%#{v}%"
139 if conditions.length > 1
140 conditions[0].sub!(/^1=1 and /, '')
147 @objects = @objects.limit(params[:limit].to_i)
149 raise ArgumentError.new("Invalid value for limit parameter")
152 @objects = @objects.limit(100)
156 params[:order].split(',').each do |order|
157 attr, direction = order.strip.split " "
159 if attr.match /^[a-z][_a-z0-9]+$/ and
160 model_class.columns.collect(&:name).index(attr) and
161 ['asc','desc'].index direction.downcase
162 orders << "#{table_name}.#{attr} #{direction.downcase}"
167 orders << "#{table_name}.modified_at desc"
169 @objects = @objects.order(orders.join ", ")
173 return @attrs if @attrs
174 @attrs = params[resource_name]
175 if @attrs.is_a? String
176 @attrs = uncamelcase_hash_keys(Oj.load @attrs)
178 unless @attrs.is_a? Hash
179 message = "No #{resource_name}"
180 if resource_name.index('_')
181 message << " (or #{resource_name.camelcase(:lower)})"
183 message << " hash provided with request"
184 raise ArgumentError.new(message)
186 %w(created_at modified_by_client modified_by_user modified_at).each do |x|
195 respond_to do |format|
197 redirect_to '/auth/joshid'
200 render :json => { errors: ['Not logged in'] }.to_json
206 def thread_with_auth_info
210 api_client_auth = nil
212 params[:api_token] ||
213 params[:oauth_token] ||
214 request.headers["Authorization"].andand.match(/OAuth2 ([a-z0-9]+)/).andand[1]
216 api_client_auth = ApiClientAuthorization.
217 includes(:api_client, :user).
218 where('api_token=?', supplied_token).
221 session[:user_id] = api_client_auth.user.id
222 session[:api_client_uuid] = api_client_auth.api_client.uuid
223 session[:api_client_authorization_id] = api_client_auth.id
224 user = api_client_auth.user
225 api_client = api_client_auth.api_client
227 elsif session[:user_id]
228 user = User.find(session[:user_id]) rescue nil
229 api_client = ApiClient.
230 where('uuid=?',session[:api_client_uuid]).
232 if session[:api_client_authorization_id] then
233 api_client_auth = ApiClientAuthorization.
234 find session[:api_client_authorization_id]
237 Thread.current[:api_client_trusted] = session[:api_client_trusted]
238 Thread.current[:api_client_ip_address] = remote_ip
239 Thread.current[:api_client_authorization] = api_client_auth
240 Thread.current[:api_client_uuid] = api_client && api_client.uuid
241 Thread.current[:api_client] = api_client
242 Thread.current[:user] = user
245 Thread.current[:api_client_trusted] = nil
246 Thread.current[:api_client_ip_address] = nil
247 Thread.current[:api_client_authorization] = nil
248 Thread.current[:api_client_uuid] = nil
249 Thread.current[:api_client] = nil
250 Thread.current[:user] = nil
256 controller_name.classify.constantize
259 def resource_name # params[] key used by client
260 controller_name.singularize
267 def find_object_by_uuid
268 if params[:id] and params[:id].match /\D/
269 params[:uuid] = params.delete :id
271 @object = model_class.where('uuid=?', params[:uuid]).first
274 def self.accept_attribute_as_json(attr, force_class=nil)
275 before_filter lambda { accept_attribute_as_json attr, force_class }
277 def accept_attribute_as_json(attr, force_class)
278 if params[resource_name].is_a? Hash
279 if params[resource_name][attr].is_a? String
280 params[resource_name][attr] = Oj.load params[resource_name][attr]
281 if force_class and !params[resource_name][attr].is_a? force_class
282 raise TypeError.new("#{resource_name}[#{attr.to_s}] must be a #{force_class.to_s}")
288 def uncamelcase_params_hash_keys
289 self.params = uncamelcase_hash_keys(params)
291 def uncamelcase_hash_keys(h, max_depth=-1)
292 if h.is_a? Hash and max_depth != 0
297 elsif k.class == Symbol
298 nk = k.to_s.underscore.to_sym
302 nh[nk] = uncamelcase_hash_keys(v, max_depth-1)
311 :kind => "arvados##{resource_name}List",
314 :next_page_token => "",
316 :items => @objects.as_api_response(:superuser)
318 render json: @object_list
322 # Caveat: this is highly dependent on the proxy setup. YMMV.
323 if request.headers.has_key?('HTTP_X_REAL_IP') then
324 # We're behind a reverse proxy
325 @remote_ip = request.headers['HTTP_X_REAL_IP']
327 # Hopefully, we are not!
328 @remote_ip = request.env['REMOTE_ADDR']