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