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