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