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
9 before_filter :remote_ip
10 before_filter :login_required, :except => :render_not_found
12 before_filter :catch_redirect_hint
14 def catch_redirect_hint
16 if params.has_key?('redirect_to') then
17 session[:redirect_to] = params[:redirect_to]
22 unless Rails.application.config.consider_all_requests_local
23 rescue_from Exception,
24 :with => :render_error
25 rescue_from ActiveRecord::RecordNotFound,
26 :with => :render_not_found
27 rescue_from ActionController::RoutingError,
28 :with => :render_not_found
29 rescue_from ActionController::UnknownController,
30 :with => :render_not_found
31 rescue_from ActionController::UnknownAction,
32 :with => :render_not_found
36 logger.error e.inspect
37 logger.error e.backtrace.collect { |x| x + "\n" }.join('') if e.backtrace
38 if @object and @object.errors and @object.errors.full_messages
39 errors = @object.errors.full_messages
43 render json: { errors: errors }, status: 422
46 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
47 logger.error e.inspect
48 render json: { errors: ["Path not found"] }, status: 404
52 @objects ||= model_class.
53 joins("LEFT JOIN metadata permissions ON permissions.tail=#{table_name}.uuid AND permissions.head=#{model_class.sanitize current_user.uuid} AND permissions.metadata_class='permission' AND permissions.name='visible_to'").
54 where("#{table_name}.created_by_user=? OR permissions.head IS NOT NULL",
57 where = params[:where]
58 where = JSON.parse(where) if where.is_a?(String)
60 where.each do |attr,value|
62 attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
63 model_class.columns.collect(&:name).index(attr))
65 conditions[0] << " and #{table_name}.#{attr} in (?)"
68 conditions[0] << " and #{table_name}.#{attr}=?"
73 if conditions.length > 1
74 conditions[0].sub!(/^1=1 and /, '')
79 if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
80 @objects.each(&:eager_load_associations)
87 render json: @object.as_api_response(:superuser)
89 render_not_found("object not found")
94 @attrs = params[resource_name]
96 raise "no #{resource_name} (or #{resource_name.camelcase(:lower)}) provided with request #{params.inspect}"
98 if @attrs.class == String
99 @attrs = uncamelcase_hash_keys(JSON.parse @attrs)
101 @object = model_class.new @attrs
107 @attrs = params[resource_name]
108 if @attrs.is_a? String
109 @attrs = uncamelcase_hash_keys(JSON.parse @attrs)
111 @object.update_attributes @attrs
120 respond_to do |format|
122 redirect_to '/auth/joshid'
125 render :json => { 'error' => 'Not logged in' }.to_json
131 def thread_with_auth_info
135 api_client_auth = nil
136 if params[:api_token]
137 api_client_auth = ApiClientAuthorization.
138 includes(:api_client, :user).
139 where('api_token=?', params[:api_token]).
142 session[:user_id] = api_client_auth.user.id
143 session[:api_client_uuid] = api_client_auth.api_client.uuid
144 user = api_client_auth.user
145 api_client = api_client_auth.api_client
147 elsif session[:user_id]
148 user = User.find(session[:user_id]) rescue nil
149 api_client = ApiClient.
150 where('uuid=?',session[:api_client_uuid]).
153 Thread.current[:api_client_trusted] = session[:api_client_trusted]
154 Thread.current[:api_client_ip_address] = remote_ip
155 Thread.current[:api_client] = api_client
156 Thread.current[:user] = user
159 Thread.current[:api_client_trusted] = nil
160 Thread.current[:api_client_ip_address] = nil
161 Thread.current[:api_client_uuid] = nil
162 Thread.current[:user] = nil
168 controller_name.classify.constantize
171 def resource_name # params[] key used by client
172 controller_name.singularize
179 def find_object_by_uuid
180 if params[:id] and params[:id].match /\D/
181 params[:uuid] = params.delete :id
183 @object = model_class.where('uuid=?', params[:uuid]).first
186 def self.accept_attribute_as_json(attr, force_class=nil)
187 before_filter lambda { accept_attribute_as_json attr, force_class }
189 def accept_attribute_as_json(attr, force_class)
190 if params[resource_name].is_a? Hash
191 if params[resource_name][attr].is_a? String
192 params[resource_name][attr] = JSON.parse params[resource_name][attr]
193 if force_class and !params[resource_name][attr].is_a? force_class
194 raise TypeError.new("#{resource_name}[#{attr.to_s}] must be a #{force_class.to_s}")
200 def uncamelcase_params_hash_keys
201 self.params = uncamelcase_hash_keys(params)
204 def uncamelcase_hash_keys(h, max_depth=-1)
205 if h.is_a? Hash and max_depth != 0
210 elsif k.class == Symbol
211 nk = k.to_s.underscore.to_sym
215 nh[nk] = uncamelcase_hash_keys(v, max_depth-1)
224 :kind => "orvos##{resource_name}List",
227 :next_page_token => "",
229 :items => @objects.as_api_response(:superuser)
231 render json: @object_list
235 # Caveat: this is highly dependent on the proxy setup. YMMV.
236 if request.headers.has_key?('HTTP_X_REAL_IP') then
237 # We're behind a reverse proxy
238 @remote_ip = request.headers['HTTP_X_REAL_IP']
240 # Hopefully, we are not!
241 @remote_ip = request.env['REMOTE_ADDR']