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