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