Merge branch 'master' into 2257-inequality-conditions
[arvados.git] / services / api / app / controllers / application_controller.rb
1 class ApplicationController < ActionController::Base
2   include CurrentApiClient
3
4   respond_to :json
5   protect_from_forgery
6   around_filter :thread_with_auth_info, :except => [:render_error, :render_not_found]
7
8   before_filter :remote_ip
9   before_filter :require_auth_scope_all, :except => :render_not_found
10   before_filter :catch_redirect_hint
11
12   before_filter :load_where_param, :only => :index
13   before_filter :load_filters_param, :only => :index
14   before_filter :find_objects_for_index, :only => :index
15   before_filter :find_object_by_uuid, :except => [:index, :create,
16                                                   :render_error,
17                                                   :render_not_found]
18   before_filter :reload_object_before_update, :only => :update
19   before_filter :render_404_if_no_object, except: [:index, :create,
20                                                    :render_error,
21                                                    :render_not_found]
22
23   attr_accessor :resource_attrs
24
25   def index
26     @objects.uniq!(&:id)
27     if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
28       @objects.each(&:eager_load_associations)
29     end
30     render_list
31   end
32
33   def show
34     render json: @object.as_api_response
35   end
36
37   def create
38     @object = model_class.new resource_attrs
39     if @object.save
40       show
41     else
42       raise "Save failed"
43     end
44   end
45
46   def update
47     attrs_to_update = resource_attrs.reject { |k,v|
48       [:kind, :etag, :href].index k
49     }
50     if @object.update_attributes attrs_to_update
51       show
52     else
53       raise "Update failed"
54     end
55   end
56
57   def destroy
58     @object.destroy
59     show
60   end
61
62   def catch_redirect_hint
63     if !current_user
64       if params.has_key?('redirect_to') then
65         session[:redirect_to] = params[:redirect_to]
66       end
67     end
68   end
69
70   begin
71     rescue_from Exception,
72     :with => :render_error
73     rescue_from ActiveRecord::RecordNotFound,
74     :with => :render_not_found
75     rescue_from ActionController::RoutingError,
76     :with => :render_not_found
77     rescue_from ActionController::UnknownController,
78     :with => :render_not_found
79     rescue_from AbstractController::ActionNotFound,
80     :with => :render_not_found
81     rescue_from ArvadosModel::PermissionDeniedError,
82     :with => :render_error
83   end
84
85   def render_404_if_no_object
86     render_not_found "Object not found" if !@object
87   end
88
89   def render_error(e)
90     logger.error e.inspect
91     if e.respond_to? :backtrace and e.backtrace
92       logger.error e.backtrace.collect { |x| x + "\n" }.join('')
93     end
94     if @object and @object.errors and @object.errors.full_messages and not @object.errors.full_messages.empty?
95       errors = @object.errors.full_messages
96     else
97       errors = [e.inspect]
98     end
99     status = e.respond_to?(:http_status) ? e.http_status : 422
100     render json: { errors: errors }, status: status
101   end
102
103   def render_not_found(e=ActionController::RoutingError.new("Path not found"))
104     logger.error e.inspect
105     render json: { errors: ["Path not found"] }, status: 404
106   end
107
108   protected
109
110   def load_where_param
111     if params[:where].nil? or params[:where] == ""
112       @where = {}
113     elsif params[:where].is_a? Hash
114       @where = params[:where]
115     elsif params[:where].is_a? String
116       begin
117         @where = Oj.load(params[:where])
118         raise unless @where.is_a? Hash
119       rescue
120         raise ArgumentError.new("Could not parse \"where\" param as an object")
121       end
122     end
123     @where = @where.with_indifferent_access
124   end
125
126   def load_filters_param
127     if params[:filters].is_a? Array
128       @filters = params[:filters]
129     elsif params[:filters].is_a? String
130       begin
131         @filters = Oj.load params[:filters]
132         raise unless @filters.is_a? Array
133       rescue
134         raise ArgumentError.new("Could not parse \"filters\" param as an array")
135       end
136     end
137   end
138
139   def find_objects_for_index
140     @objects ||= model_class.readable_by(current_user)
141     apply_where_limit_order_params
142   end
143
144   def apply_where_limit_order_params
145     if @filters.is_a? Array and @filters.any?
146       cond_out = []
147       param_out = []
148       @filters.each do |attr, operator, operand|
149         if !model_class.searchable_columns.index attr.to_s
150           raise ArgumentError.new("Invalid attribute '#{attr}' in condition")
151         end
152         case operator.downcase
153         when '=', '<', '<=', '>', '>=', 'like'
154           if operand.is_a? String
155             cond_out << "#{table_name}.#{attr} #{operator} ?"
156             if operator.match(/[<=>]/) and
157                 model_class.attribute_column(attr).type == :datetime
158               operand = Time.parse operand
159             end
160             param_out << operand
161           end
162         when 'in'
163           if operand.is_a? Array
164             cond_out << "#{table_name}.#{attr} IN (?)"
165             param_out << operand
166           end
167         end
168       end
169       if cond_out.any?
170         @objects = @objects.where(cond_out.join(' AND '), *param_out)
171       end
172     end
173     if @where.is_a? Hash and @where.any?
174       conditions = ['1=1']
175       @where.each do |attr,value|
176         if attr == :any
177           if value.is_a?(Array) and
178               value.length == 2 and
179               value[0] == 'contains' and
180               model_class.columns.collect(&:name).index('name') then
181             ilikes = []
182             model_class.searchable_columns.each do |column|
183               ilikes << "#{table_name}.#{column} ilike ?"
184               conditions << "%#{value[1]}%"
185             end
186             if ilikes.any?
187               conditions[0] << ' and (' + ilikes.join(' or ') + ')'
188             end
189           end
190         elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
191             model_class.columns.collect(&:name).index(attr.to_s)
192           if value.nil?
193             conditions[0] << " and #{table_name}.#{attr} is ?"
194             conditions << nil
195           elsif value.is_a? Array
196             if value[0] == 'contains' and value.length == 2
197               conditions[0] << " and #{table_name}.#{attr} like ?"
198               conditions << "%#{value[1]}%"
199             else
200               conditions[0] << " and #{table_name}.#{attr} in (?)"
201               conditions << value
202             end
203           elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
204             conditions[0] << " and #{table_name}.#{attr}=?"
205             conditions << value
206           elsif value.is_a? Hash
207             # Not quite the same thing as "equal?" but better than nothing?
208             value.each do |k,v|
209               if v.is_a? String
210                 conditions[0] << " and #{table_name}.#{attr} ilike ?"
211                 conditions << "%#{k}%#{v}%"
212               end
213             end
214           end
215         end
216       end
217       if conditions.length > 1
218         conditions[0].sub!(/^1=1 and /, '')
219         @objects = @objects.
220           where(*conditions)
221       end
222     end
223     if params[:limit]
224       begin
225         @objects = @objects.limit(params[:limit].to_i)
226       rescue
227         raise ArgumentError.new("Invalid value for limit parameter")
228       end
229     else
230       @objects = @objects.limit(100)
231     end
232     orders = []
233     if params[:order]
234       params[:order].split(',').each do |order|
235         attr, direction = order.strip.split " "
236         direction ||= 'asc'
237         if attr.match /^[a-z][_a-z0-9]+$/ and
238             model_class.columns.collect(&:name).index(attr) and
239             ['asc','desc'].index direction.downcase
240           orders << "#{table_name}.#{attr} #{direction.downcase}"
241         end
242       end
243     end
244     if orders.empty?
245       orders << "#{table_name}.modified_at desc"
246     end
247     @objects = @objects.order(orders.join ", ")
248   end
249
250   def resource_attrs
251     return @attrs if @attrs
252     @attrs = params[resource_name]
253     if @attrs.is_a? String
254       @attrs = Oj.load @attrs, symbol_keys: true
255     end
256     unless @attrs.is_a? Hash
257       message = "No #{resource_name}"
258       if resource_name.index('_')
259         message << " (or #{resource_name.camelcase(:lower)})"
260       end
261       message << " hash provided with request"
262       raise ArgumentError.new(message)
263     end
264     %w(created_at modified_by_client_uuid modified_by_user_uuid modified_at).each do |x|
265       @attrs.delete x.to_sym
266     end
267     @attrs = @attrs.symbolize_keys if @attrs.is_a? HashWithIndifferentAccess
268     @attrs
269   end
270
271   # Authentication
272   def require_login
273     if current_user
274       true
275     else
276       respond_to do |format|
277         format.json {
278           render :json => { errors: ['Not logged in'] }.to_json, status: 401
279         }
280         format.html  {
281           redirect_to '/auth/joshid'
282         }
283       end
284       false
285     end
286   end
287
288   def admin_required
289     unless current_user and current_user.is_admin
290       render :json => { errors: ['Forbidden'] }.to_json, status: 403
291     end
292   end
293
294   def require_auth_scope_all
295     require_login and require_auth_scope(['all'])
296   end
297
298   def require_auth_scope(ok_scopes)
299     unless current_api_client_auth_has_scope(ok_scopes)
300       render :json => { errors: ['Forbidden'] }.to_json, status: 403
301     end
302   end
303
304   def thread_with_auth_info
305     Thread.current[:request_starttime] = Time.now
306     Thread.current[:api_url_base] = root_url.sub(/\/$/,'') + '/arvados/v1'
307     begin
308       user = nil
309       api_client = nil
310       api_client_auth = nil
311       supplied_token =
312         params[:api_token] ||
313         params[:oauth_token] ||
314         request.headers["Authorization"].andand.match(/OAuth2 ([a-z0-9]+)/).andand[1]
315       if supplied_token
316         api_client_auth = ApiClientAuthorization.
317           includes(:api_client, :user).
318           where('api_token=? and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', supplied_token).
319           first
320         if api_client_auth.andand.user
321           session[:user_id] = api_client_auth.user.id
322           session[:api_client_uuid] = api_client_auth.api_client.andand.uuid
323           session[:api_client_authorization_id] = api_client_auth.id
324           user = api_client_auth.user
325           api_client = api_client_auth.api_client
326         end
327       elsif session[:user_id]
328         user = User.find(session[:user_id]) rescue nil
329         api_client = ApiClient.
330           where('uuid=?',session[:api_client_uuid]).
331           first rescue nil
332         if session[:api_client_authorization_id] then
333           api_client_auth = ApiClientAuthorization.
334             find session[:api_client_authorization_id]
335         end
336       end
337       Thread.current[:api_client_ip_address] = remote_ip
338       Thread.current[:api_client_authorization] = api_client_auth
339       Thread.current[:api_client_uuid] = api_client.andand.uuid
340       Thread.current[:api_client] = api_client
341       Thread.current[:user] = user
342       if api_client_auth
343         api_client_auth.last_used_at = Time.now
344         api_client_auth.last_used_by_ip_address = remote_ip
345         api_client_auth.save validate: false
346       end
347       yield
348     ensure
349       Thread.current[:api_client_ip_address] = nil
350       Thread.current[:api_client_authorization] = nil
351       Thread.current[:api_client_uuid] = nil
352       Thread.current[:api_client] = nil
353       Thread.current[:user] = nil
354     end
355   end
356   # /Authentication
357
358   def model_class
359     controller_name.classify.constantize
360   end
361
362   def resource_name             # params[] key used by client
363     controller_name.singularize
364   end
365
366   def table_name
367     controller_name
368   end
369
370   def find_object_by_uuid
371     if params[:id] and params[:id].match /\D/
372       params[:uuid] = params.delete :id
373     end
374     @where = { uuid: params[:uuid] }
375     find_objects_for_index
376     @object = @objects.first
377   end
378
379   def reload_object_before_update
380     # This is necessary to prevent an ActiveRecord::ReadOnlyRecord
381     # error when updating an object which was retrieved using a join.
382     if @object.andand.readonly?
383       @object = model_class.find_by_uuid(@objects.first.uuid)
384     end
385   end
386
387   def self.accept_attribute_as_json(attr, force_class=nil)
388     before_filter lambda { accept_attribute_as_json attr, force_class }
389   end
390   accept_attribute_as_json :properties, Hash
391   accept_attribute_as_json :info, Hash
392   def accept_attribute_as_json(attr, force_class)
393     if params[resource_name] and resource_attrs.is_a? Hash
394       if resource_attrs[attr].is_a? String
395         resource_attrs[attr] = Oj.load(resource_attrs[attr],
396                                        symbol_keys: false)
397         if force_class and !resource_attrs[attr].is_a? force_class
398           raise TypeError.new("#{resource_name}[#{attr.to_s}] must be a #{force_class.to_s}")
399         end
400       elsif resource_attrs[attr].is_a? Hash
401         # Convert symbol keys to strings (in hashes provided by
402         # resource_attrs)
403         resource_attrs[attr] = resource_attrs[attr].
404           with_indifferent_access.to_hash
405       end
406     end
407   end
408
409   def render_list
410     @object_list = {
411       :kind  => "arvados##{(@response_resource_name || resource_name).camelize(:lower)}List",
412       :etag => "",
413       :self_link => "",
414       :next_page_token => "",
415       :next_link => "",
416       :items => @objects.as_api_response(nil)
417     }
418     if @objects.respond_to? :except
419       @object_list[:items_available] = @objects.except(:limit).count
420     end
421     render json: @object_list
422   end
423
424   def remote_ip
425     # Caveat: this is highly dependent on the proxy setup. YMMV.
426     if request.headers.has_key?('HTTP_X_REAL_IP') then
427       # We're behind a reverse proxy
428       @remote_ip = request.headers['HTTP_X_REAL_IP']
429     else
430       # Hopefully, we are not!
431       @remote_ip = request.env['REMOTE_ADDR']
432     end
433   end
434
435   def self._index_requires_parameters
436     {
437       filters: { type: 'array', required: false },
438       where: { type: 'object', required: false },
439       order: { type: 'string', required: false }
440     }
441   end
442   
443   def client_accepts_plain_text_stream
444     (request.headers['Accept'].split(' ') &
445      ['text/plain', '*/*']).count > 0
446   end
447
448   def render *opts
449     if opts.first
450       response = opts.first[:json]
451       if response.is_a?(Hash) &&
452           params[:_profile] &&
453           Thread.current[:request_starttime]
454         response[:_profile] = {
455           request_time: Time.now - Thread.current[:request_starttime]
456         }
457       end
458     end
459     super *opts
460   end
461 end