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