1 class ApplicationController < ActionController::Base
2 include SessionPersistence
6 if STATUS == :database_readonly or STATUS == :database_offline
7 after_filter :clear_session
14 def self.cache_sweeper(*sweepers)
20 @user = User.where(:id => session[:user]).where("status IN ('active', 'confirmed', 'suspended')").first
22 if @user.display_name != cookies["_osm_username"]
23 logger.info "Session user '#{@user.display_name}' does not match cookie user '#{cookies['_osm_username']}'"
26 elsif @user.status == "suspended"
28 session_expires_automatically
30 redirect_to :controller => "user", :action => "suspended"
32 # don't allow access to any auth-requiring part of the site unless
33 # the new CTs have been seen (and accept/decline chosen).
34 elsif !@user.terms_seen and flash[:skip_terms].nil?
35 flash[:notice] = t 'user.terms.you need to accept or decline'
37 redirect_to :controller => "user", :action => "terms", :referer => params[:referer]
39 redirect_to :controller => "user", :action => "terms", :referer => request.fullpath
43 if @user = User.authenticate(:token => session[:token])
44 session[:user] = @user.id
47 rescue Exception => ex
48 logger.info("Exception authorizing user: #{ex.to_s}")
56 redirect_to :controller => 'user', :action => 'login', :referer => request.fullpath
58 render :nothing => true, :status => :forbidden
64 # requires the user to be logged in by the token or HTTP methods, or have an
65 # OAuth token with the right capability. this method is a bit of a pain to call
66 # directly, since it's cumbersome to call filters with arguments in rails. to
67 # make it easier to read and write the code, there are some utility methods
69 def require_capability(cap)
70 # when the current token is nil, it means the user logged in with a different
71 # method, otherwise an OAuth token was used, which has to be checked.
72 unless current_token.nil?
73 unless current_token.read_attribute(cap)
74 report_error "OAuth token doesn't have that capability.", :forbidden
81 # require the user to have cookies enabled in their browser
83 if request.cookies["_osm_session"].to_s == ""
84 if params[:cookie_test].nil?
85 session[:cookie_test] = true
86 redirect_to params.merge(:cookie_test => "true")
89 flash.now[:warning] = t 'application.require_cookies.cookies_needed'
92 session.delete(:cookie_test)
96 # Utility methods to make the controller filter methods easier to read and write.
97 def require_allow_read_prefs
98 require_capability(:allow_read_prefs)
100 def require_allow_write_prefs
101 require_capability(:allow_write_prefs)
103 def require_allow_write_diary
104 require_capability(:allow_write_diary)
106 def require_allow_write_api
107 require_capability(:allow_write_api)
109 if REQUIRE_TERMS_AGREED and @user.terms_agreed.nil?
110 report_error "You must accept the contributor terms before you can edit.", :forbidden
114 def require_allow_read_gpx
115 require_capability(:allow_read_gpx)
117 def require_allow_write_gpx
118 require_capability(:allow_write_gpx)
122 # sets up the @user object for use by other methods. this is mostly called
123 # from the authorize method, but can be called elsewhere if authorisation
126 # try and setup using OAuth
127 if not Authenticator.new(self, [:token]).allow?
128 username, passwd = get_auth_data # parse from headers
129 # authenticate per-scheme
131 @user = nil # no authentication provided - perhaps first connect (client should retry after 401)
132 elsif username == 'token'
133 @user = User.authenticate(:token => passwd) # preferred - random token for user from db, passed in basic auth
135 @user = User.authenticate(:username => username, :password => passwd) # basic auth
139 # have we identified the user?
141 # check if the user has been banned
142 if not @user.active_blocks.empty?
143 # NOTE: need slightly more helpful message than this.
144 report_error t('application.setup_user_auth.blocked'), :forbidden
147 # if the user hasn't seen the contributor terms then don't
148 # allow editing - they have to go to the web site and see
149 # (but can decline) the CTs to continue.
150 if REQUIRE_TERMS_SEEN and not @user.terms_seen and flash[:skip_terms].nil?
152 report_error t('application.setup_user_auth.need_to_see_terms'), :forbidden
157 def authorize(realm='Web Password', errormessage="Couldn't authenticate you")
158 # make the @user object from any auth sources we have
161 # handle authenticate pass/fail
163 # no auth, the user does not exist or the password was wrong
164 response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
165 render :text => errormessage, :status => :unauthorized
170 def check_database_readable(need_api = false)
171 if STATUS == :database_offline or (need_api and STATUS == :api_offline)
172 redirect_to :controller => 'site', :action => 'offline'
176 def check_database_writable(need_api = false)
177 if STATUS == :database_offline or STATUS == :database_readonly or
178 (need_api and (STATUS == :api_offline or STATUS == :api_readonly))
179 redirect_to :controller => 'site', :action => 'offline'
183 def check_api_readable
184 if STATUS == :database_offline or STATUS == :api_offline
185 report_error "Database offline for maintenance", :service_unavailable
190 def check_api_writable
191 if STATUS == :database_offline or STATUS == :database_readonly or
192 STATUS == :api_offline or STATUS == :api_readonly
193 report_error "Database offline for maintenance", :service_unavailable
198 def require_public_data
199 unless @user.data_public?
200 report_error "You must make your edits public to upload new data", :forbidden
205 # Report and error to the user
206 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
207 # rather than only a status code and having the web engine make up a
208 # phrase from that, we can also put the error message into the status
209 # message. For now, rails won't let us)
210 def report_error(message, status = :bad_request)
211 # Todo: some sort of escaping of problem characters in the message
212 response.headers['Error'] = message
214 if request.headers['X-Error-Format'] and
215 request.headers['X-Error-Format'].downcase == "xml"
216 result = OSM::API.new.get_xml_doc
217 result.root.name = "osmError"
218 result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
219 result.root << (XML::Node.new("message") << message)
221 render :text => result.to_s, :content_type => "text/xml"
223 render :text => message, :status => status
228 response.header['Vary'] = 'Accept-Language'
231 if !@user.languages.empty?
232 request.user_preferred_languages = @user.languages
233 response.header['Vary'] = '*'
234 elsif !request.user_preferred_languages.empty?
235 @user.languages = request.user_preferred_languages
240 if request.compatible_language_from(I18n.available_locales).nil?
241 request.user_preferred_languages = request.user_preferred_languages.collect do |pl|
244 while pl.match(/^(.*)-[^-]+$/)
245 pls.push($1) if I18n.available_locales.include?($1.to_sym)
252 if @user and not request.compatible_language_from(I18n.available_locales).nil?
253 @user.languages = request.user_preferred_languages
258 I18n.locale = request.compatible_language_from(I18n.available_locales) || I18n.default_locale
260 response.headers['Content-Language'] = I18n.locale.to_s
263 def api_call_handle_error
266 rescue ActiveRecord::RecordNotFound => ex
267 render :nothing => true, :status => :not_found
268 rescue LibXML::XML::Error, ArgumentError => ex
269 report_error ex.message, :bad_request
270 rescue ActiveRecord::RecordInvalid => ex
271 message = "#{ex.record.class} #{ex.record.id}: "
272 ex.record.errors.each { |attr,msg| message << "#{attr}: #{msg} (#{ex.record[attr].inspect})" }
273 report_error message, :bad_request
274 rescue OSM::APIError => ex
275 report_error ex.message, ex.status
276 rescue AbstractController::ActionNotFound => ex
278 rescue Exception => ex
279 logger.info("API threw unexpected #{ex.class} exception: #{ex.message}")
280 ex.backtrace.each { |l| logger.info(l) }
281 report_error "#{ex.class}: #{ex.message}", :internal_server_error
286 # asserts that the request method is the +method+ given as a parameter
287 # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
288 def assert_method(method)
289 ok = request.send((method.to_s.downcase + "?").to_sym)
290 raise OSM::APIBadMethodError.new(method) unless ok
294 # wrap an api call in a timeout
296 OSM::Timer.timeout(API_TIMEOUT) do
299 rescue Timeout::Error
300 raise OSM::APITimeoutError
304 # wrap a web page in a timeout
306 OSM::Timer.timeout(WEB_TIMEOUT) do
309 rescue ActionView::Template::Error => ex
310 ex = ex.original_exception
312 if ex.is_a?(ActiveRecord::StatementInvalid) and ex.message =~ /^Timeout::Error/
313 ex = Timeout::Error.new
316 if ex.is_a?(Timeout::Error)
317 render :action => "timeout"
321 rescue Timeout::Error
322 render :action => "timeout"
326 # extend caches_action to include the parameters, locale and logged in
327 # status in all cache keys
328 def self.caches_action(*actions)
329 options = actions.extract_options!
330 cache_path = options[:cache_path] || Hash.new
332 options[:unless] = case options[:unless]
333 when NilClass then Array.new
334 when Array then options[:unless]
335 else unlessp = [ options[:unless] ]
338 options[:unless].push(Proc.new do |controller|
339 controller.params.include?(:page)
342 options[:cache_path] = Proc.new do |controller|
343 cache_path.merge(controller.params).merge(:host => SERVER_URL, :locale => I18n.locale)
346 actions.push(options)
352 # extend expire_action to expire all variants
353 def expire_action(options = {})
354 I18n.available_locales.each do |locale|
355 super options.merge(:host => SERVER_URL, :locale => locale)
360 # is the requestor logged in?
367 # extract authorisation credentials from headers, returns user = nil if none
369 if request.env.has_key? 'X-HTTP_AUTHORIZATION' # where mod_rewrite might have put it
370 authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split
371 elsif request.env.has_key? 'REDIRECT_X_HTTP_AUTHORIZATION' # mod_fcgi
372 authdata = request.env['REDIRECT_X_HTTP_AUTHORIZATION'].to_s.split
373 elsif request.env.has_key? 'HTTP_AUTHORIZATION' # regular location
374 authdata = request.env['HTTP_AUTHORIZATION'].to_s.split
376 # only basic authentication supported
377 if authdata and authdata[0] == 'Basic'
378 user, pass = Base64.decode64(authdata[1]).split(':',2)
383 # used by oauth plugin to get the current user
388 # used by oauth plugin to set the current user
389 def current_user=(user)
393 # override to stop oauth plugin sending errors
394 def invalid_oauth_response