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