Merge branch 'master' into 2640-folder-api
[arvados.git] / services / api / app / controllers / application_controller.rb
1 module ApiTemplateOverride
2   def allowed_to_render?(fieldset, field, model, options)
3     if options[:select]
4       return options[:select].include? field.to_s
5     end
6     super
7   end
8 end
9
10 class ActsAsApi::ApiTemplate
11   prepend ApiTemplateOverride
12 end
13
14 require 'load_param'
15 require 'record_filters'
16
17 class ApplicationController < ActionController::Base
18   include CurrentApiClient
19   include ThemesForRails::ActionController
20   include LoadParam
21   include RecordFilters
22
23   ERROR_ACTIONS = [:render_error, :render_not_found]
24
25
26   respond_to :json
27   protect_from_forgery
28
29   before_filter :respond_with_json_by_default
30   before_filter :remote_ip
31   before_filter :load_read_auths
32   before_filter :require_auth_scope, except: ERROR_ACTIONS
33
34   before_filter :catch_redirect_hint
35   before_filter(:find_object_by_uuid,
36                 except: [:index, :create] + ERROR_ACTIONS)
37   before_filter :load_limit_offset_order_params, only: [:index, :contents]
38   before_filter :load_where_param, only: [:index, :contents]
39   before_filter :load_filters_param, only: [:index, :contents]
40   before_filter :find_objects_for_index, :only => :index
41   before_filter :reload_object_before_update, :only => :update
42   before_filter(:render_404_if_no_object,
43                 except: [:index, :create] + ERROR_ACTIONS)
44
45   theme :select_theme
46
47   attr_accessor :resource_attrs
48
49   def index
50     @objects.uniq!(&:id) if @select.nil? or @select.include? "id"
51     if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
52       @objects.each(&:eager_load_associations)
53     end
54     render_list
55   end
56
57   def show
58     render json: @object.as_api_response
59   end
60
61   def create
62     @object = model_class.new resource_attrs
63     @object.save!
64     show
65   end
66
67   def update
68     attrs_to_update = resource_attrs.reject { |k,v|
69       [:kind, :etag, :href].index k
70     }
71     @object.update_attributes! attrs_to_update
72     show
73   end
74
75   def destroy
76     @object.destroy
77     show
78   end
79
80   def self._contents_requires_parameters
81     _index_requires_parameters.
82       merge({
83               include_linked: {
84                 type: 'boolean', required: false, default: false
85               },
86             })
87   end
88
89   def contents
90     all_objects = []
91     all_available = 0
92
93     # Trick apply_where_limit_order_params into applying suitable
94     # per-table values. *_all are the real ones we'll apply to the
95     # aggregate set.
96     limit_all = @limit
97     offset_all = @offset
98     @orders = []
99
100     ArvadosModel.descendants.reject(&:abstract_class?).sort_by(&:to_s).
101       each do |klass|
102       case klass.to_s
103         # We might expect klass==Link etc. here, but we would be
104         # disappointed: when Rails reloads model classes, we get two
105         # distinct classes called Link which do not equal each
106         # other. But we can still rely on klass.to_s to be "Link".
107       when 'ApiClientAuthorization', 'UserAgreement'
108         # Do not want.
109       else
110         @objects = klass.readable_by(*@read_users)
111         cond_sql = "#{klass.table_name}.owner_uuid = ?"
112         cond_params = [@object.uuid]
113         if params[:include_linked]
114           cond_sql += " OR #{klass.table_name}.uuid IN (SELECT head_uuid FROM links WHERE link_class=#{klass.sanitize 'name'} AND links.tail_uuid=#{klass.sanitize @object.uuid})"
115         end
116         @objects = @objects.where(cond_sql, *cond_params).order("#{klass.table_name}.uuid")
117         @limit = limit_all - all_objects.count
118         apply_where_limit_order_params
119         items_available = @objects.
120           except(:limit).except(:offset).
121           count(:id, distinct: true)
122         all_available += items_available
123         @offset = [@offset - items_available, 0].max
124
125         all_objects += @objects.to_a
126       end
127     end
128     @objects = all_objects || []
129     @links = Link.where('link_class=? and tail_uuid=?'\
130                         ' and head_uuid in (?)',
131                         'name',
132                         @object.uuid,
133                         @objects.collect(&:uuid))
134     @object_list = {
135       :kind  => "arvados#objectList",
136       :etag => "",
137       :self_link => "",
138       :links => @links.as_api_response(nil),
139       :offset => offset_all,
140       :limit => limit_all,
141       :items_available => all_available,
142       :items => @objects.as_api_response(nil)
143     }
144     render json: @object_list
145   end
146
147   def catch_redirect_hint
148     if !current_user
149       if params.has_key?('redirect_to') then
150         session[:redirect_to] = params[:redirect_to]
151       end
152     end
153   end
154
155   begin
156     rescue_from Exception,
157     :with => :render_error
158     rescue_from ActiveRecord::RecordNotFound,
159     :with => :render_not_found
160     rescue_from ActionController::RoutingError,
161     :with => :render_not_found
162     rescue_from ActionController::UnknownController,
163     :with => :render_not_found
164     rescue_from AbstractController::ActionNotFound,
165     :with => :render_not_found
166     rescue_from ArvadosModel::PermissionDeniedError,
167     :with => :render_error
168   end
169
170   def render_404_if_no_object
171     render_not_found "Object not found" if !@object
172   end
173
174   def render_error(e)
175     logger.error e.inspect
176     if e.respond_to? :backtrace and e.backtrace
177       logger.error e.backtrace.collect { |x| x + "\n" }.join('')
178     end
179     if @object and @object.errors and @object.errors.full_messages and not @object.errors.full_messages.empty?
180       errors = @object.errors.full_messages
181     else
182       errors = [e.inspect]
183     end
184     status = e.respond_to?(:http_status) ? e.http_status : 422
185     render json: { errors: errors }, status: status
186   end
187
188   def render_not_found(e=ActionController::RoutingError.new("Path not found"))
189     logger.error e.inspect
190     render json: { errors: ["Path not found"] }, status: 404
191   end
192
193   protected
194
195   def find_objects_for_index
196     @objects ||= model_class.readable_by(*@read_users)
197     apply_where_limit_order_params
198   end
199
200   def apply_where_limit_order_params
201     ar_table_name = @objects.table_name
202
203     ft = record_filters @filters, ar_table_name
204     if ft[:cond_out].any?
205       @objects = @objects.where(ft[:cond_out].join(' AND '), *ft[:param_out])
206     end
207
208     if @where.is_a? Hash and @where.any?
209       conditions = ['1=1']
210       @where.each do |attr,value|
211         if attr.to_s == 'any'
212           if value.is_a?(Array) and
213               value.length == 2 and
214               value[0] == 'contains' then
215             ilikes = []
216             model_class.searchable_columns('ilike').each do |column|
217               # Including owner_uuid in an "any column" search will
218               # probably just return a lot of false positives.
219               next if column == 'owner_uuid'
220               ilikes << "#{ar_table_name}.#{column} ilike ?"
221               conditions << "%#{value[1]}%"
222             end
223             if ilikes.any?
224               conditions[0] << ' and (' + ilikes.join(' or ') + ')'
225             end
226           end
227         elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
228             model_class.columns.collect(&:name).index(attr.to_s)
229           if value.nil?
230             conditions[0] << " and #{ar_table_name}.#{attr} is ?"
231             conditions << nil
232           elsif value.is_a? Array
233             if value[0] == 'contains' and value.length == 2
234               conditions[0] << " and #{ar_table_name}.#{attr} like ?"
235               conditions << "%#{value[1]}%"
236             else
237               conditions[0] << " and #{ar_table_name}.#{attr} in (?)"
238               conditions << value
239             end
240           elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
241             conditions[0] << " and #{ar_table_name}.#{attr}=?"
242             conditions << value
243           elsif value.is_a? Hash
244             # Not quite the same thing as "equal?" but better than nothing?
245             value.each do |k,v|
246               if v.is_a? String
247                 conditions[0] << " and #{ar_table_name}.#{attr} ilike ?"
248                 conditions << "%#{k}%#{v}%"
249               end
250             end
251           end
252         end
253       end
254       if conditions.length > 1
255         conditions[0].sub!(/^1=1 and /, '')
256         @objects = @objects.
257           where(*conditions)
258       end
259     end
260
261     @objects = @objects.select(@select.map { |s| "#{table_name}.#{ActiveRecord::Base.connection.quote_column_name s.to_s}" }.join ", ") if @select
262     @objects = @objects.order(@orders.join ", ") if @orders.any?
263     @objects = @objects.limit(@limit)
264     @objects = @objects.offset(@offset)
265     @objects = @objects.uniq(@distinct) if not @distinct.nil?
266   end
267
268   def resource_attrs
269     return @attrs if @attrs
270     @attrs = params[resource_name]
271     if @attrs.is_a? String
272       @attrs = Oj.load @attrs, symbol_keys: true
273     end
274     unless @attrs.is_a? Hash
275       message = "No #{resource_name}"
276       if resource_name.index('_')
277         message << " (or #{resource_name.camelcase(:lower)})"
278       end
279       message << " hash provided with request"
280       raise ArgumentError.new(message)
281     end
282     %w(created_at modified_by_client_uuid modified_by_user_uuid modified_at).each do |x|
283       @attrs.delete x.to_sym
284     end
285     @attrs = @attrs.symbolize_keys if @attrs.is_a? HashWithIndifferentAccess
286     @attrs
287   end
288
289   # Authentication
290   def load_read_auths
291     @read_auths = []
292     if current_api_client_authorization
293       @read_auths << current_api_client_authorization
294     end
295     # Load reader tokens if this is a read request.
296     # If there are too many reader tokens, assume the request is malicious
297     # and ignore it.
298     if request.get? and params[:reader_tokens] and
299         params[:reader_tokens].size < 100
300       @read_auths += ApiClientAuthorization
301         .includes(:user)
302         .where('api_token IN (?) AND
303                 (expires_at IS NULL OR expires_at > CURRENT_TIMESTAMP)',
304                params[:reader_tokens])
305         .all
306     end
307     @read_auths.select! { |auth| auth.scopes_allow_request? request }
308     @read_users = @read_auths.map { |auth| auth.user }.uniq
309   end
310
311   def require_login
312     if not current_user
313       respond_to do |format|
314         format.json {
315           render :json => { errors: ['Not logged in'] }.to_json, status: 401
316         }
317         format.html {
318           redirect_to '/auth/joshid'
319         }
320       end
321       false
322     end
323   end
324
325   def admin_required
326     unless current_user and current_user.is_admin
327       render :json => { errors: ['Forbidden'] }.to_json, status: 403
328     end
329   end
330
331   def require_auth_scope
332     if @read_auths.empty?
333       if require_login != false
334         render :json => { errors: ['Forbidden'] }.to_json, status: 403
335       end
336       false
337     end
338   end
339
340   def respond_with_json_by_default
341     html_index = request.accepts.index(Mime::HTML)
342     if html_index.nil? or request.accepts[0...html_index].include?(Mime::JSON)
343       request.format = :json
344     end
345   end
346
347   def model_class
348     controller_name.classify.constantize
349   end
350
351   def resource_name             # params[] key used by client
352     controller_name.singularize
353   end
354
355   def table_name
356     controller_name
357   end
358
359   def find_object_by_uuid
360     if params[:id] and params[:id].match /\D/
361       params[:uuid] = params.delete :id
362     end
363     @where = { uuid: params[:uuid] }
364     @offset = 0
365     @limit = 1
366     @orders = []
367     @filters = []
368     @objects = nil
369     find_objects_for_index
370     @object = @objects.first
371   end
372
373   def reload_object_before_update
374     # This is necessary to prevent an ActiveRecord::ReadOnlyRecord
375     # error when updating an object which was retrieved using a join.
376     if @object.andand.readonly?
377       @object = model_class.find_by_uuid(@objects.first.uuid)
378     end
379   end
380
381   def load_json_value(hash, key, must_be_class=nil)
382     if hash[key].is_a? String
383       hash[key] = Oj.load(hash[key], symbol_keys: false)
384       if must_be_class and !hash[key].is_a? must_be_class
385         raise TypeError.new("parameter #{key.to_s} must be a #{must_be_class.to_s}")
386       end
387     end
388   end
389
390   def self.accept_attribute_as_json(attr, must_be_class=nil)
391     before_filter lambda { accept_attribute_as_json attr, must_be_class }
392   end
393   accept_attribute_as_json :properties, Hash
394   accept_attribute_as_json :info, Hash
395   def accept_attribute_as_json(attr, must_be_class)
396     if params[resource_name] and resource_attrs.is_a? Hash
397       if resource_attrs[attr].is_a? Hash
398         # Convert symbol keys to strings (in hashes provided by
399         # resource_attrs)
400         resource_attrs[attr] = resource_attrs[attr].
401           with_indifferent_access.to_hash
402       else
403         load_json_value(resource_attrs, attr, must_be_class)
404       end
405     end
406   end
407
408   def self.accept_param_as_json(key, must_be_class=nil)
409     prepend_before_filter lambda { load_json_value(params, key, must_be_class) }
410   end
411   accept_param_as_json :reader_tokens, Array
412
413   def render_list
414     @object_list = {
415       :kind  => "arvados##{(@response_resource_name || resource_name).camelize(:lower)}List",
416       :etag => "",
417       :self_link => "",
418       :offset => @offset,
419       :limit => @limit,
420       :items => @objects.as_api_response(nil, {select: @select})
421     }
422     if @objects.respond_to? :except
423       @object_list[:items_available] = @objects.
424         except(:limit).except(:offset).
425         count(:id, distinct: true)
426     end
427     render json: @object_list
428   end
429
430   def remote_ip
431     # Caveat: this is highly dependent on the proxy setup. YMMV.
432     if request.headers.has_key?('HTTP_X_REAL_IP') then
433       # We're behind a reverse proxy
434       @remote_ip = request.headers['HTTP_X_REAL_IP']
435     else
436       # Hopefully, we are not!
437       @remote_ip = request.env['REMOTE_ADDR']
438     end
439   end
440
441   def self._index_requires_parameters
442     {
443       filters: { type: 'array', required: false },
444       where: { type: 'object', required: false },
445       order: { type: 'array', required: false },
446       select: { type: 'array', required: false },
447       distinct: { type: 'boolean', required: false },
448       limit: { type: 'integer', required: false, default: DEFAULT_LIMIT },
449       offset: { type: 'integer', required: false, default: 0 },
450     }
451   end
452
453   def client_accepts_plain_text_stream
454     (request.headers['Accept'].split(' ') &
455      ['text/plain', '*/*']).count > 0
456   end
457
458   def render *opts
459     if opts.first
460       response = opts.first[:json]
461       if response.is_a?(Hash) &&
462           params[:_profile] &&
463           Thread.current[:request_starttime]
464         response[:_profile] = {
465           request_time: Time.now - Thread.current[:request_starttime]
466         }
467       end
468     end
469     super *opts
470   end
471
472   def select_theme
473     return Rails.configuration.arvados_theme
474   end
475 end