Merge branch '1968-monitor-disk-usage'
[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 catch_redirect_hint
81     if !current_user
82       if params.has_key?('redirect_to') then
83         session[:redirect_to] = params[:redirect_to]
84       end
85     end
86   end
87
88   begin
89     rescue_from Exception,
90     :with => :render_error
91     rescue_from ActiveRecord::RecordNotFound,
92     :with => :render_not_found
93     rescue_from ActionController::RoutingError,
94     :with => :render_not_found
95     rescue_from ActionController::UnknownController,
96     :with => :render_not_found
97     rescue_from AbstractController::ActionNotFound,
98     :with => :render_not_found
99     rescue_from ArvadosModel::PermissionDeniedError,
100     :with => :render_error
101   end
102
103   def render_404_if_no_object
104     render_not_found "Object not found" if !@object
105   end
106
107   def render_error(e)
108     logger.error e.inspect
109     if e.respond_to? :backtrace and e.backtrace
110       logger.error e.backtrace.collect { |x| x + "\n" }.join('')
111     end
112     if @object and @object.errors and @object.errors.full_messages and not @object.errors.full_messages.empty?
113       errors = @object.errors.full_messages
114     else
115       errors = [e.inspect]
116     end
117     status = e.respond_to?(:http_status) ? e.http_status : 422
118     render json: { errors: errors }, status: status
119   end
120
121   def render_not_found(e=ActionController::RoutingError.new("Path not found"))
122     logger.error e.inspect
123     render json: { errors: ["Path not found"] }, status: 404
124   end
125
126   protected
127
128   def find_objects_for_index
129     @objects ||= model_class.readable_by(*@read_users)
130     apply_where_limit_order_params
131   end
132
133   def apply_where_limit_order_params
134     ar_table_name = @objects.table_name
135
136     ft = record_filters @filters, ar_table_name
137     if ft[:cond_out].any?
138       @objects = @objects.where(ft[:cond_out].join(' AND '), *ft[:param_out])
139     end
140
141     if @where.is_a? Hash and @where.any?
142       conditions = ['1=1']
143       @where.each do |attr,value|
144         if attr.to_s == 'any'
145           if value.is_a?(Array) and
146               value.length == 2 and
147               value[0] == 'contains' then
148             ilikes = []
149             model_class.searchable_columns('ilike').each do |column|
150               # Including owner_uuid in an "any column" search will
151               # probably just return a lot of false positives.
152               next if column == 'owner_uuid'
153               ilikes << "#{ar_table_name}.#{column} ilike ?"
154               conditions << "%#{value[1]}%"
155             end
156             if ilikes.any?
157               conditions[0] << ' and (' + ilikes.join(' or ') + ')'
158             end
159           end
160         elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
161             model_class.columns.collect(&:name).index(attr.to_s)
162           if value.nil?
163             conditions[0] << " and #{ar_table_name}.#{attr} is ?"
164             conditions << nil
165           elsif value.is_a? Array
166             if value[0] == 'contains' and value.length == 2
167               conditions[0] << " and #{ar_table_name}.#{attr} like ?"
168               conditions << "%#{value[1]}%"
169             else
170               conditions[0] << " and #{ar_table_name}.#{attr} in (?)"
171               conditions << value
172             end
173           elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
174             conditions[0] << " and #{ar_table_name}.#{attr}=?"
175             conditions << value
176           elsif value.is_a? Hash
177             # Not quite the same thing as "equal?" but better than nothing?
178             value.each do |k,v|
179               if v.is_a? String
180                 conditions[0] << " and #{ar_table_name}.#{attr} ilike ?"
181                 conditions << "%#{k}%#{v}%"
182               end
183             end
184           end
185         end
186       end
187       if conditions.length > 1
188         conditions[0].sub!(/^1=1 and /, '')
189         @objects = @objects.
190           where(*conditions)
191       end
192     end
193
194     @objects = @objects.select(@select.map { |s| "#{table_name}.#{ActiveRecord::Base.connection.quote_column_name s.to_s}" }.join ", ") if @select
195     @objects = @objects.order(@orders.join ", ") if @orders.any?
196     @objects = @objects.limit(@limit)
197     @objects = @objects.offset(@offset)
198     @objects = @objects.uniq(@distinct) if not @distinct.nil?
199   end
200
201   def resource_attrs
202     return @attrs if @attrs
203     @attrs = params[resource_name]
204     if @attrs.is_a? String
205       @attrs = Oj.load @attrs, symbol_keys: true
206     end
207     unless @attrs.is_a? Hash
208       message = "No #{resource_name}"
209       if resource_name.index('_')
210         message << " (or #{resource_name.camelcase(:lower)})"
211       end
212       message << " hash provided with request"
213       raise ArgumentError.new(message)
214     end
215     %w(created_at modified_by_client_uuid modified_by_user_uuid modified_at).each do |x|
216       @attrs.delete x.to_sym
217     end
218     @attrs = @attrs.symbolize_keys if @attrs.is_a? HashWithIndifferentAccess
219     @attrs
220   end
221
222   # Authentication
223   def load_read_auths
224     @read_auths = []
225     if current_api_client_authorization
226       @read_auths << current_api_client_authorization
227     end
228     # Load reader tokens if this is a read request.
229     # If there are too many reader tokens, assume the request is malicious
230     # and ignore it.
231     if request.get? and params[:reader_tokens] and
232         params[:reader_tokens].size < 100
233       @read_auths += ApiClientAuthorization
234         .includes(:user)
235         .where('api_token IN (?) AND
236                 (expires_at IS NULL OR expires_at > CURRENT_TIMESTAMP)',
237                params[:reader_tokens])
238         .all
239     end
240     @read_auths.select! { |auth| auth.scopes_allow_request? request }
241     @read_users = @read_auths.map { |auth| auth.user }.uniq
242   end
243
244   def require_login
245     if not current_user
246       respond_to do |format|
247         format.json {
248           render :json => { errors: ['Not logged in'] }.to_json, status: 401
249         }
250         format.html {
251           redirect_to '/auth/joshid'
252         }
253       end
254       false
255     end
256   end
257
258   def admin_required
259     unless current_user and current_user.is_admin
260       render :json => { errors: ['Forbidden'] }.to_json, status: 403
261     end
262   end
263
264   def require_auth_scope
265     if @read_auths.empty?
266       if require_login != false
267         render :json => { errors: ['Forbidden'] }.to_json, status: 403
268       end
269       false
270     end
271   end
272
273   def respond_with_json_by_default
274     html_index = request.accepts.index(Mime::HTML)
275     if html_index.nil? or request.accepts[0...html_index].include?(Mime::JSON)
276       request.format = :json
277     end
278   end
279
280   def model_class
281     controller_name.classify.constantize
282   end
283
284   def resource_name             # params[] key used by client
285     controller_name.singularize
286   end
287
288   def table_name
289     controller_name
290   end
291
292   def find_object_by_uuid
293     if params[:id] and params[:id].match /\D/
294       params[:uuid] = params.delete :id
295     end
296     @where = { uuid: params[:uuid] }
297     @offset = 0
298     @limit = 1
299     @orders = []
300     @filters = []
301     @objects = nil
302     find_objects_for_index
303     @object = @objects.first
304   end
305
306   def reload_object_before_update
307     # This is necessary to prevent an ActiveRecord::ReadOnlyRecord
308     # error when updating an object which was retrieved using a join.
309     if @object.andand.readonly?
310       @object = model_class.find_by_uuid(@objects.first.uuid)
311     end
312   end
313
314   def load_json_value(hash, key, must_be_class=nil)
315     if hash[key].is_a? String
316       hash[key] = Oj.load(hash[key], symbol_keys: false)
317       if must_be_class and !hash[key].is_a? must_be_class
318         raise TypeError.new("parameter #{key.to_s} must be a #{must_be_class.to_s}")
319       end
320     end
321   end
322
323   def self.accept_attribute_as_json(attr, must_be_class=nil)
324     before_filter lambda { accept_attribute_as_json attr, must_be_class }
325   end
326   accept_attribute_as_json :properties, Hash
327   accept_attribute_as_json :info, Hash
328   def accept_attribute_as_json(attr, must_be_class)
329     if params[resource_name] and resource_attrs.is_a? Hash
330       if resource_attrs[attr].is_a? Hash
331         # Convert symbol keys to strings (in hashes provided by
332         # resource_attrs)
333         resource_attrs[attr] = resource_attrs[attr].
334           with_indifferent_access.to_hash
335       else
336         load_json_value(resource_attrs, attr, must_be_class)
337       end
338     end
339   end
340
341   def self.accept_param_as_json(key, must_be_class=nil)
342     prepend_before_filter lambda { load_json_value(params, key, must_be_class) }
343   end
344   accept_param_as_json :reader_tokens, Array
345
346   def render_list
347     @object_list = {
348       :kind  => "arvados##{(@response_resource_name || resource_name).camelize(:lower)}List",
349       :etag => "",
350       :self_link => "",
351       :offset => @offset,
352       :limit => @limit,
353       :items => @objects.as_api_response(nil, {select: @select})
354     }
355     if @objects.respond_to? :except
356       @object_list[:items_available] = @objects.
357         except(:limit).except(:offset).
358         count(:id, distinct: true)
359     end
360     render json: @object_list
361   end
362
363   def remote_ip
364     # Caveat: this is highly dependent on the proxy setup. YMMV.
365     if request.headers.has_key?('HTTP_X_REAL_IP') then
366       # We're behind a reverse proxy
367       @remote_ip = request.headers['HTTP_X_REAL_IP']
368     else
369       # Hopefully, we are not!
370       @remote_ip = request.env['REMOTE_ADDR']
371     end
372   end
373
374   def self._index_requires_parameters
375     {
376       filters: { type: 'array', required: false },
377       where: { type: 'object', required: false },
378       order: { type: 'array', required: false },
379       select: { type: 'array', required: false },
380       distinct: { type: 'boolean', required: false },
381       limit: { type: 'integer', required: false, default: DEFAULT_LIMIT },
382       offset: { type: 'integer', required: false, default: 0 },
383     }
384   end
385
386   def client_accepts_plain_text_stream
387     (request.headers['Accept'].split(' ') &
388      ['text/plain', '*/*']).count > 0
389   end
390
391   def render *opts
392     if opts.first
393       response = opts.first[:json]
394       if response.is_a?(Hash) &&
395           params[:_profile] &&
396           Thread.current[:request_starttime]
397         response[:_profile] = {
398           request_time: Time.now - Thread.current[:request_starttime]
399         }
400       end
401     end
402     super *opts
403   end
404
405   def select_theme
406     return Rails.configuration.arvados_theme
407   end
408 end