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