Fix crash on error pages by removing before_filters that assume there
[arvados.git] / services / api / app / controllers / application_controller.rb
1 class ApplicationController < ActionController::Base
2   include CurrentApiClient
3
4   protect_from_forgery
5   around_filter :thread_with_auth_info, :except => [:render_error, :render_not_found]
6
7   before_filter :remote_ip
8   before_filter :require_auth_scope_all, :except => :render_not_found
9   before_filter :catch_redirect_hint
10
11   before_filter :load_where_param, :only => :index
12   before_filter :find_objects_for_index, :only => :index
13   before_filter :find_object_by_uuid, :except => [:index, :create,
14                                                   :render_error,
15                                                   :render_not_found]
16   before_filter :reload_object_before_update, :only => :update
17
18   attr_accessor :resource_attrs
19
20   def index
21     @objects.uniq!(&:id)
22     if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
23       @objects.each(&:eager_load_associations)
24     end
25     render_list
26   end
27
28   def show
29     if @object
30       render json: @object.as_api_response
31     else
32       render_not_found("object not found")
33     end
34   end
35
36   def create
37     @object = model_class.new resource_attrs
38     if @object.save
39       show
40     else
41       render_error "Save failed"
42     end
43   end
44
45   def update
46     if !@object
47       return render_not_found("object not found")
48     end
49     attrs_to_update = resource_attrs.reject { |k,v|
50       [:kind, :etag, :href].index k
51     }
52     if @object.update_attributes attrs_to_update
53       show
54     else
55       render_error "Update failed"
56     end
57   end
58
59   def destroy
60     @object.destroy
61     show
62   end
63
64   def catch_redirect_hint
65     if !current_user
66       if params.has_key?('redirect_to') then
67         session[:redirect_to] = params[:redirect_to]
68       end
69     end
70   end
71
72   begin
73     rescue_from Exception,
74     :with => :render_error
75     rescue_from ActiveRecord::RecordNotFound,
76     :with => :render_not_found
77     rescue_from ActionController::RoutingError,
78     :with => :render_not_found
79     rescue_from ActionController::UnknownController,
80     :with => :render_not_found
81     rescue_from AbstractController::ActionNotFound,
82     :with => :render_not_found
83     rescue_from ArvadosModel::PermissionDeniedError,
84     :with => :render_error
85   end
86
87   def render_error(e)
88     logger.error e.inspect
89     logger.error e.backtrace.collect { |x| x + "\n" }.join('') if e.backtrace
90     if @object and @object.errors and @object.errors.full_messages and not @object.errors.full_messages.empty?
91       errors = @object.errors.full_messages
92     else
93       errors = [e.inspect]
94     end
95     status = e.respond_to?(:http_status) ? e.http_status : 422
96     render json: { errors: errors }, status: status
97   end
98
99   def render_not_found(e=ActionController::RoutingError.new("Path not found"))
100     logger.error e.inspect
101     render json: { errors: ["Path not found"] }, status: 404
102   end
103
104   protected
105
106   def load_where_param
107     if params[:where].nil? or params[:where] == ""
108       @where = {}
109     elsif params[:where].is_a? Hash
110       @where = params[:where]
111     elsif params[:where].is_a? String
112       begin
113         @where = Oj.load(params[:where], symbol_keys: true)
114       rescue
115         raise ArgumentError.new("Could not parse \"where\" param as an object")
116       end
117     end
118   end
119
120   def find_objects_for_index
121     uuid_list = [current_user.uuid, *current_user.groups_i_can(:read)]
122     sanitized_uuid_list = uuid_list.
123       collect { |uuid| model_class.sanitize(uuid) }.join(', ')
124     or_references_me = ''
125     if model_class == Link and current_user
126       or_references_me = "OR (#{table_name}.link_class in (#{model_class.sanitize 'permission'}, #{model_class.sanitize 'resources'}) AND #{model_class.sanitize current_user.uuid} IN (#{table_name}.head_uuid, #{table_name}.tail_uuid))"
127     end
128     @objects ||= model_class.
129       joins("LEFT JOIN links permissions ON permissions.head_uuid in (#{table_name}.owner_uuid, #{table_name}.uuid) AND permissions.tail_uuid in (#{sanitized_uuid_list}) AND permissions.link_class='permission'").
130       where("?=? OR #{table_name}.owner_uuid in (?) OR #{table_name}.uuid=? OR permissions.head_uuid IS NOT NULL #{or_references_me}",
131             true, current_user.is_admin,
132             uuid_list,
133             current_user.uuid)
134     if !@where.empty?
135       conditions = ['1=1']
136       @where.each do |attr,value|
137         if attr == :any
138           if value.is_a?(Array) and
139               value[0] == 'contains' and
140               model_class.columns.collect(&:name).index('name') then
141             ilikes = []
142             model_class.searchable_columns.each do |column|
143               ilikes << "#{table_name}.#{column} ilike ?"
144               conditions << "%#{value[1]}%"
145             end
146             if ilikes.any?
147               conditions[0] << ' and (' + ilikes.join(' or ') + ')'
148             end
149           end
150         elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
151             model_class.columns.collect(&:name).index(attr.to_s)
152           if value.nil?
153             conditions[0] << " and #{table_name}.#{attr} is ?"
154             conditions << nil
155           elsif value.is_a? Array
156             conditions[0] << " and #{table_name}.#{attr} in (?)"
157             conditions << value
158           elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
159             conditions[0] << " and #{table_name}.#{attr}=?"
160             conditions << value
161           elsif value.is_a? Hash
162             # Not quite the same thing as "equal?" but better than nothing?
163             value.each do |k,v|
164               if v.is_a? String
165                 conditions[0] << " and #{table_name}.#{attr} ilike ?"
166                 conditions << "%#{k}%#{v}%"
167               end
168             end
169           end
170         end
171       end
172       if conditions.length > 1
173         conditions[0].sub!(/^1=1 and /, '')
174         @objects = @objects.
175           where(*conditions)
176       end
177     end
178     if params[:limit]
179       begin
180         @objects = @objects.limit(params[:limit].to_i)
181       rescue
182         raise ArgumentError.new("Invalid value for limit parameter")
183       end
184     else
185       @objects = @objects.limit(100)
186     end
187     orders = []
188     if params[:order]
189       params[:order].split(',').each do |order|
190         attr, direction = order.strip.split " "
191         direction ||= 'asc'
192         if attr.match /^[a-z][_a-z0-9]+$/ and
193             model_class.columns.collect(&:name).index(attr) and
194             ['asc','desc'].index direction.downcase
195           orders << "#{table_name}.#{attr} #{direction.downcase}"
196         end
197       end
198     end
199     if orders.empty?
200       orders << "#{table_name}.modified_at desc"
201     end
202     @objects = @objects.order(orders.join ", ")
203   end
204
205   def resource_attrs
206     return @attrs if @attrs
207     @attrs = params[resource_name]
208     if @attrs.is_a? String
209       @attrs = Oj.load @attrs, symbol_keys: true
210     end
211     unless @attrs.is_a? Hash
212       message = "No #{resource_name}"
213       if resource_name.index('_')
214         message << " (or #{resource_name.camelcase(:lower)})"
215       end
216       message << " hash provided with request"
217       raise ArgumentError.new(message)
218     end
219     %w(created_at modified_by_client_uuid modified_by_user_uuid modified_at).each do |x|
220       @attrs.delete x.to_sym
221     end
222     @attrs
223   end
224
225   # Authentication
226   def require_login
227     if current_user
228       true
229     else
230       respond_to do |format|
231         format.json {
232           render :json => { errors: ['Not logged in'] }.to_json, status: 401
233         }
234         format.html  {
235           redirect_to '/auth/joshid'
236         }
237       end
238       false
239     end
240   end
241
242   def admin_required
243     unless current_user and current_user.is_admin
244       render :json => { errors: ['Forbidden'] }.to_json, status: 403
245     end
246   end
247
248   def require_auth_scope_all
249     require_login and require_auth_scope(['all'])
250   end
251
252   def require_auth_scope(ok_scopes)
253     unless current_api_client_auth_has_scope(ok_scopes)
254       render :json => { errors: ['Forbidden'] }.to_json, status: 403
255     end
256   end
257
258   def thread_with_auth_info
259     Thread.current[:request_starttime] = Time.now
260     Thread.current[:api_url_base] = root_url.sub(/\/$/,'') + '/arvados/v1'
261     begin
262       user = nil
263       api_client = nil
264       api_client_auth = nil
265       supplied_token =
266         params[:api_token] ||
267         params[:oauth_token] ||
268         request.headers["Authorization"].andand.match(/OAuth2 ([a-z0-9]+)/).andand[1]
269       if supplied_token
270         api_client_auth = ApiClientAuthorization.
271           includes(:api_client, :user).
272           where('api_token=? and (expires_at is null or expires_at > now())', supplied_token).
273           first
274         if api_client_auth.andand.user
275           session[:user_id] = api_client_auth.user.id
276           session[:api_client_uuid] = api_client_auth.api_client.andand.uuid
277           session[:api_client_authorization_id] = api_client_auth.id
278           user = api_client_auth.user
279           api_client = api_client_auth.api_client
280         end
281       elsif session[:user_id]
282         user = User.find(session[:user_id]) rescue nil
283         api_client = ApiClient.
284           where('uuid=?',session[:api_client_uuid]).
285           first rescue nil
286         if session[:api_client_authorization_id] then
287           api_client_auth = ApiClientAuthorization.
288             find session[:api_client_authorization_id]
289         end
290       end
291       Thread.current[:api_client_ip_address] = remote_ip
292       Thread.current[:api_client_authorization] = api_client_auth
293       Thread.current[:api_client_uuid] = api_client.andand.uuid
294       Thread.current[:api_client] = api_client
295       Thread.current[:user] = user
296       if api_client_auth
297         api_client_auth.last_used_at = Time.now
298         api_client_auth.last_used_by_ip_address = remote_ip
299         api_client_auth.save validate: false
300       end
301       yield
302     ensure
303       Thread.current[:api_client_ip_address] = nil
304       Thread.current[:api_client_authorization] = nil
305       Thread.current[:api_client_uuid] = nil
306       Thread.current[:api_client] = nil
307       Thread.current[:user] = nil
308     end
309   end
310   # /Authentication
311
312   def model_class
313     controller_name.classify.constantize
314   end
315
316   def resource_name             # params[] key used by client
317     controller_name.singularize
318   end
319
320   def table_name
321     controller_name
322   end
323
324   def find_object_by_uuid
325     if params[:id] and params[:id].match /\D/
326       params[:uuid] = params.delete :id
327     end
328     @where = { uuid: params[:uuid] }
329     find_objects_for_index
330     @object = @objects.first
331   end
332
333   def reload_object_before_update
334     # This is necessary to prevent an ActiveRecord::ReadOnlyRecord
335     # error when updating an object which was retrieved using a join.
336     if @object.andand.readonly?
337       @object = model_class.find_by_uuid(@objects.first.uuid)
338     end
339   end
340
341   def self.accept_attribute_as_json(attr, force_class=nil)
342     before_filter lambda { accept_attribute_as_json attr, force_class }
343   end
344   accept_attribute_as_json :properties, Hash
345   accept_attribute_as_json :info, Hash
346   def accept_attribute_as_json(attr, force_class)
347     if params[resource_name] and resource_attrs.is_a? Hash
348       if resource_attrs[attr].is_a? String
349         resource_attrs[attr] = Oj.load(resource_attrs[attr],
350                                        symbol_keys: false)
351         if force_class and !resource_attrs[attr].is_a? force_class
352           raise TypeError.new("#{resource_name}[#{attr.to_s}] must be a #{force_class.to_s}")
353         end
354       elsif resource_attrs[attr].is_a? Hash
355         # Convert symbol keys to strings (in hashes provided by
356         # resource_attrs)
357         resource_attrs[attr] = resource_attrs[attr].
358           with_indifferent_access.to_hash
359       end
360     end
361   end
362
363   def render_list
364     @object_list = {
365       :kind  => "arvados##{(@response_resource_name || resource_name).camelize(:lower)}List",
366       :etag => "",
367       :self_link => "",
368       :next_page_token => "",
369       :next_link => "",
370       :items => @objects.as_api_response(nil)
371     }
372     if @objects.respond_to? :except
373       @object_list[:items_available] = @objects.except(:limit).count
374     end
375     render json: @object_list
376   end
377
378   def remote_ip
379     # Caveat: this is highly dependent on the proxy setup. YMMV.
380     if request.headers.has_key?('HTTP_X_REAL_IP') then
381       # We're behind a reverse proxy
382       @remote_ip = request.headers['HTTP_X_REAL_IP']
383     else
384       # Hopefully, we are not!
385       @remote_ip = request.env['REMOTE_ADDR']
386     end
387   end
388
389   def self._index_requires_parameters
390     {
391       where: { type: 'object', required: false },
392       order: { type: 'string', required: false }
393     }
394   end
395   
396   def client_accepts_plain_text_stream
397     (request.headers['Accept'].split(' ') &
398      ['text/plain', '*/*']).count > 0
399   end
400
401   def render *opts
402     response = opts.first[:json]
403     if response.is_a?(Hash) &&
404         params[:_profile] &&
405         Thread.current[:request_starttime]
406       response[:_profile] = {
407          request_time: Time.now - Thread.current[:request_starttime]
408       }
409     end
410     super *opts
411   end
412 end