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