set created_by/at and modified_by/at attributes when saving objects
[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 metadata permissions ON permissions.tail=#{table_name}.uuid AND permissions.head=#{model_class.sanitize current_user.uuid} AND permissions.metadata_class='permission' AND permissions.name='visible_to'").
54       where("#{table_name}.created_by_user=? OR permissions.head IS NOT NULL",
55             current_user.uuid)
56     if params[:where]
57       where = params[:where]
58       where = JSON.parse(where) if where.is_a?(String)
59       conditions = ['1=1']
60       where.each do |attr,value|
61         if (!value.nil? and
62             attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
63             model_class.columns.collect(&:name).index(attr))
64           if value.is_a? Array
65             conditions[0] << " and #{table_name}.#{attr} in (?)"
66             conditions << value
67           else
68             conditions[0] << " and #{table_name}.#{attr}=?"
69             conditions << value
70           end
71         end
72       end
73       if conditions.length > 1
74         conditions[0].sub!(/^1=1 and /, '')
75         @objects = @objects.
76           where(*conditions)
77       end
78     end
79     if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
80       @objects.each(&:eager_load_associations)
81     end
82     render_list
83   end
84
85   def show
86     if @object
87       render json: @object.as_api_response(:superuser)
88     else
89       render_not_found("object not found")
90     end
91   end
92
93   def create
94     @attrs = params[resource_name]
95     if @attrs.nil?
96       raise "no #{resource_name} (or #{resource_name.camelcase(:lower)}) provided with request #{params.inspect}"
97     end
98     if @attrs.class == String
99       @attrs = uncamelcase_hash_keys(JSON.parse @attrs)
100     end
101     @object = model_class.new @attrs
102     @object.save
103     show
104   end
105
106   def update
107     @attrs = params[resource_name]
108     if @attrs.is_a? String
109       @attrs = uncamelcase_hash_keys(JSON.parse @attrs)
110     end
111     @object.update_attributes @attrs
112     show
113   end
114
115   protected
116
117   # Authentication
118   def login_required
119     if !current_user
120       respond_to do |format|
121         format.html  {
122           redirect_to '/auth/joshid'
123         }
124         format.json {
125           render :json => { 'error' => 'Not logged in' }.to_json
126         }
127       end
128     end
129   end
130
131   def thread_with_auth_info
132     begin
133       user = nil
134       api_client = nil
135       api_client_auth = nil
136       if params[:api_token]
137         api_client_auth = ApiClientAuthorization.
138           includes(:api_client, :user).
139           where('api_token=?', params[:api_token]).
140           first
141         if api_client_auth
142           session[:user_id] = api_client_auth.user.id
143           session[:api_client_uuid] = api_client_auth.api_client.uuid
144           user = api_client_auth.user
145           api_client = api_client_auth.api_client
146         end
147       elsif session[:user_id]
148         user = User.find(session[:user_id]) rescue nil
149         api_client = ApiClient.
150           where('uuid=?',session[:api_client_uuid]).
151           first rescue nil
152       end
153       Thread.current[:api_client_trusted] = session[:api_client_trusted]
154       Thread.current[:api_client_ip_address] = remote_ip
155       Thread.current[:api_client] = api_client
156       Thread.current[:user] = user
157       yield
158     ensure
159       Thread.current[:api_client_trusted] = nil
160       Thread.current[:api_client_ip_address] = nil
161       Thread.current[:api_client_uuid] = nil
162       Thread.current[:user] = nil
163     end
164   end
165   # /Authentication
166
167   def model_class
168     controller_name.classify.constantize
169   end
170
171   def resource_name             # params[] key used by client
172     controller_name.singularize
173   end
174
175   def table_name
176     controller_name
177   end
178
179   def find_object_by_uuid
180     if params[:id] and params[:id].match /\D/
181       params[:uuid] = params.delete :id
182     end
183     @object = model_class.where('uuid=?', params[:uuid]).first
184   end
185
186   def self.accept_attribute_as_json(attr, force_class=nil)
187     before_filter lambda { accept_attribute_as_json attr, force_class }
188   end
189   def accept_attribute_as_json(attr, force_class)
190     if params[resource_name].is_a? Hash
191       if params[resource_name][attr].is_a? String
192         params[resource_name][attr] = JSON.parse params[resource_name][attr]
193         if force_class and !params[resource_name][attr].is_a? force_class
194           raise TypeError.new("#{resource_name}[#{attr.to_s}] must be a #{force_class.to_s}")
195         end
196       end
197     end
198   end
199
200   def uncamelcase_params_hash_keys
201     self.params = uncamelcase_hash_keys(params)
202   end
203
204   def uncamelcase_hash_keys(h, max_depth=-1)
205     if h.is_a? Hash and max_depth != 0
206       nh = Hash.new
207       h.each do |k,v|
208         if k.class == String
209           nk = k.underscore
210         elsif k.class == Symbol
211           nk = k.to_s.underscore.to_sym
212         else
213           nk = k
214         end
215         nh[nk] = uncamelcase_hash_keys(v, max_depth-1)
216       end
217       h.replace(nh)
218     end
219     h
220   end
221
222   def render_list
223     @object_list = {
224       :kind  => "orvos##{resource_name}List",
225       :etag => "",
226       :self_link => "",
227       :next_page_token => "",
228       :next_link => "",
229       :items => @objects.as_api_response(:superuser)
230     }
231     render json: @object_list
232   end
233
234   def remote_ip
235     # Caveat: this is highly dependent on the proxy setup. YMMV.
236     if request.headers.has_key?('HTTP_X_REAL_IP') then
237       # We're behind a reverse proxy
238       @remote_ip = request.headers['HTTP_X_REAL_IP']
239     else
240       # Hopefully, we are not!
241       @remote_ip = request.env['REMOTE_ADDR']
242     end
243   end
244 end