fix db query
[arvados.git] / app / controllers / application_controller.rb
1 class ApplicationController < ActionController::Base
2   include CurrentApiClient
3
4   protect_from_forgery
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
8
9   before_filter :remote_ip
10   before_filter :login_required, :except => :render_not_found
11
12   before_filter :catch_redirect_hint
13
14   def catch_redirect_hint
15     if !current_user
16       if params.has_key?('redirect_to') then
17         session[:redirect_to] = params[:redirect_to]
18       end
19     end
20   end
21
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
33   end
34
35   def render_error(e)
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
40     else
41       errors = [e.inspect]
42     end
43     render json: { errors: errors }, status: 422
44   end
45
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
49   end
50
51   def index
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)
57     if params[:where]
58       where = params[:where]
59       where = JSON.parse(where) if where.is_a?(String)
60       conditions = ['1=1']
61       where.each do |attr,value|
62         if (!value.nil? and
63             attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
64             model_class.columns.collect(&:name).index(attr))
65           if value.is_a? Array
66             conditions[0] << " and #{table_name}.#{attr} in (?)"
67             conditions << value
68           else
69             conditions[0] << " and #{table_name}.#{attr}=?"
70             conditions << value
71           end
72         end
73       end
74       if conditions.length > 1
75         conditions[0].sub!(/^1=1 and /, '')
76         @objects = @objects.
77           where(*conditions)
78       end
79     end
80     @objects.uniq!(&:id)
81     if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
82       @objects.each(&:eager_load_associations)
83     end
84     render_list
85   end
86
87   def show
88     if @object
89       render json: @object.as_api_response(:superuser)
90     else
91       render_not_found("object not found")
92     end
93   end
94
95   def create
96     @attrs = params[resource_name]
97     if @attrs.nil?
98       raise "no #{resource_name} (or #{resource_name.camelcase(:lower)}) provided with request #{params.inspect}"
99     end
100     if @attrs.class == String
101       @attrs = uncamelcase_hash_keys(JSON.parse @attrs)
102     end
103     @object = model_class.new @attrs
104     @object.save
105     show
106   end
107
108   def update
109     @attrs = params[resource_name]
110     if @attrs.is_a? String
111       @attrs = uncamelcase_hash_keys(JSON.parse @attrs)
112     end
113     @object.update_attributes @attrs
114     show
115   end
116
117   protected
118
119   # Authentication
120   def login_required
121     if !current_user
122       respond_to do |format|
123         format.html  {
124           redirect_to '/auth/joshid'
125         }
126         format.json {
127           render :json => { errors: ['Not logged in'] }.to_json
128         }
129       end
130     end
131   end
132
133   def thread_with_auth_info
134     begin
135       user = nil
136       api_client = nil
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]).
142           first
143         if api_client_auth
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
148         end
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]).
153           first rescue nil
154       end
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
159       yield
160     ensure
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
165     end
166   end
167   # /Authentication
168
169   def model_class
170     controller_name.classify.constantize
171   end
172
173   def resource_name             # params[] key used by client
174     controller_name.singularize
175   end
176
177   def table_name
178     controller_name
179   end
180
181   def find_object_by_uuid
182     if params[:id] and params[:id].match /\D/
183       params[:uuid] = params.delete :id
184     end
185     @object = model_class.where('uuid=?', params[:uuid]).first
186   end
187
188   def self.accept_attribute_as_json(attr, force_class=nil)
189     before_filter lambda { accept_attribute_as_json attr, force_class }
190   end
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}")
197         end
198       end
199     end
200   end
201
202   def uncamelcase_params_hash_keys
203     self.params = uncamelcase_hash_keys(params)
204   end
205
206   def uncamelcase_hash_keys(h, max_depth=-1)
207     if h.is_a? Hash and max_depth != 0
208       nh = Hash.new
209       h.each do |k,v|
210         if k.class == String
211           nk = k.underscore
212         elsif k.class == Symbol
213           nk = k.to_s.underscore.to_sym
214         else
215           nk = k
216         end
217         nh[nk] = uncamelcase_hash_keys(v, max_depth-1)
218       end
219       h.replace(nh)
220     end
221     h
222   end
223
224   def render_list
225     @object_list = {
226       :kind  => "orvos##{resource_name}List",
227       :etag => "",
228       :self_link => "",
229       :next_page_token => "",
230       :next_link => "",
231       :items => @objects.as_api_response(:superuser)
232     }
233     render json: @object_list
234   end
235
236   def remote_ip
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']
241     else
242       # Hopefully, we are not!
243       @remote_ip = request.env['REMOTE_ADDR']
244     end
245   end
246 end