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