Merge branch 'master' of git.clinicalfuture.com:arvados
[arvados.git] / services / api / app / controllers / application_controller.rb
1 class ApplicationController < ActionController::Base
2   include CurrentApiClient
3
4   protect_from_forgery
5   around_filter :thread_with_auth_info, :except => [:render_error, :render_not_found]
6
7   before_filter :remote_ip
8   before_filter :require_auth_scope_all, :except => :render_not_found
9   before_filter :catch_redirect_hint
10
11   before_filter :load_where_param, :only => :index
12   before_filter :find_objects_for_index, :only => :index
13   before_filter :find_object_by_uuid, :except => [:index, :create]
14   before_filter :reload_object_before_update, :only => :update
15
16   attr_accessor :resource_attrs
17
18   def index
19     @objects.uniq!(&:id)
20     if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
21       @objects.each(&:eager_load_associations)
22     end
23     render_list
24   end
25
26   def show
27     if @object
28       render json: @object.as_api_response
29     else
30       render_not_found("object not found")
31     end
32   end
33
34   def create
35     @object = model_class.new resource_attrs
36     @object.save
37     show
38   end
39
40   def update
41     if !@object
42       return render_not_found("object not found")
43     end
44     attrs_to_update = resource_attrs.reject { |k,v|
45       [:kind, :etag, :href].index k
46     }
47     if @object.update_attributes attrs_to_update
48       show
49     else
50       render json: { errors: @object.errors.full_messages }, status: 422
51     end
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_error(e)
83     logger.error e.inspect
84     logger.error e.backtrace.collect { |x| x + "\n" }.join('') if e.backtrace
85     if @object and @object.errors and @object.errors.full_messages and not @object.errors.full_messages.empty?
86       errors = @object.errors.full_messages
87     else
88       errors = [e.inspect]
89     end
90     status = e.respond_to?(:http_status) ? e.http_status : 422
91     render json: { errors: errors }, status: status
92   end
93
94   def render_not_found(e=ActionController::RoutingError.new("Path not found"))
95     logger.error e.inspect
96     render json: { errors: ["Path not found"] }, status: 404
97   end
98
99   protected
100
101   def load_where_param
102     if params[:where].nil? or params[:where] == ""
103       @where = {}
104     elsif params[:where].is_a? Hash
105       @where = params[:where]
106     elsif params[:where].is_a? String
107       begin
108         @where = Oj.load(params[:where], symbol_keys: true)
109       rescue
110         raise ArgumentError.new("Could not parse \"where\" param as an object")
111       end
112     end
113   end
114
115   def find_objects_for_index
116     uuid_list = [current_user.uuid, *current_user.groups_i_can(:read)]
117     sanitized_uuid_list = uuid_list.
118       collect { |uuid| model_class.sanitize(uuid) }.join(', ')
119     or_references_me = ''
120     if model_class == Link and current_user
121       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))"
122     end
123     @objects ||= model_class.
124       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'").
125       where("?=? OR #{table_name}.owner_uuid in (?) OR #{table_name}.uuid=? OR permissions.head_uuid IS NOT NULL #{or_references_me}",
126             true, current_user.is_admin,
127             uuid_list,
128             current_user.uuid)
129     if !@where.empty?
130       conditions = ['1=1']
131       @where.each do |attr,value|
132         if attr == :any
133           if value.is_a?(Array) and
134               value[0] == 'contains' and
135               model_class.columns.collect(&:name).index('name') then
136             ilikes = []
137             model_class.searchable_columns.each do |column|
138               ilikes << "#{table_name}.#{column} ilike ?"
139               conditions << "%#{value[1]}%"
140             end
141             if ilikes.any?
142               conditions[0] << ' and (' + ilikes.join(' or ') + ')'
143             end
144           end
145         elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
146             model_class.columns.collect(&:name).index(attr.to_s)
147           if value.nil?
148             conditions[0] << " and #{table_name}.#{attr} is ?"
149             conditions << nil
150           elsif value.is_a? Array
151             conditions[0] << " and #{table_name}.#{attr} in (?)"
152             conditions << value
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
216     end
217     @attrs
218   end
219
220   # Authentication
221   def require_login
222     if current_user
223       true
224     else
225       respond_to do |format|
226         format.json {
227           render :json => { errors: ['Not logged in'] }.to_json, status: 401
228         }
229         format.html  {
230           redirect_to '/auth/joshid'
231         }
232       end
233       false
234     end
235   end
236
237   def admin_required
238     unless current_user and current_user.is_admin
239       render :json => { errors: ['Forbidden'] }.to_json, status: 403
240     end
241   end
242
243   def require_auth_scope_all
244     require_login and require_auth_scope(['all'])
245   end
246
247   def require_auth_scope(ok_scopes)
248     unless current_api_client_auth_has_scope(ok_scopes)
249       render :json => { errors: ['Forbidden'] }.to_json, status: 403
250     end
251   end
252
253   def thread_with_auth_info
254     Thread.current[:request_starttime] = Time.now
255     Thread.current[:api_url_base] = root_url.sub(/\/$/,'') + '/arvados/v1'
256     begin
257       user = nil
258       api_client = nil
259       api_client_auth = nil
260       supplied_token =
261         params[:api_token] ||
262         params[:oauth_token] ||
263         request.headers["Authorization"].andand.match(/OAuth2 ([a-z0-9]+)/).andand[1]
264       if supplied_token
265         api_client_auth = ApiClientAuthorization.
266           includes(:api_client, :user).
267           where('api_token=? and (expires_at is null or expires_at > now())', supplied_token).
268           first
269         if api_client_auth.andand.user
270           session[:user_id] = api_client_auth.user.id
271           session[:api_client_uuid] = api_client_auth.api_client.andand.uuid
272           session[:api_client_authorization_id] = api_client_auth.id
273           user = api_client_auth.user
274           api_client = api_client_auth.api_client
275         end
276       elsif session[:user_id]
277         user = User.find(session[:user_id]) rescue nil
278         api_client = ApiClient.
279           where('uuid=?',session[:api_client_uuid]).
280           first rescue nil
281         if session[:api_client_authorization_id] then
282           api_client_auth = ApiClientAuthorization.
283             find session[:api_client_authorization_id]
284         end
285       end
286       Thread.current[:api_client_ip_address] = remote_ip
287       Thread.current[:api_client_authorization] = api_client_auth
288       Thread.current[:api_client_uuid] = api_client.andand.uuid
289       Thread.current[:api_client] = api_client
290       Thread.current[:user] = user
291       if api_client_auth
292         api_client_auth.last_used_at = Time.now
293         api_client_auth.last_used_by_ip_address = remote_ip
294         api_client_auth.save validate: false
295       end
296       yield
297     ensure
298       Thread.current[:api_client_ip_address] = nil
299       Thread.current[:api_client_authorization] = nil
300       Thread.current[:api_client_uuid] = nil
301       Thread.current[:api_client] = nil
302       Thread.current[:user] = nil
303     end
304   end
305   # /Authentication
306
307   def model_class
308     controller_name.classify.constantize
309   end
310
311   def resource_name             # params[] key used by client
312     controller_name.singularize
313   end
314
315   def table_name
316     controller_name
317   end
318
319   def find_object_by_uuid
320     if params[:id] and params[:id].match /\D/
321       params[:uuid] = params.delete :id
322     end
323     @where = { uuid: params[:uuid] }
324     find_objects_for_index
325     @object = @objects.first
326   end
327
328   def reload_object_before_update
329     # This is necessary to prevent an ActiveRecord::ReadOnlyRecord
330     # error when updating an object which was retrieved using a join.
331     if @object.andand.readonly?
332       @object = model_class.find_by_uuid(@objects.first.uuid)
333     end
334   end
335
336   def self.accept_attribute_as_json(attr, force_class=nil)
337     before_filter lambda { accept_attribute_as_json attr, force_class }
338   end
339   def accept_attribute_as_json(attr, force_class)
340     if params[resource_name].is_a? Hash
341       if params[resource_name][attr].is_a? String
342         params[resource_name][attr] = Oj.load(params[resource_name][attr],
343                                               symbol_keys: true)
344         if force_class and !params[resource_name][attr].is_a? force_class
345           raise TypeError.new("#{resource_name}[#{attr.to_s}] must be a #{force_class.to_s}")
346         end
347       end
348     end
349   end
350
351   def render_list
352     @object_list = {
353       :kind  => "arvados##{(@response_resource_name || resource_name).camelize(:lower)}List",
354       :etag => "",
355       :self_link => "",
356       :next_page_token => "",
357       :next_link => "",
358       :items => @objects.as_api_response(nil)
359     }
360     if @objects.respond_to? :except
361       @object_list[:items_available] = @objects.except(:limit).count
362     end
363     render json: @object_list
364   end
365
366   def remote_ip
367     # Caveat: this is highly dependent on the proxy setup. YMMV.
368     if request.headers.has_key?('HTTP_X_REAL_IP') then
369       # We're behind a reverse proxy
370       @remote_ip = request.headers['HTTP_X_REAL_IP']
371     else
372       # Hopefully, we are not!
373       @remote_ip = request.env['REMOTE_ADDR']
374     end
375   end
376
377   def self._index_requires_parameters
378     {
379       where: { type: 'object', required: false },
380       order: { type: 'string', required: false }
381     }
382   end
383   
384   def client_accepts_plain_text_stream
385     (request.headers['Accept'].split(' ') &
386      ['text/plain', '*/*']).count > 0
387   end
388
389   def render *opts
390     response = opts.first[:json]
391     if response.is_a?(Hash) &&
392         params[:_profile] &&
393         Thread.current[:request_starttime]
394       response[:_profile] = {
395          request_time: Time.now - Thread.current[:request_starttime]
396       }
397     end
398     super *opts
399   end
400 end