Merge remote-tracking branch 'origin/master' into 2075-workbench-paging
[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 (# any operator that operates on value rather than
157                 # representation:
158                 operator.match(/[<=>]/) and
159                 model_class.attribute_column(attr).type == :datetime)
160               operand = Time.parse operand
161             end
162             param_out << operand
163           end
164         when 'in'
165           if operand.is_a? Array
166             cond_out << "#{table_name}.#{attr} IN (?)"
167             param_out << operand
168           end
169         end
170       end
171       if cond_out.any?
172         @objects = @objects.where(cond_out.join(' AND '), *param_out)
173       end
174     end
175     if @where.is_a? Hash and @where.any?
176       conditions = ['1=1']
177       @where.each do |attr,value|
178         if attr == :any
179           if value.is_a?(Array) and
180               value.length == 2 and
181               value[0] == 'contains' and
182               model_class.columns.collect(&:name).index('name') then
183             ilikes = []
184             model_class.searchable_columns.each do |column|
185               ilikes << "#{table_name}.#{column} ilike ?"
186               conditions << "%#{value[1]}%"
187             end
188             if ilikes.any?
189               conditions[0] << ' and (' + ilikes.join(' or ') + ')'
190             end
191           end
192         elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
193             model_class.columns.collect(&:name).index(attr.to_s)
194           if value.nil?
195             conditions[0] << " and #{table_name}.#{attr} is ?"
196             conditions << nil
197           elsif value.is_a? Array
198             if value[0] == 'contains' and value.length == 2
199               conditions[0] << " and #{table_name}.#{attr} like ?"
200               conditions << "%#{value[1]}%"
201             else
202               conditions[0] << " and #{table_name}.#{attr} in (?)"
203               conditions << value
204             end
205           elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
206             conditions[0] << " and #{table_name}.#{attr}=?"
207             conditions << value
208           elsif value.is_a? Hash
209             # Not quite the same thing as "equal?" but better than nothing?
210             value.each do |k,v|
211               if v.is_a? String
212                 conditions[0] << " and #{table_name}.#{attr} ilike ?"
213                 conditions << "%#{k}%#{v}%"
214               end
215             end
216           end
217         end
218       end
219       if conditions.length > 1
220         conditions[0].sub!(/^1=1 and /, '')
221         @objects = @objects.
222           where(*conditions)
223       end
224     end
225
226     if params[:limit]
227       begin
228         @limit = params[:limit].to_i
229       rescue
230         raise ArgumentError.new("Invalid value for limit parameter")
231       end
232     else
233       @limit = 100
234     end
235     @objects = @objects.limit(@limit)
236
237     orders = []
238
239     if params[:offset]
240       begin
241         @objects = @objects.offset(params[:offset].to_i)
242         @offset = params[:offset].to_i
243       rescue
244         raise ArgumentError.new("Invalid value for limit parameter")
245       end
246     else
247       @offset = 0
248     end      
249
250     orders = []
251     if params[:order]
252       params[:order].split(',').each do |order|
253         attr, direction = order.strip.split " "
254         direction ||= 'asc'
255         if attr.match /^[a-z][_a-z0-9]+$/ and
256             model_class.columns.collect(&:name).index(attr) and
257             ['asc','desc'].index direction.downcase
258           orders << "#{table_name}.#{attr} #{direction.downcase}"
259         end
260       end
261     end
262     if orders.empty?
263       orders << "#{table_name}.modified_at desc"
264     end
265     @objects = @objects.order(orders.join ", ")
266   end
267
268   def resource_attrs
269     return @attrs if @attrs
270     @attrs = params[resource_name]
271     if @attrs.is_a? String
272       @attrs = Oj.load @attrs, symbol_keys: true
273     end
274     unless @attrs.is_a? Hash
275       message = "No #{resource_name}"
276       if resource_name.index('_')
277         message << " (or #{resource_name.camelcase(:lower)})"
278       end
279       message << " hash provided with request"
280       raise ArgumentError.new(message)
281     end
282     %w(created_at modified_by_client_uuid modified_by_user_uuid modified_at).each do |x|
283       @attrs.delete x.to_sym
284     end
285     @attrs = @attrs.symbolize_keys if @attrs.is_a? HashWithIndifferentAccess
286     @attrs
287   end
288
289   # Authentication
290   def require_login
291     if current_user
292       true
293     else
294       respond_to do |format|
295         format.json {
296           render :json => { errors: ['Not logged in'] }.to_json, status: 401
297         }
298         format.html  {
299           redirect_to '/auth/joshid'
300         }
301       end
302       false
303     end
304   end
305
306   def admin_required
307     unless current_user and current_user.is_admin
308       render :json => { errors: ['Forbidden'] }.to_json, status: 403
309     end
310   end
311
312   def require_auth_scope_all
313     require_login and require_auth_scope(['all'])
314   end
315
316   def require_auth_scope(ok_scopes)
317     unless current_api_client_auth_has_scope(ok_scopes)
318       render :json => { errors: ['Forbidden'] }.to_json, status: 403
319     end
320   end
321
322   def thread_with_auth_info
323     Thread.current[:request_starttime] = Time.now
324     Thread.current[:api_url_base] = root_url.sub(/\/$/,'') + '/arvados/v1'
325     begin
326       user = nil
327       api_client = nil
328       api_client_auth = nil
329       supplied_token =
330         params[:api_token] ||
331         params[:oauth_token] ||
332         request.headers["Authorization"].andand.match(/OAuth2 ([a-z0-9]+)/).andand[1]
333       if supplied_token
334         api_client_auth = ApiClientAuthorization.
335           includes(:api_client, :user).
336           where('api_token=? and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', supplied_token).
337           first
338         if api_client_auth.andand.user
339           session[:user_id] = api_client_auth.user.id
340           session[:api_client_uuid] = api_client_auth.api_client.andand.uuid
341           session[:api_client_authorization_id] = api_client_auth.id
342           user = api_client_auth.user
343           api_client = api_client_auth.api_client
344         end
345       elsif session[:user_id]
346         user = User.find(session[:user_id]) rescue nil
347         api_client = ApiClient.
348           where('uuid=?',session[:api_client_uuid]).
349           first rescue nil
350         if session[:api_client_authorization_id] then
351           api_client_auth = ApiClientAuthorization.
352             find session[:api_client_authorization_id]
353         end
354       end
355       Thread.current[:api_client_ip_address] = remote_ip
356       Thread.current[:api_client_authorization] = api_client_auth
357       Thread.current[:api_client_uuid] = api_client.andand.uuid
358       Thread.current[:api_client] = api_client
359       Thread.current[:user] = user
360       if api_client_auth
361         api_client_auth.last_used_at = Time.now
362         api_client_auth.last_used_by_ip_address = remote_ip
363         api_client_auth.save validate: false
364       end
365       yield
366     ensure
367       Thread.current[:api_client_ip_address] = nil
368       Thread.current[:api_client_authorization] = nil
369       Thread.current[:api_client_uuid] = nil
370       Thread.current[:api_client] = nil
371       Thread.current[:user] = nil
372     end
373   end
374   # /Authentication
375
376   def model_class
377     controller_name.classify.constantize
378   end
379
380   def resource_name             # params[] key used by client
381     controller_name.singularize
382   end
383
384   def table_name
385     controller_name
386   end
387
388   def find_object_by_uuid
389     if params[:id] and params[:id].match /\D/
390       params[:uuid] = params.delete :id
391     end
392     @where = { uuid: params[:uuid] }
393     find_objects_for_index
394     @object = @objects.first
395   end
396
397   def reload_object_before_update
398     # This is necessary to prevent an ActiveRecord::ReadOnlyRecord
399     # error when updating an object which was retrieved using a join.
400     if @object.andand.readonly?
401       @object = model_class.find_by_uuid(@objects.first.uuid)
402     end
403   end
404
405   def self.accept_attribute_as_json(attr, force_class=nil)
406     before_filter lambda { accept_attribute_as_json attr, force_class }
407   end
408   accept_attribute_as_json :properties, Hash
409   accept_attribute_as_json :info, Hash
410   def accept_attribute_as_json(attr, force_class)
411     if params[resource_name] and resource_attrs.is_a? Hash
412       if resource_attrs[attr].is_a? String
413         resource_attrs[attr] = Oj.load(resource_attrs[attr],
414                                        symbol_keys: false)
415         if force_class and !resource_attrs[attr].is_a? force_class
416           raise TypeError.new("#{resource_name}[#{attr.to_s}] must be a #{force_class.to_s}")
417         end
418       elsif resource_attrs[attr].is_a? Hash
419         # Convert symbol keys to strings (in hashes provided by
420         # resource_attrs)
421         resource_attrs[attr] = resource_attrs[attr].
422           with_indifferent_access.to_hash
423       end
424     end
425   end
426
427   def render_list
428     @object_list = {
429       :kind  => "arvados##{(@response_resource_name || resource_name).camelize(:lower)}List",
430       :etag => "",
431       :self_link => "",
432       :offset => @offset,
433       :limit => @limit,
434       :items => @objects.as_api_response(nil)
435     }
436     if @objects.respond_to? :except
437       @object_list[:items_available] = @objects.except(:limit).except(:offset).count
438     end
439     render json: @object_list
440   end
441
442   def remote_ip
443     # Caveat: this is highly dependent on the proxy setup. YMMV.
444     if request.headers.has_key?('HTTP_X_REAL_IP') then
445       # We're behind a reverse proxy
446       @remote_ip = request.headers['HTTP_X_REAL_IP']
447     else
448       # Hopefully, we are not!
449       @remote_ip = request.env['REMOTE_ADDR']
450     end
451   end
452
453   def self._index_requires_parameters
454     {
455       filters: { type: 'array', required: false },
456       where: { type: 'object', required: false },
457       order: { type: 'string', required: false }
458     }
459   end
460   
461   def client_accepts_plain_text_stream
462     (request.headers['Accept'].split(' ') &
463      ['text/plain', '*/*']).count > 0
464   end
465
466   def render *opts
467     if opts.first
468       response = opts.first[:json]
469       if response.is_a?(Hash) &&
470           params[:_profile] &&
471           Thread.current[:request_starttime]
472         response[:_profile] = {
473           request_time: Time.now - Thread.current[:request_starttime]
474         }
475       end
476     end
477     super *opts
478   end
479 end