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