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]
7 before_filter :find_object_by_uuid, :except => [:index, :create]
9 before_filter :remote_ip
10 before_filter :login_required, :except => :render_not_found
12 before_filter :catch_redirect_hint
13 attr_accessor :resource_attrs
15 def catch_redirect_hint
17 if params.has_key?('redirect_to') then
18 session[:redirect_to] = params[:redirect_to]
23 unless Rails.application.config.consider_all_requests_local
24 rescue_from Exception,
25 :with => :render_error
26 rescue_from ActiveRecord::RecordNotFound,
27 :with => :render_not_found
28 rescue_from ActionController::RoutingError,
29 :with => :render_not_found
30 rescue_from ActionController::UnknownController,
31 :with => :render_not_found
32 rescue_from ActionController::UnknownAction,
33 :with => :render_not_found
37 logger.error e.inspect
38 logger.error e.backtrace.collect { |x| x + "\n" }.join('') if e.backtrace
39 if @object and @object.errors and @object.errors.full_messages
40 errors = @object.errors.full_messages
44 render json: { errors: errors }, status: 422
47 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
48 logger.error e.inspect
49 render json: { errors: ["Path not found"] }, status: 404
53 uuid_list = [current_user.uuid, *current_user.groups_i_can(:read)]
54 sanitized_uuid_list = uuid_list.
55 collect { |uuid| model_class.sanitize(uuid) }.join(', ')
56 @objects ||= model_class.
57 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'").
58 where("?=? OR #{table_name}.owner in (?) OR #{table_name}.uuid=? OR permissions.head_uuid IS NOT NULL",
59 true, current_user.is_admin,
63 where = params[:where]
64 where = Oj.load(where) if where.is_a?(String)
66 where.each do |attr,value|
68 attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
69 model_class.columns.collect(&:name).index(attr))
71 conditions[0] << " and #{table_name}.#{attr} in (?)"
74 conditions[0] << " and #{table_name}.#{attr}=?"
77 elsif (!value.nil? and attr == 'any' and
78 value.is_a?(Array) and value[0] == 'contains' and
79 model_class.columns.collect(&:name).index('name')) then
80 conditions[0] << " and #{table_name}.name ilike ?"
81 conditions << "%#{value[1]}%"
84 if conditions.length > 1
85 conditions[0].sub!(/^1=1 and /, '')
92 @objects = @objects.limit(params[:limit].to_i)
94 raise "invalid argument (limit)"
97 @objects = @objects.limit(100)
99 @objects = @objects.order('modified_at desc')
101 if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
102 @objects.each(&:eager_load_associations)
109 render json: @object.as_api_response(:superuser)
111 render_not_found("object not found")
116 @object = model_class.new resource_attrs
122 @object.update_attributes resource_attrs
129 return @attrs if @attrs
130 @attrs = params[resource_name]
131 if @attrs.is_a? String
132 @attrs = uncamelcase_hash_keys(Oj.load @attrs)
134 unless @attrs.is_a? Hash
135 raise "no #{resource_name} (or #{resource_name.camelcase(:lower)}) hash provided with request #{params.inspect}"
137 %w(created_at modified_by_client modified_by_user modified_at).each do |x|
146 respond_to do |format|
148 redirect_to '/auth/joshid'
151 render :json => { errors: ['Not logged in'] }.to_json
157 def thread_with_auth_info
161 api_client_auth = nil
162 supplied_token = params[:api_token] || params[:oauth_token]
164 api_client_auth = ApiClientAuthorization.
165 includes(:api_client, :user).
166 where('api_token=?', supplied_token).
169 session[:user_id] = api_client_auth.user.id
170 session[:api_client_uuid] = api_client_auth.api_client.uuid
171 session[:api_client_authorization_id] = api_client_auth.id
172 user = api_client_auth.user
173 api_client = api_client_auth.api_client
175 elsif session[:user_id]
176 user = User.find(session[:user_id]) rescue nil
177 api_client = ApiClient.
178 where('uuid=?',session[:api_client_uuid]).
180 api_client_auth = ApiClientAuthorization.
181 find session[:api_client_authorization_id]
183 Thread.current[:api_client_trusted] = session[:api_client_trusted]
184 Thread.current[:api_client_ip_address] = remote_ip
185 Thread.current[:api_client_authorization] = api_client_auth
186 Thread.current[:api_client_uuid] = api_client && api_client.uuid
187 Thread.current[:api_client] = api_client
188 Thread.current[:user] = user
191 Thread.current[:api_client_trusted] = nil
192 Thread.current[:api_client_ip_address] = nil
193 Thread.current[:api_client_authorization] = nil
194 Thread.current[:api_client_uuid] = nil
195 Thread.current[:api_client] = nil
196 Thread.current[:user] = nil
202 controller_name.classify.constantize
205 def resource_name # params[] key used by client
206 controller_name.singularize
213 def find_object_by_uuid
214 if params[:id] and params[:id].match /\D/
215 params[:uuid] = params.delete :id
217 @object = model_class.where('uuid=?', params[:uuid]).first
220 def self.accept_attribute_as_json(attr, force_class=nil)
221 before_filter lambda { accept_attribute_as_json attr, force_class }
223 def accept_attribute_as_json(attr, force_class)
224 if params[resource_name].is_a? Hash
225 if params[resource_name][attr].is_a? String
226 params[resource_name][attr] = Oj.load params[resource_name][attr]
227 if force_class and !params[resource_name][attr].is_a? force_class
228 raise TypeError.new("#{resource_name}[#{attr.to_s}] must be a #{force_class.to_s}")
234 def uncamelcase_params_hash_keys
235 self.params = uncamelcase_hash_keys(params)
238 def uncamelcase_hash_keys(h, max_depth=-1)
239 if h.is_a? Hash and max_depth != 0
244 elsif k.class == Symbol
245 nk = k.to_s.underscore.to_sym
249 nh[nk] = uncamelcase_hash_keys(v, max_depth-1)
258 :kind => "orvos##{resource_name}List",
261 :next_page_token => "",
263 :items => @objects.as_api_response(:superuser)
265 render json: @object_list
269 # Caveat: this is highly dependent on the proxy setup. YMMV.
270 if request.headers.has_key?('HTTP_X_REAL_IP') then
271 # We're behind a reverse proxy
272 @remote_ip = request.headers['HTTP_X_REAL_IP']
274 # Hopefully, we are not!
275 @remote_ip = request.env['REMOTE_ADDR']