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