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