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