- Added object_owner_uuid to logs table, which records the owner of the object
[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 :remote_ip
14   before_filter :require_auth_scope_all, :except => :render_not_found
15   before_filter :catch_redirect_hint
16
17   before_filter :load_where_param, :only => :index
18   before_filter :load_filters_param, :only => :index
19   before_filter :find_objects_for_index, :only => :index
20   before_filter :find_object_by_uuid, :except => [:index, :create,
21                                                   :render_error,
22                                                   :render_not_found]
23   before_filter :reload_object_before_update, :only => :update
24   before_filter :render_404_if_no_object, except: [:index, :create,
25                                                    :render_error,
26                                                    :render_not_found]
27
28   theme :select_theme
29
30   attr_accessor :resource_attrs
31
32   def index
33     @objects.uniq!(&:id)
34     if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
35       @objects.each(&:eager_load_associations)
36     end
37     render_list
38   end
39
40   def show
41     render json: @object.as_api_response
42   end
43
44   def create
45     @object = model_class.new resource_attrs
46     @object.save!
47     show
48   end
49
50   def update
51     attrs_to_update = resource_attrs.reject { |k,v|
52       [:kind, :etag, :href].index k
53     }
54     @object.update_attributes! attrs_to_update
55     show
56   end
57
58   def destroy
59     @object.destroy
60     show
61   end
62
63   def catch_redirect_hint
64     if !current_user
65       if params.has_key?('redirect_to') then
66         session[:redirect_to] = params[:redirect_to]
67       end
68     end
69   end
70
71   begin
72     rescue_from Exception,
73     :with => :render_error
74     rescue_from ActiveRecord::RecordNotFound,
75     :with => :render_not_found
76     rescue_from ActionController::RoutingError,
77     :with => :render_not_found
78     rescue_from ActionController::UnknownController,
79     :with => :render_not_found
80     rescue_from AbstractController::ActionNotFound,
81     :with => :render_not_found
82     rescue_from ArvadosModel::PermissionDeniedError,
83     :with => :render_error
84   end
85
86   def render_404_if_no_object
87     render_not_found "Object not found" if !@object
88   end
89
90   def render_error(e)
91     logger.error e.inspect
92     if e.respond_to? :backtrace and e.backtrace
93       logger.error e.backtrace.collect { |x| x + "\n" }.join('')
94     end
95     if @object and @object.errors and @object.errors.full_messages and not @object.errors.full_messages.empty?
96       errors = @object.errors.full_messages
97     else
98       errors = [e.inspect]
99     end
100     status = e.respond_to?(:http_status) ? e.http_status : 422
101     render json: { errors: errors }, status: status
102   end
103
104   def render_not_found(e=ActionController::RoutingError.new("Path not found"))
105     logger.error e.inspect
106     render json: { errors: ["Path not found"] }, status: 404
107   end
108
109   protected
110
111   def apply_where_limit_order_params
112     ft = record_filters @filters
113     if ft[:cond_out].any?
114       @objects = @objects.where(ft[:cond_out].join(' AND '), *ft[:param_out])
115     end
116
117     if @where.is_a? Hash and @where.any?
118       conditions = ['1=1']
119       @where.each do |attr,value|
120         if attr.to_s == 'any'
121           if value.is_a?(Array) and
122               value.length == 2 and
123               value[0] == 'contains' then
124             ilikes = []
125             model_class.searchable_columns('ilike').each do |column|
126               ilikes << "#{table_name}.#{column} ilike ?"
127               conditions << "%#{value[1]}%"
128             end
129             if ilikes.any?
130               conditions[0] << ' and (' + ilikes.join(' or ') + ')'
131             end
132           end
133         elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
134             model_class.columns.collect(&:name).index(attr.to_s)
135           if value.nil?
136             conditions[0] << " and #{table_name}.#{attr} is ?"
137             conditions << nil
138           elsif value.is_a? Array
139             if value[0] == 'contains' and value.length == 2
140               conditions[0] << " and #{table_name}.#{attr} like ?"
141               conditions << "%#{value[1]}%"
142             else
143               conditions[0] << " and #{table_name}.#{attr} in (?)"
144               conditions << value
145             end
146           elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
147             conditions[0] << " and #{table_name}.#{attr}=?"
148             conditions << value
149           elsif value.is_a? Hash
150             # Not quite the same thing as "equal?" but better than nothing?
151             value.each do |k,v|
152               if v.is_a? String
153                 conditions[0] << " and #{table_name}.#{attr} ilike ?"
154                 conditions << "%#{k}%#{v}%"
155               end
156             end
157           end
158         end
159       end
160       if conditions.length > 1
161         conditions[0].sub!(/^1=1 and /, '')
162         @objects = @objects.
163           where(*conditions)
164       end
165     end
166
167     if params[:limit]
168       begin
169         @limit = params[:limit].to_i
170       rescue
171         raise ArgumentError.new("Invalid value for limit parameter")
172       end
173     else
174       @limit = 100
175     end
176     @objects = @objects.limit(@limit)
177
178     orders = []
179
180     if params[:offset]
181       begin
182         @objects = @objects.offset(params[:offset].to_i)
183         @offset = params[:offset].to_i
184       rescue
185         raise ArgumentError.new("Invalid value for limit parameter")
186       end
187     else
188       @offset = 0
189     end
190
191     orders = []
192     if params[:order]
193       params[:order].split(',').each do |order|
194         attr, direction = order.strip.split " "
195         direction ||= 'asc'
196         if attr.match /^[a-z][_a-z0-9]+$/ and
197             model_class.columns.collect(&:name).index(attr) and
198             ['asc','desc'].index direction.downcase
199           orders << "#{table_name}.#{attr} #{direction.downcase}"
200         end
201       end
202     end
203     if orders.empty?
204       orders << "#{table_name}.modified_at desc"
205     end
206     @objects = @objects.order(orders.join ", ")
207   end
208
209   def find_objects_for_index
210     @objects ||= model_class.readable_by(current_user)
211     apply_where_limit_order_params
212   end
213
214   def resource_attrs
215     return @attrs if @attrs
216     @attrs = params[resource_name]
217     if @attrs.is_a? String
218       @attrs = Oj.load @attrs, symbol_keys: true
219     end
220     unless @attrs.is_a? Hash
221       message = "No #{resource_name}"
222       if resource_name.index('_')
223         message << " (or #{resource_name.camelcase(:lower)})"
224       end
225       message << " hash provided with request"
226       raise ArgumentError.new(message)
227     end
228     %w(created_at modified_by_client_uuid modified_by_user_uuid modified_at).each do |x|
229       @attrs.delete x.to_sym
230     end
231     @attrs = @attrs.symbolize_keys if @attrs.is_a? HashWithIndifferentAccess
232     @attrs
233   end
234
235   # Authentication
236   def require_login
237     if current_user
238       true
239     else
240       respond_to do |format|
241         format.json {
242           render :json => { errors: ['Not logged in'] }.to_json, status: 401
243         }
244         format.html  {
245           redirect_to '/auth/joshid'
246         }
247       end
248       false
249     end
250   end
251
252   def admin_required
253     unless current_user and current_user.is_admin
254       render :json => { errors: ['Forbidden'] }.to_json, status: 403
255     end
256   end
257
258   def require_auth_scope_all
259     require_login and require_auth_scope(['all'])
260   end
261
262   def require_auth_scope(ok_scopes)
263     unless current_api_client_auth_has_scope(ok_scopes)
264       render :json => { errors: ['Forbidden'] }.to_json, status: 403
265     end
266   end
267
268   def model_class
269     controller_name.classify.constantize
270   end
271
272   def resource_name             # params[] key used by client
273     controller_name.singularize
274   end
275
276   def table_name
277     controller_name
278   end
279
280   def find_object_by_uuid
281     if params[:id] and params[:id].match /\D/
282       params[:uuid] = params.delete :id
283     end
284     @where = { uuid: params[:uuid] }
285     find_objects_for_index
286     @object = @objects.first
287   end
288
289   def reload_object_before_update
290     # This is necessary to prevent an ActiveRecord::ReadOnlyRecord
291     # error when updating an object which was retrieved using a join.
292     if @object.andand.readonly?
293       @object = model_class.find_by_uuid(@objects.first.uuid)
294     end
295   end
296
297   def self.accept_attribute_as_json(attr, force_class=nil)
298     before_filter lambda { accept_attribute_as_json attr, force_class }
299   end
300   accept_attribute_as_json :properties, Hash
301   accept_attribute_as_json :info, Hash
302   def accept_attribute_as_json(attr, force_class)
303     if params[resource_name] and resource_attrs.is_a? Hash
304       if resource_attrs[attr].is_a? String
305         resource_attrs[attr] = Oj.load(resource_attrs[attr],
306                                        symbol_keys: false)
307         if force_class and !resource_attrs[attr].is_a? force_class
308           raise TypeError.new("#{resource_name}[#{attr.to_s}] must be a #{force_class.to_s}")
309         end
310       elsif resource_attrs[attr].is_a? Hash
311         # Convert symbol keys to strings (in hashes provided by
312         # resource_attrs)
313         resource_attrs[attr] = resource_attrs[attr].
314           with_indifferent_access.to_hash
315       end
316     end
317   end
318
319   def render_list
320     @object_list = {
321       :kind  => "arvados##{(@response_resource_name || resource_name).camelize(:lower)}List",
322       :etag => "",
323       :self_link => "",
324       :offset => @offset,
325       :limit => @limit,
326       :items => @objects.as_api_response(nil)
327     }
328     if @objects.respond_to? :except
329       @object_list[:items_available] = @objects.
330         except(:limit).except(:offset).
331         count(:id, distinct: true)
332     end
333     render json: @object_list
334   end
335
336   def remote_ip
337     # Caveat: this is highly dependent on the proxy setup. YMMV.
338     if request.headers.has_key?('HTTP_X_REAL_IP') then
339       # We're behind a reverse proxy
340       @remote_ip = request.headers['HTTP_X_REAL_IP']
341     else
342       # Hopefully, we are not!
343       @remote_ip = request.env['REMOTE_ADDR']
344     end
345   end
346
347   def self._index_requires_parameters
348     {
349       filters: { type: 'array', required: false },
350       where: { type: 'object', required: false },
351       order: { type: 'string', required: false }
352     }
353   end
354
355   def client_accepts_plain_text_stream
356     (request.headers['Accept'].split(' ') &
357      ['text/plain', '*/*']).count > 0
358   end
359
360   def render *opts
361     if opts.first
362       response = opts.first[:json]
363       if response.is_a?(Hash) &&
364           params[:_profile] &&
365           Thread.current[:request_starttime]
366         response[:_profile] = {
367           request_time: Time.now - Thread.current[:request_starttime]
368         }
369       end
370     end
371     super *opts
372   end
373
374   def select_theme
375     return Rails.configuration.arvados_theme
376   end
377 end