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