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