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