catch and propagate errors during #update
[arvados.git] / services / api / 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
8   before_filter :remote_ip
9   before_filter :login_required, :except => :render_not_found
10   before_filter :catch_redirect_hint
11
12   before_filter :find_objects_for_index, :only => :index
13   before_filter :find_object_by_uuid, :except => [:index, :create]
14
15   attr_accessor :resource_attrs
16
17   def index
18     @objects.uniq!(&:id)
19     if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
20       @objects.each(&:eager_load_associations)
21     end
22     render_list
23   end
24
25   def show
26     if @object
27       render json: @object.as_api_response(:superuser)
28     else
29       render_not_found("object not found")
30     end
31   end
32
33   def create
34     @object = model_class.new resource_attrs
35     @object.save
36     show
37   end
38
39   def update
40     if @object.update_attributes resource_attrs
41       show
42     else
43       render json: { errors: @object.errors.full_messages }, status: 422
44     end
45   end
46
47   def destroy
48     @object.destroy
49     show
50   end
51
52   def catch_redirect_hint
53     if !current_user
54       if params.has_key?('redirect_to') then
55         session[:redirect_to] = params[:redirect_to]
56       end
57     end
58   end
59
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
71   end
72
73   def render_error(e)
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
78     else
79       errors = [e.inspect]
80     end
81     render json: { errors: errors }, status: 422
82   end
83
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
87   end
88
89   protected
90
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,
99             uuid_list,
100             current_user.uuid)
101     @where = params[:where] || {}
102     @where = Oj.load(@where) if @where.is_a?(String)
103     if params[:where]
104       conditions = ['1=1']
105       @where.each do |attr,value|
106         if (!value.nil? and
107             attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
108             model_class.columns.collect(&:name).index(attr))
109           if value.is_a? Array
110             conditions[0] << " and #{table_name}.#{attr} in (?)"
111             conditions << value
112           elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
113             conditions[0] << " and #{table_name}.#{attr}=?"
114             conditions << value
115           elsif value.is_a? Hash
116             # Not quite the same thing as "equal?" but better than nothing?
117             value.each do |k,v|
118               if v.is_a? String
119                 conditions[0] << " and #{table_name}.#{attr} ilike ?"
120                 conditions << "%#{k}%#{v}%"
121               end
122             end
123           end
124         elsif (!value.nil? and attr == 'any' and
125           value.is_a?(Array) and value[0] == 'contains' and
126           model_class.columns.collect(&:name).index('name')) then
127             conditions[0] << " and #{table_name}.name ilike ?"
128             conditions << "%#{value[1]}%"
129         end
130       end
131       if conditions.length > 1
132         conditions[0].sub!(/^1=1 and /, '')
133         @objects = @objects.
134           where(*conditions)
135       end
136     end
137     if params[:limit]
138       begin
139         @objects = @objects.limit(params[:limit].to_i)
140       rescue
141         raise "invalid argument (limit)"
142       end
143     else
144       @objects = @objects.limit(100)
145     end
146     @objects = @objects.order("#{table_name}.modified_at desc")
147   end
148
149   def resource_attrs
150     return @attrs if @attrs
151     @attrs = params[resource_name]
152     if @attrs.is_a? String
153       @attrs = uncamelcase_hash_keys(Oj.load @attrs)
154     end
155     unless @attrs.is_a? Hash
156       raise "no #{resource_name} (or #{resource_name.camelcase(:lower)}) hash provided with request #{params.inspect}"
157     end
158     %w(created_at modified_by_client modified_by_user modified_at).each do |x|
159       @attrs.delete x
160     end
161     @attrs
162   end
163
164   # Authentication
165   def login_required
166     if !current_user
167       respond_to do |format|
168         format.html  {
169           redirect_to '/auth/joshid'
170         }
171         format.json {
172           render :json => { errors: ['Not logged in'] }.to_json
173         }
174       end
175     end
176   end
177
178   def thread_with_auth_info
179     begin
180       user = nil
181       api_client = nil
182       api_client_auth = nil
183       supplied_token =
184         params[:api_token] ||
185         params[:oauth_token] ||
186         request.headers["Authorization"].andand.match(/OAuth2 ([a-z0-9]+)/).andand[1]
187       if supplied_token
188         api_client_auth = ApiClientAuthorization.
189           includes(:api_client, :user).
190           where('api_token=?', supplied_token).
191           first
192         if api_client_auth
193           session[:user_id] = api_client_auth.user.id
194           session[:api_client_uuid] = api_client_auth.api_client.uuid
195           session[:api_client_authorization_id] = api_client_auth.id
196           user = api_client_auth.user
197           api_client = api_client_auth.api_client
198         end
199       elsif session[:user_id]
200         user = User.find(session[:user_id]) rescue nil
201         api_client = ApiClient.
202           where('uuid=?',session[:api_client_uuid]).
203           first rescue nil
204         if session[:api_client_authorization_id] then
205           api_client_auth = ApiClientAuthorization.
206             find session[:api_client_authorization_id]
207         end
208       end
209       Thread.current[:api_client_trusted] = session[:api_client_trusted]
210       Thread.current[:api_client_ip_address] = remote_ip
211       Thread.current[:api_client_authorization] = api_client_auth
212       Thread.current[:api_client_uuid] = api_client && api_client.uuid
213       Thread.current[:api_client] = api_client
214       Thread.current[:user] = user
215       yield
216     ensure
217       Thread.current[:api_client_trusted] = nil
218       Thread.current[:api_client_ip_address] = nil
219       Thread.current[:api_client_authorization] = nil
220       Thread.current[:api_client_uuid] = nil
221       Thread.current[:api_client] = nil
222       Thread.current[:user] = nil
223     end
224   end
225   # /Authentication
226
227   def model_class
228     controller_name.classify.constantize
229   end
230
231   def resource_name             # params[] key used by client
232     controller_name.singularize
233   end
234
235   def table_name
236     controller_name
237   end
238
239   def find_object_by_uuid
240     if params[:id] and params[:id].match /\D/
241       params[:uuid] = params.delete :id
242     end
243     @object = model_class.where('uuid=?', params[:uuid]).first
244   end
245
246   def self.accept_attribute_as_json(attr, force_class=nil)
247     before_filter lambda { accept_attribute_as_json attr, force_class }
248   end
249   def accept_attribute_as_json(attr, force_class)
250     if params[resource_name].is_a? Hash
251       if params[resource_name][attr].is_a? String
252         params[resource_name][attr] = Oj.load params[resource_name][attr]
253         if force_class and !params[resource_name][attr].is_a? force_class
254           raise TypeError.new("#{resource_name}[#{attr.to_s}] must be a #{force_class.to_s}")
255         end
256       end
257     end
258   end
259
260   def uncamelcase_params_hash_keys
261     self.params = uncamelcase_hash_keys(params)
262   end
263   def uncamelcase_hash_keys(h, max_depth=-1)
264     if h.is_a? Hash and max_depth != 0
265       nh = Hash.new
266       h.each do |k,v|
267         if k.class == String
268           nk = k.underscore
269         elsif k.class == Symbol
270           nk = k.to_s.underscore.to_sym
271         else
272           nk = k
273         end
274         nh[nk] = uncamelcase_hash_keys(v, max_depth-1)
275       end
276       h.replace(nh)
277     end
278     h
279   end
280
281   def render_list
282     @object_list = {
283       :kind  => "arvados##{resource_name}List",
284       :etag => "",
285       :self_link => "",
286       :next_page_token => "",
287       :next_link => "",
288       :items => @objects.as_api_response(:superuser)
289     }
290     render json: @object_list
291   end
292
293   def remote_ip
294     # Caveat: this is highly dependent on the proxy setup. YMMV.
295     if request.headers.has_key?('HTTP_X_REAL_IP') then
296       # We're behind a reverse proxy
297       @remote_ip = request.headers['HTTP_X_REAL_IP']
298     else
299       # Hopefully, we are not!
300       @remote_ip = request.env['REMOTE_ADDR']
301     end
302   end
303 end