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