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