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