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