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