include indivually permitted objects in #index responses
[arvados.git] / services / api / app / controllers / application_controller.rb
1 class ApplicationController < ActionController::Base
2   include CurrentApiClient
3
4   protect_from_forgery
5   before_filter :uncamelcase_params_hash_keys
6   around_filter :thread_with_auth_info, :except => [:render_error, :render_not_found]
7
8   before_filter :remote_ip
9   before_filter :login_required, :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
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(:superuser)
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     attrs_to_update = resource_attrs.reject { |k,v| [:kind,:etag].index k }
42     if @object.update_attributes attrs_to_update
43       show
44     else
45       render json: { errors: @object.errors.full_messages }, status: 422
46     end
47   end
48
49   def destroy
50     @object.destroy
51     show
52   end
53
54   def catch_redirect_hint
55     if !current_user
56       if params.has_key?('redirect_to') then
57         session[:redirect_to] = params[:redirect_to]
58       end
59     end
60   end
61
62   unless Rails.application.config.consider_all_requests_local
63     rescue_from Exception,
64     :with => :render_error
65     rescue_from ActiveRecord::RecordNotFound,
66     :with => :render_not_found
67     rescue_from ActionController::RoutingError,
68     :with => :render_not_found
69     rescue_from ActionController::UnknownController,
70     :with => :render_not_found
71     rescue_from ActionController::UnknownAction,
72     :with => :render_not_found
73   end
74
75   def render_error(e)
76     logger.error e.inspect
77     logger.error e.backtrace.collect { |x| x + "\n" }.join('') if e.backtrace
78     if @object and @object.errors and @object.errors.full_messages and not @object.errors.full_messages.empty?
79       errors = @object.errors.full_messages
80     else
81       errors = [e.inspect]
82     end
83     render json: { errors: errors }, status: 422
84   end
85
86   def render_not_found(e=ActionController::RoutingError.new("Path not found"))
87     logger.error e.inspect
88     render json: { errors: ["Path not found"] }, status: 404
89   end
90
91   protected
92
93   def load_where_param
94     @where = params[:where] || {}
95     @where = Oj.load(@where) if @where.is_a?(String)
96   end
97
98   def find_objects_for_index
99     uuid_list = [current_user.uuid, *current_user.groups_i_can(:read)]
100     sanitized_uuid_list = uuid_list.
101       collect { |uuid| model_class.sanitize(uuid) }.join(', ')
102     @objects ||= model_class.
103       joins("LEFT JOIN links permissions ON permissions.head_uuid in (#{table_name}.owner, #{table_name}.uuid) AND permissions.tail_uuid in (#{sanitized_uuid_list}) AND permissions.link_class='permission'").
104       where("?=? OR #{table_name}.owner in (?) OR #{table_name}.uuid=? OR permissions.head_uuid IS NOT NULL",
105             true, current_user.is_admin,
106             uuid_list,
107             current_user.uuid)
108     if !@where.empty?
109       conditions = ['1=1']
110       @where.each do |attr,value|
111         if attr == 'any' or attr == :any
112           if value.is_a?(Array) and
113               value[0] == 'contains' and
114               model_class.columns.collect(&:name).index('name') then
115             conditions[0] << " and #{table_name}.name ilike ?"
116             conditions << "%#{value[1]}%"
117           end
118         elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
119             model_class.columns.collect(&:name).index(attr.to_s)
120           if value.nil?
121             conditions[0] << " and #{table_name}.#{attr} is ?"
122             conditions << nil
123           elsif value.is_a? Array
124             conditions[0] << " and #{table_name}.#{attr} in (?)"
125             conditions << value
126           elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
127             conditions[0] << " and #{table_name}.#{attr}=?"
128             conditions << value
129           elsif value.is_a? Hash
130             # Not quite the same thing as "equal?" but better than nothing?
131             value.each do |k,v|
132               if v.is_a? String
133                 conditions[0] << " and #{table_name}.#{attr} ilike ?"
134                 conditions << "%#{k}%#{v}%"
135               end
136             end
137           end
138         end
139       end
140       if conditions.length > 1
141         conditions[0].sub!(/^1=1 and /, '')
142         @objects = @objects.
143           where(*conditions)
144       end
145     end
146     if params[:limit]
147       begin
148         @objects = @objects.limit(params[:limit].to_i)
149       rescue
150         raise ArgumentError.new("Invalid value for limit parameter")
151       end
152     else
153       @objects = @objects.limit(100)
154     end
155     orders = []
156     if params[:order]
157       params[:order].split(',').each do |order|
158         attr, direction = order.strip.split " "
159         direction ||= 'asc'
160         if attr.match /^[a-z][_a-z0-9]+$/ and
161             model_class.columns.collect(&:name).index(attr) and
162             ['asc','desc'].index direction.downcase
163           orders << "#{table_name}.#{attr} #{direction.downcase}"
164         end
165       end
166     end
167     if orders.empty?
168       orders << "#{table_name}.modified_at desc"
169     end
170     @objects = @objects.order(orders.join ", ")
171   end
172
173   def resource_attrs
174     return @attrs if @attrs
175     @attrs = params[resource_name]
176     if @attrs.is_a? String
177       @attrs = uncamelcase_hash_keys(Oj.load @attrs)
178     end
179     unless @attrs.is_a? Hash
180       message = "No #{resource_name}"
181       if resource_name.index('_')
182         message << " (or #{resource_name.camelcase(:lower)})"
183       end
184       message << " hash provided with request"
185       raise ArgumentError.new(message)
186     end
187     %w(created_at modified_by_client modified_by_user modified_at).each do |x|
188       @attrs.delete x
189     end
190     @attrs
191   end
192
193   # Authentication
194   def login_required
195     if !current_user
196       respond_to do |format|
197         format.html  {
198           redirect_to '/auth/joshid'
199         }
200         format.json {
201           render :json => { errors: ['Not logged in'] }.to_json
202         }
203       end
204     end
205   end
206
207   def thread_with_auth_info
208     begin
209       user = nil
210       api_client = nil
211       api_client_auth = nil
212       supplied_token =
213         params[:api_token] ||
214         params[:oauth_token] ||
215         request.headers["Authorization"].andand.match(/OAuth2 ([a-z0-9]+)/).andand[1]
216       if supplied_token
217         api_client_auth = ApiClientAuthorization.
218           includes(:api_client, :user).
219           where('api_token=?', supplied_token).
220           first
221         if api_client_auth
222           session[:user_id] = api_client_auth.user.id
223           session[:api_client_uuid] = api_client_auth.api_client.uuid
224           session[:api_client_authorization_id] = api_client_auth.id
225           user = api_client_auth.user
226           api_client = api_client_auth.api_client
227         end
228       elsif session[:user_id]
229         user = User.find(session[:user_id]) rescue nil
230         api_client = ApiClient.
231           where('uuid=?',session[:api_client_uuid]).
232           first rescue nil
233         if session[:api_client_authorization_id] then
234           api_client_auth = ApiClientAuthorization.
235             find session[:api_client_authorization_id]
236         end
237       end
238       Thread.current[:api_client_trusted] = session[:api_client_trusted]
239       Thread.current[:api_client_ip_address] = remote_ip
240       Thread.current[:api_client_authorization] = api_client_auth
241       Thread.current[:api_client_uuid] = api_client && api_client.uuid
242       Thread.current[:api_client] = api_client
243       Thread.current[:user] = user
244       yield
245     ensure
246       Thread.current[:api_client_trusted] = nil
247       Thread.current[:api_client_ip_address] = nil
248       Thread.current[:api_client_authorization] = nil
249       Thread.current[:api_client_uuid] = nil
250       Thread.current[:api_client] = nil
251       Thread.current[:user] = nil
252     end
253   end
254   # /Authentication
255
256   def model_class
257     controller_name.classify.constantize
258   end
259
260   def resource_name             # params[] key used by client
261     controller_name.singularize
262   end
263
264   def table_name
265     controller_name
266   end
267
268   def find_object_by_uuid
269     if params[:id] and params[:id].match /\D/
270       params[:uuid] = params.delete :id
271     end
272     @object = model_class.where('uuid=?', params[:uuid]).first
273   end
274
275   def self.accept_attribute_as_json(attr, force_class=nil)
276     before_filter lambda { accept_attribute_as_json attr, force_class }
277   end
278   def accept_attribute_as_json(attr, force_class)
279     if params[resource_name].is_a? Hash
280       if params[resource_name][attr].is_a? String
281         params[resource_name][attr] = Oj.load params[resource_name][attr]
282         if force_class and !params[resource_name][attr].is_a? force_class
283           raise TypeError.new("#{resource_name}[#{attr.to_s}] must be a #{force_class.to_s}")
284         end
285       end
286     end
287   end
288
289   def uncamelcase_params_hash_keys
290     self.params = uncamelcase_hash_keys(params)
291   end
292   def uncamelcase_hash_keys(h, max_depth=-1)
293     if h.is_a? Hash and max_depth != 0
294       nh = Hash.new
295       h.each do |k,v|
296         if k.class == String
297           nk = k.underscore
298         elsif k.class == Symbol
299           nk = k.to_s.underscore.to_sym
300         else
301           nk = k
302         end
303         nh[nk] = uncamelcase_hash_keys(v, max_depth-1)
304       end
305       h.replace(nh)
306     end
307     h
308   end
309
310   def render_list
311     @object_list = {
312       :kind  => "arvados##{resource_name}List",
313       :etag => "",
314       :self_link => "",
315       :next_page_token => "",
316       :next_link => "",
317       :items => @objects.as_api_response(:superuser)
318     }
319     render json: @object_list
320   end
321
322   def remote_ip
323     # Caveat: this is highly dependent on the proxy setup. YMMV.
324     if request.headers.has_key?('HTTP_X_REAL_IP') then
325       # We're behind a reverse proxy
326       @remote_ip = request.headers['HTTP_X_REAL_IP']
327     else
328       # Hopefully, we are not!
329       @remote_ip = request.env['REMOTE_ADDR']
330     end
331   end
332
333   def self._index_requires_parameters
334     {
335       where: { type: 'object', required: false },
336       order: { type: 'string', required: false }
337     }
338   end
339 end