]> git.openstreetmap.org Git - rails.git/blob - app/controllers/application_controller.rb
Fix object_id warning
[rails.git] / app / controllers / application_controller.rb
1 class ApplicationController < ActionController::Base
2
3   protect_from_forgery
4
5   if STATUS == :database_readonly or STATUS == :database_offline
6     after_filter :clear_session
7     wrap_parameters false
8
9     def clear_session
10       session.clear
11     end
12
13     def self.cache_sweeper(*sweepers)
14     end
15   end
16
17   def authorize_web
18     if session[:user]
19       @user = User.where(:id => session[:user]).where("status IN ('active', 'confirmed', 'suspended')").first
20
21       if @user.status == "suspended"
22         session.delete(:user)
23         session_expires_automatically
24
25         redirect_to :controller => "user", :action => "suspended"
26
27         # don't allow access to any auth-requiring part of the site unless
28         # the new CTs have been seen (and accept/decline chosen).
29       elsif !@user.terms_seen and flash[:skip_terms].nil?
30         flash[:notice] = t 'user.terms.you need to accept or decline'
31         if params[:referer]
32           redirect_to :controller => "user", :action => "terms", :referer => params[:referer]
33         else
34           redirect_to :controller => "user", :action => "terms", :referer => request.fullpath
35         end
36       end
37     elsif session[:token]
38       if @user = User.authenticate(:token => session[:token])
39         session[:user] = @user.id
40       end
41     end
42   rescue Exception => ex
43     logger.info("Exception authorizing user: #{ex.to_s}")
44     @user = nil
45   end
46
47   def require_user
48     redirect_to :controller => 'user', :action => 'login', :referer => request.fullpath unless @user
49   end
50
51   ##
52   # requires the user to be logged in by the token or HTTP methods, or have an 
53   # OAuth token with the right capability. this method is a bit of a pain to call 
54   # directly, since it's cumbersome to call filters with arguments in rails. to
55   # make it easier to read and write the code, there are some utility methods
56   # below.
57   def require_capability(cap)
58     # when the current token is nil, it means the user logged in with a different
59     # method, otherwise an OAuth token was used, which has to be checked.
60     unless current_token.nil?
61       unless current_token.read_attribute(cap)
62         report_error "OAuth token doesn't have that capability.", :forbidden
63         return false
64       end
65     end
66   end
67
68   ##
69   # require the user to have cookies enabled in their browser
70   def require_cookies
71     if request.cookies["_osm_session"].to_s == ""
72       if params[:cookie_test].nil?
73         session[:cookie_test] = true
74         redirect_to params.merge(:cookie_test => "true")
75         return false
76       else
77         flash.now[:warning] = t 'application.require_cookies.cookies_needed'
78       end
79     else
80       session.delete(:cookie_test)
81     end
82   end
83
84   # Utility methods to make the controller filter methods easier to read and write.
85   def require_allow_read_prefs
86     require_capability(:allow_read_prefs)
87   end
88   def require_allow_write_prefs
89     require_capability(:allow_write_prefs)
90   end
91   def require_allow_write_diary
92     require_capability(:allow_write_diary)
93   end
94   def require_allow_write_api
95     require_capability(:allow_write_api)
96
97     if REQUIRE_TERMS_AGREED and @user.terms_agreed.nil?
98       report_error "You must accept the contributor terms before you can edit.", :forbidden
99       return false
100     end
101   end
102   def require_allow_read_gpx
103     require_capability(:allow_read_gpx)
104   end
105   def require_allow_write_gpx
106     require_capability(:allow_write_gpx)
107   end
108
109   ##
110   # sets up the @user object for use by other methods. this is mostly called
111   # from the authorize method, but can be called elsewhere if authorisation
112   # is optional.
113   def setup_user_auth
114     # try and setup using OAuth
115     if not Authenticator.new(self, [:token]).allow?
116       username, passwd = get_auth_data # parse from headers
117       # authenticate per-scheme
118       if username.nil?
119         @user = nil # no authentication provided - perhaps first connect (client should retry after 401)
120       elsif username == 'token'
121         @user = User.authenticate(:token => passwd) # preferred - random token for user from db, passed in basic auth
122       else
123         @user = User.authenticate(:username => username, :password => passwd) # basic auth
124       end
125     end
126
127     # have we identified the user?
128     if @user
129       # check if the user has been banned
130       if not  @user.active_blocks.empty?
131         # NOTE: need slightly more helpful message than this.
132         report_error t('application.setup_user_auth.blocked'), :forbidden
133       end
134
135       # if the user hasn't seen the contributor terms then don't
136       # allow editing - they have to go to the web site and see
137       # (but can decline) the CTs to continue.
138       if REQUIRE_TERMS_SEEN and not @user.terms_seen and flash[:skip_terms].nil?
139         set_locale
140         report_error t('application.setup_user_auth.need_to_see_terms'), :forbidden
141       end
142     end
143   end
144
145   def authorize(realm='Web Password', errormessage="Couldn't authenticate you") 
146     # make the @user object from any auth sources we have
147     setup_user_auth
148
149     # handle authenticate pass/fail
150     unless @user
151       # no auth, the user does not exist or the password was wrong
152       response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\"" 
153       render :text => errormessage, :status => :unauthorized
154       return false
155     end 
156   end 
157
158   def check_database_readable(need_api = false)
159     if STATUS == :database_offline or (need_api and STATUS == :api_offline)
160       redirect_to :controller => 'site', :action => 'offline'
161     end
162   end
163
164   def check_database_writable(need_api = false)
165     if STATUS == :database_offline or STATUS == :database_readonly or
166        (need_api and (STATUS == :api_offline or STATUS == :api_readonly))
167       redirect_to :controller => 'site', :action => 'offline'
168     end
169   end
170
171   def check_api_readable
172     if STATUS == :database_offline or STATUS == :api_offline
173       report_error "Database offline for maintenance", :service_unavailable
174       return false
175     end
176   end
177
178   def check_api_writable
179     if STATUS == :database_offline or STATUS == :database_readonly or
180        STATUS == :api_offline or STATUS == :api_readonly
181       report_error "Database offline for maintenance", :service_unavailable
182       return false
183     end
184   end
185
186   def require_public_data
187     unless @user.data_public?
188       report_error "You must make your edits public to upload new data", :forbidden
189       return false
190     end
191   end
192
193   # Report and error to the user
194   # (If anyone ever fixes Rails so it can set a http status "reason phrase",
195   #  rather than only a status code and having the web engine make up a 
196   #  phrase from that, we can also put the error message into the status
197   #  message. For now, rails won't let us)
198   def report_error(message, status = :bad_request)
199     # Todo: some sort of escaping of problem characters in the message
200     response.headers['Error'] = message
201
202     if request.headers['X-Error-Format'] and
203        request.headers['X-Error-Format'].downcase == "xml"
204       result = OSM::API.new.get_xml_doc
205       result.root.name = "osmError"
206       result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
207       result.root << (XML::Node.new("message") << message)
208
209       render :text => result.to_s, :content_type => "text/xml"
210     else
211       render :text => message, :status => status
212     end
213   end
214   
215   def set_locale
216     response.header['Vary'] = 'Accept-Language'
217
218     if @user
219       if !@user.languages.empty?
220         request.user_preferred_languages = @user.languages
221         response.header['Vary'] = '*'
222       elsif !request.user_preferred_languages.empty?
223         @user.languages = request.user_preferred_languages
224         @user.save
225       end
226     end
227
228     if request.compatible_language_from(I18n.available_locales).nil?
229       request.user_preferred_languages = request.user_preferred_languages.collect do |pl|
230         pls = [ pl ]
231
232         while pl.match(/^(.*)-[^-]+$/)
233           pls.push($1) if I18n.available_locales.include?($1.to_sym)
234           pl = $1
235         end
236
237         pls
238       end.flatten
239
240       if @user and not request.compatible_language_from(I18n.available_locales).nil?
241         @user.languages = request.user_preferred_languages
242         @user.save        
243       end
244     end
245
246     I18n.locale = request.compatible_language_from(I18n.available_locales)
247
248     response.headers['Content-Language'] = I18n.locale.to_s
249   end
250
251   def api_call_handle_error
252     begin
253       yield
254     rescue ActiveRecord::RecordNotFound => ex
255       render :nothing => true, :status => :not_found
256     rescue LibXML::XML::Error, ArgumentError => ex
257       report_error ex.message, :bad_request
258     rescue ActiveRecord::RecordInvalid => ex
259       message = "#{ex.record.class} #{ex.record.id}: "
260       ex.record.errors.each { |attr,msg| message << "#{attr}: #{msg} (#{ex.record[attr].inspect})" }
261       report_error message, :bad_request
262     rescue OSM::APIError => ex
263       report_error ex.message, ex.status
264     rescue ActionController::UnknownAction => ex
265       raise
266     rescue Exception => ex
267       logger.info("API threw unexpected #{ex.class} exception: #{ex.message}")
268       ex.backtrace.each { |l| logger.info(l) }
269       report_error "#{ex.class}: #{ex.message}", :internal_server_error
270     end
271   end
272
273   ##
274   # asserts that the request method is the +method+ given as a parameter
275   # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
276   def assert_method(method)
277     ok = request.send((method.to_s.downcase + "?").to_sym)
278     raise OSM::APIBadMethodError.new(method) unless ok
279   end
280
281   ##
282   # wrap an api call in a timeout
283   def api_call_timeout
284     SystemTimer.timeout_after(API_TIMEOUT) do
285       yield
286     end
287   rescue Timeout::Error
288     raise OSM::APITimeoutError
289   end
290
291   ##
292   # wrap a web page in a timeout
293   def web_timeout
294     SystemTimer.timeout_after(WEB_TIMEOUT) do
295       yield
296     end
297   rescue ActionView::TemplateError => ex
298     if ex.original_exception.is_a?(Timeout::Error)
299       render :action => "timeout"
300     else
301       raise
302     end
303   rescue Timeout::Error
304     render :action => "timeout"
305   end
306
307   ##
308   # extend caches_action to include the parameters, locale and logged in
309   # status in all cache keys
310   def self.caches_action(*actions)
311     options = actions.extract_options!
312     cache_path = options[:cache_path] || Hash.new
313
314     options[:unless] = case options[:unless]
315                        when NilClass then Array.new
316                        when Array then options[:unless]
317                        else unlessp = [ options[:unless] ]
318                        end
319
320     options[:unless].push(Proc.new do |controller|
321       controller.params.include?(:page)
322     end)
323
324     options[:cache_path] = Proc.new do |controller|
325       cache_path.merge(controller.params).merge(:locale => I18n.locale)
326     end
327
328     actions.push(options)
329
330     super *actions
331   end
332
333   ##
334   # extend expire_action to expire all variants
335   def expire_action(options = {})
336     I18n.available_locales.each do |locale|
337       super options.merge(:locale => locale)
338     end
339   end
340
341   ##
342   # is the requestor logged in?
343   def logged_in?
344     !@user.nil?
345   end
346
347 private 
348
349   # extract authorisation credentials from headers, returns user = nil if none
350   def get_auth_data 
351     if request.env.has_key? 'X-HTTP_AUTHORIZATION'          # where mod_rewrite might have put it 
352       authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split 
353     elsif request.env.has_key? 'REDIRECT_X_HTTP_AUTHORIZATION'          # mod_fcgi 
354       authdata = request.env['REDIRECT_X_HTTP_AUTHORIZATION'].to_s.split 
355     elsif request.env.has_key? 'HTTP_AUTHORIZATION'         # regular location
356       authdata = request.env['HTTP_AUTHORIZATION'].to_s.split
357     end 
358     # only basic authentication supported
359     if authdata and authdata[0] == 'Basic' 
360       user, pass = Base64.decode64(authdata[1]).split(':',2)
361     end 
362     return [user, pass] 
363   end 
364
365   # used by oauth plugin to set the current user
366   def current_user=(user)
367     @user=user
368   end
369
370   # override to stop oauth plugin sending errors
371   def invalid_oauth_response
372   end
373
374 end