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 :find_objects_for_index, :only => :index
13 before_filter :find_object_by_uuid, :except => [:index, :create]
15 attr_accessor :resource_attrs
19 if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
20 @objects.each(&:eager_load_associations)
27 render json: @object.as_api_response(:superuser)
29 render_not_found("object not found")
34 @object = model_class.new resource_attrs
40 if @object.update_attributes resource_attrs
43 render json: { errors: @object.errors.full_messages }, status: 422
52 def catch_redirect_hint
54 if params.has_key?('redirect_to') then
55 session[:redirect_to] = params[:redirect_to]
60 unless Rails.application.config.consider_all_requests_local
61 rescue_from Exception,
62 :with => :render_error
63 rescue_from ActiveRecord::RecordNotFound,
64 :with => :render_not_found
65 rescue_from ActionController::RoutingError,
66 :with => :render_not_found
67 rescue_from ActionController::UnknownController,
68 :with => :render_not_found
69 rescue_from ActionController::UnknownAction,
70 :with => :render_not_found
74 logger.error e.inspect
75 logger.error e.backtrace.collect { |x| x + "\n" }.join('') if e.backtrace
76 if @object and @object.errors and @object.errors.full_messages
77 errors = @object.errors.full_messages
81 render json: { errors: errors }, status: 422
84 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
85 logger.error e.inspect
86 render json: { errors: ["Path not found"] }, status: 404
91 def find_objects_for_index
92 uuid_list = [current_user.uuid, *current_user.groups_i_can(:read)]
93 sanitized_uuid_list = uuid_list.
94 collect { |uuid| model_class.sanitize(uuid) }.join(', ')
95 @objects ||= model_class.
96 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'").
97 where("?=? OR #{table_name}.owner in (?) OR #{table_name}.uuid=? OR permissions.head_uuid IS NOT NULL",
98 true, current_user.is_admin,
101 @where = params[:where] || {}
102 @where = Oj.load(@where) if @where.is_a?(String)
105 @where.each do |attr,value|
107 if value.is_a?(Array) and
108 value[0] == 'contains' and
109 model_class.columns.collect(&:name).index('name') then
110 conditions[0] << " and #{table_name}.name ilike ?"
111 conditions << "%#{value[1]}%"
113 elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
114 model_class.columns.collect(&:name).index(attr)
116 conditions[0] << " and #{table_name}.#{attr} is ?"
118 elsif value.is_a? Array
119 conditions[0] << " and #{table_name}.#{attr} in (?)"
121 elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
122 conditions[0] << " and #{table_name}.#{attr}=?"
124 elsif value.is_a? Hash
125 # Not quite the same thing as "equal?" but better than nothing?
128 conditions[0] << " and #{table_name}.#{attr} ilike ?"
129 conditions << "%#{k}%#{v}%"
135 if conditions.length > 1
136 conditions[0].sub!(/^1=1 and /, '')
143 @objects = @objects.limit(params[:limit].to_i)
145 raise ArgumentError.new("Invalid value for limit parameter")
148 @objects = @objects.limit(100)
150 @objects = @objects.order("#{table_name}.modified_at desc")
154 return @attrs if @attrs
155 @attrs = params[resource_name]
156 if @attrs.is_a? String
157 @attrs = uncamelcase_hash_keys(Oj.load @attrs)
159 unless @attrs.is_a? Hash
160 message = "No #{resource_name}"
161 if resource_name.index('_')
162 message << " (or #{resource_name.camelcase(:lower)})"
164 message << " hash provided with request"
165 raise ArgumentError.new(message)
167 %w(created_at modified_by_client modified_by_user modified_at).each do |x|
176 respond_to do |format|
178 redirect_to '/auth/joshid'
181 render :json => { errors: ['Not logged in'] }.to_json
187 def thread_with_auth_info
191 api_client_auth = nil
193 params[:api_token] ||
194 params[:oauth_token] ||
195 request.headers["Authorization"].andand.match(/OAuth2 ([a-z0-9]+)/).andand[1]
197 api_client_auth = ApiClientAuthorization.
198 includes(:api_client, :user).
199 where('api_token=?', supplied_token).
202 session[:user_id] = api_client_auth.user.id
203 session[:api_client_uuid] = api_client_auth.api_client.uuid
204 session[:api_client_authorization_id] = api_client_auth.id
205 user = api_client_auth.user
206 api_client = api_client_auth.api_client
208 elsif session[:user_id]
209 user = User.find(session[:user_id]) rescue nil
210 api_client = ApiClient.
211 where('uuid=?',session[:api_client_uuid]).
213 if session[:api_client_authorization_id] then
214 api_client_auth = ApiClientAuthorization.
215 find session[:api_client_authorization_id]
218 Thread.current[:api_client_trusted] = session[:api_client_trusted]
219 Thread.current[:api_client_ip_address] = remote_ip
220 Thread.current[:api_client_authorization] = api_client_auth
221 Thread.current[:api_client_uuid] = api_client && api_client.uuid
222 Thread.current[:api_client] = api_client
223 Thread.current[:user] = user
226 Thread.current[:api_client_trusted] = nil
227 Thread.current[:api_client_ip_address] = nil
228 Thread.current[:api_client_authorization] = nil
229 Thread.current[:api_client_uuid] = nil
230 Thread.current[:api_client] = nil
231 Thread.current[:user] = nil
237 controller_name.classify.constantize
240 def resource_name # params[] key used by client
241 controller_name.singularize
248 def find_object_by_uuid
249 if params[:id] and params[:id].match /\D/
250 params[:uuid] = params.delete :id
252 @object = model_class.where('uuid=?', params[:uuid]).first
255 def self.accept_attribute_as_json(attr, force_class=nil)
256 before_filter lambda { accept_attribute_as_json attr, force_class }
258 def accept_attribute_as_json(attr, force_class)
259 if params[resource_name].is_a? Hash
260 if params[resource_name][attr].is_a? String
261 params[resource_name][attr] = Oj.load params[resource_name][attr]
262 if force_class and !params[resource_name][attr].is_a? force_class
263 raise TypeError.new("#{resource_name}[#{attr.to_s}] must be a #{force_class.to_s}")
269 def uncamelcase_params_hash_keys
270 self.params = uncamelcase_hash_keys(params)
272 def uncamelcase_hash_keys(h, max_depth=-1)
273 if h.is_a? Hash and max_depth != 0
278 elsif k.class == Symbol
279 nk = k.to_s.underscore.to_sym
283 nh[nk] = uncamelcase_hash_keys(v, max_depth-1)
292 :kind => "arvados##{resource_name}List",
295 :next_page_token => "",
297 :items => @objects.as_api_response(:superuser)
299 render json: @object_list
303 # Caveat: this is highly dependent on the proxy setup. YMMV.
304 if request.headers.has_key?('HTTP_X_REAL_IP') then
305 # We're behind a reverse proxy
306 @remote_ip = request.headers['HTTP_X_REAL_IP']
308 # Hopefully, we are not!
309 @remote_ip = request.env['REMOTE_ADDR']