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.head=#{table_name}.owner AND permissions.tail=#{model_class.sanitize current_user.uuid} AND permissions.metadata_class='permission'").
54 where("?=? OR #{table_name}.owner=? OR #{table_name}.uuid=? OR permissions.head IS NOT NULL",
55 true, current_user.is_admin,
56 current_user.uuid, current_user.uuid)
58 where = params[:where]
59 where = JSON.parse(where) if where.is_a?(String)
61 where.each do |attr,value|
63 attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
64 model_class.columns.collect(&:name).index(attr))
66 conditions[0] << " and #{table_name}.#{attr} in (?)"
69 conditions[0] << " and #{table_name}.#{attr}=?"
74 if conditions.length > 1
75 conditions[0].sub!(/^1=1 and /, '')
81 if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
82 @objects.each(&:eager_load_associations)
89 render json: @object.as_api_response(:superuser)
91 render_not_found("object not found")
96 @attrs = params[resource_name]
98 raise "no #{resource_name} (or #{resource_name.camelcase(:lower)}) provided with request #{params.inspect}"
100 if @attrs.class == String
101 @attrs = uncamelcase_hash_keys(JSON.parse @attrs)
103 @object = model_class.new @attrs
109 @attrs = params[resource_name]
110 if @attrs.is_a? String
111 @attrs = uncamelcase_hash_keys(JSON.parse @attrs)
113 @object.update_attributes @attrs
122 respond_to do |format|
124 redirect_to '/auth/joshid'
127 render :json => { errors: ['Not logged in'] }.to_json
133 def thread_with_auth_info
137 api_client_auth = nil
138 if params[:api_token]
139 api_client_auth = ApiClientAuthorization.
140 includes(:api_client, :user).
141 where('api_token=?', params[:api_token]).
144 session[:user_id] = api_client_auth.user.id
145 session[:api_client_uuid] = api_client_auth.api_client.uuid
146 user = api_client_auth.user
147 api_client = api_client_auth.api_client
149 elsif session[:user_id]
150 user = User.find(session[:user_id]) rescue nil
151 api_client = ApiClient.
152 where('uuid=?',session[:api_client_uuid]).
155 Thread.current[:api_client_trusted] = session[:api_client_trusted]
156 Thread.current[:api_client_ip_address] = remote_ip
157 Thread.current[:api_client] = api_client
158 Thread.current[:user] = user
161 Thread.current[:api_client_trusted] = nil
162 Thread.current[:api_client_ip_address] = nil
163 Thread.current[:api_client_uuid] = nil
164 Thread.current[:user] = nil
170 controller_name.classify.constantize
173 def resource_name # params[] key used by client
174 controller_name.singularize
181 def find_object_by_uuid
182 if params[:id] and params[:id].match /\D/
183 params[:uuid] = params.delete :id
185 @object = model_class.where('uuid=?', params[:uuid]).first
188 def self.accept_attribute_as_json(attr, force_class=nil)
189 before_filter lambda { accept_attribute_as_json attr, force_class }
191 def accept_attribute_as_json(attr, force_class)
192 if params[resource_name].is_a? Hash
193 if params[resource_name][attr].is_a? String
194 params[resource_name][attr] = JSON.parse params[resource_name][attr]
195 if force_class and !params[resource_name][attr].is_a? force_class
196 raise TypeError.new("#{resource_name}[#{attr.to_s}] must be a #{force_class.to_s}")
202 def uncamelcase_params_hash_keys
203 self.params = uncamelcase_hash_keys(params)
206 def uncamelcase_hash_keys(h, max_depth=-1)
207 if h.is_a? Hash and max_depth != 0
212 elsif k.class == Symbol
213 nk = k.to_s.underscore.to_sym
217 nh[nk] = uncamelcase_hash_keys(v, max_depth-1)
226 :kind => "orvos##{resource_name}List",
229 :next_page_token => "",
231 :items => @objects.as_api_response(:superuser)
233 render json: @object_list
237 # Caveat: this is highly dependent on the proxy setup. YMMV.
238 if request.headers.has_key?('HTTP_X_REAL_IP') then
239 # We're behind a reverse proxy
240 @remote_ip = request.headers['HTTP_X_REAL_IP']
242 # Hopefully, we are not!
243 @remote_ip = request.env['REMOTE_ADDR']