1 class ApplicationController < ActionController::Base
5 if STATUS == :database_readonly or STATUS == :database_offline
6 after_filter :clear_session
13 def self.cache_sweeper(*sweepers)
19 @user = User.where(:id => session[:user]).where("status IN ('active', 'confirmed', 'suspended')").first
21 if @user.display_name != cookies["_osm_username"]
22 logger.info "Session user '#{@user.display_name}' does not match cookie user '#{cookies['_osm_username']}'"
25 elsif @user.status == "suspended"
27 session_expires_automatically
29 redirect_to :controller => "user", :action => "suspended"
31 # don't allow access to any auth-requiring part of the site unless
32 # the new CTs have been seen (and accept/decline chosen).
33 elsif !@user.terms_seen and flash[:skip_terms].nil?
34 flash[:notice] = t 'user.terms.you need to accept or decline'
36 redirect_to :controller => "user", :action => "terms", :referer => params[:referer]
38 redirect_to :controller => "user", :action => "terms", :referer => request.fullpath
42 if @user = User.authenticate(:token => session[:token])
43 session[:user] = @user.id
46 rescue Exception => ex
47 logger.info("Exception authorizing user: #{ex.to_s}")
53 redirect_to :controller => 'user', :action => 'login', :referer => request.fullpath unless @user
57 # requires the user to be logged in by the token or HTTP methods, or have an
58 # OAuth token with the right capability. this method is a bit of a pain to call
59 # directly, since it's cumbersome to call filters with arguments in rails. to
60 # make it easier to read and write the code, there are some utility methods
62 def require_capability(cap)
63 # when the current token is nil, it means the user logged in with a different
64 # method, otherwise an OAuth token was used, which has to be checked.
65 unless current_token.nil?
66 unless current_token.read_attribute(cap)
67 report_error "OAuth token doesn't have that capability.", :forbidden
74 # require the user to have cookies enabled in their browser
76 if request.cookies["_osm_session"].to_s == ""
77 if params[:cookie_test].nil?
78 session[:cookie_test] = true
79 redirect_to params.merge(:cookie_test => "true")
82 flash.now[:warning] = t 'application.require_cookies.cookies_needed'
85 session.delete(:cookie_test)
89 # Utility methods to make the controller filter methods easier to read and write.
90 def require_allow_read_prefs
91 require_capability(:allow_read_prefs)
93 def require_allow_write_prefs
94 require_capability(:allow_write_prefs)
96 def require_allow_write_diary
97 require_capability(:allow_write_diary)
99 def require_allow_write_api
100 require_capability(:allow_write_api)
102 if REQUIRE_TERMS_AGREED and @user.terms_agreed.nil?
103 report_error "You must accept the contributor terms before you can edit.", :forbidden
107 def require_allow_read_gpx
108 require_capability(:allow_read_gpx)
110 def require_allow_write_gpx
111 require_capability(:allow_write_gpx)
115 # sets up the @user object for use by other methods. this is mostly called
116 # from the authorize method, but can be called elsewhere if authorisation
119 # try and setup using OAuth
120 if not Authenticator.new(self, [:token]).allow?
121 username, passwd = get_auth_data # parse from headers
122 # authenticate per-scheme
124 @user = nil # no authentication provided - perhaps first connect (client should retry after 401)
125 elsif username == 'token'
126 @user = User.authenticate(:token => passwd) # preferred - random token for user from db, passed in basic auth
128 @user = User.authenticate(:username => username, :password => passwd) # basic auth
132 # have we identified the user?
134 # check if the user has been banned
135 if not @user.active_blocks.empty?
136 # NOTE: need slightly more helpful message than this.
137 report_error t('application.setup_user_auth.blocked'), :forbidden
140 # if the user hasn't seen the contributor terms then don't
141 # allow editing - they have to go to the web site and see
142 # (but can decline) the CTs to continue.
143 if REQUIRE_TERMS_SEEN and not @user.terms_seen and flash[:skip_terms].nil?
145 report_error t('application.setup_user_auth.need_to_see_terms'), :forbidden
150 def authorize(realm='Web Password', errormessage="Couldn't authenticate you")
151 # make the @user object from any auth sources we have
154 # handle authenticate pass/fail
156 # no auth, the user does not exist or the password was wrong
157 response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
158 render :text => errormessage, :status => :unauthorized
163 def check_database_readable(need_api = false)
164 if STATUS == :database_offline or (need_api and STATUS == :api_offline)
165 redirect_to :controller => 'site', :action => 'offline'
169 def check_database_writable(need_api = false)
170 if STATUS == :database_offline or STATUS == :database_readonly or
171 (need_api and (STATUS == :api_offline or STATUS == :api_readonly))
172 redirect_to :controller => 'site', :action => 'offline'
176 def check_api_readable
177 if STATUS == :database_offline or STATUS == :api_offline
178 report_error "Database offline for maintenance", :service_unavailable
183 def check_api_writable
184 if STATUS == :database_offline or STATUS == :database_readonly or
185 STATUS == :api_offline or STATUS == :api_readonly
186 report_error "Database offline for maintenance", :service_unavailable
191 def require_public_data
192 unless @user.data_public?
193 report_error "You must make your edits public to upload new data", :forbidden
198 # Report and error to the user
199 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
200 # rather than only a status code and having the web engine make up a
201 # phrase from that, we can also put the error message into the status
202 # message. For now, rails won't let us)
203 def report_error(message, status = :bad_request)
204 # Todo: some sort of escaping of problem characters in the message
205 response.headers['Error'] = message
207 if request.headers['X-Error-Format'] and
208 request.headers['X-Error-Format'].downcase == "xml"
209 result = OSM::API.new.get_xml_doc
210 result.root.name = "osmError"
211 result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
212 result.root << (XML::Node.new("message") << message)
214 render :text => result.to_s, :content_type => "text/xml"
216 render :text => message, :status => status
221 response.header['Vary'] = 'Accept-Language'
224 if !@user.languages.empty?
225 request.user_preferred_languages = @user.languages
226 response.header['Vary'] = '*'
227 elsif !request.user_preferred_languages.empty?
228 @user.languages = request.user_preferred_languages
233 if request.compatible_language_from(I18n.available_locales).nil?
234 request.user_preferred_languages = request.user_preferred_languages.collect do |pl|
237 while pl.match(/^(.*)-[^-]+$/)
238 pls.push($1) if I18n.available_locales.include?($1.to_sym)
245 if @user and not request.compatible_language_from(I18n.available_locales).nil?
246 @user.languages = request.user_preferred_languages
251 I18n.locale = request.compatible_language_from(I18n.available_locales) || I18n.default_locale
253 response.headers['Content-Language'] = I18n.locale.to_s
256 def api_call_handle_error
259 rescue ActiveRecord::RecordNotFound => ex
260 render :nothing => true, :status => :not_found
261 rescue LibXML::XML::Error, ArgumentError => ex
262 report_error ex.message, :bad_request
263 rescue ActiveRecord::RecordInvalid => ex
264 message = "#{ex.record.class} #{ex.record.id}: "
265 ex.record.errors.each { |attr,msg| message << "#{attr}: #{msg} (#{ex.record[attr].inspect})" }
266 report_error message, :bad_request
267 rescue OSM::APIError => ex
268 report_error ex.message, ex.status
269 rescue AbstractController::ActionNotFound => ex
271 rescue Exception => ex
272 logger.info("API threw unexpected #{ex.class} exception: #{ex.message}")
273 ex.backtrace.each { |l| logger.info(l) }
274 report_error "#{ex.class}: #{ex.message}", :internal_server_error
279 # asserts that the request method is the +method+ given as a parameter
280 # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
281 def assert_method(method)
282 ok = request.send((method.to_s.downcase + "?").to_sym)
283 raise OSM::APIBadMethodError.new(method) unless ok
287 # wrap an api call in a timeout
289 OSM::Timer.timeout(API_TIMEOUT) do
292 rescue Timeout::Error
293 raise OSM::APITimeoutError
297 # wrap a web page in a timeout
299 OSM::Timer.timeout(WEB_TIMEOUT) do
302 rescue ActionView::Template::Error => ex
303 ex = ex.original_exception
305 if ex.is_a?(ActiveRecord::StatementInvalid) and ex.message =~ /^Timeout::Error/
306 ex = Timeout::Error.new
309 if ex.is_a?(Timeout::Error)
310 render :action => "timeout"
314 rescue Timeout::Error
315 render :action => "timeout"
319 # extend caches_action to include the parameters, locale and logged in
320 # status in all cache keys
321 def self.caches_action(*actions)
322 options = actions.extract_options!
323 cache_path = options[:cache_path] || Hash.new
325 options[:unless] = case options[:unless]
326 when NilClass then Array.new
327 when Array then options[:unless]
328 else unlessp = [ options[:unless] ]
331 options[:unless].push(Proc.new do |controller|
332 controller.params.include?(:page)
335 options[:cache_path] = Proc.new do |controller|
336 cache_path.merge(controller.params).merge(:locale => I18n.locale)
339 actions.push(options)
345 # extend expire_action to expire all variants
346 def expire_action(options = {})
347 I18n.available_locales.each do |locale|
348 super options.merge(:locale => locale)
353 # is the requestor logged in?
360 # extract authorisation credentials from headers, returns user = nil if none
362 if request.env.has_key? 'X-HTTP_AUTHORIZATION' # where mod_rewrite might have put it
363 authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split
364 elsif request.env.has_key? 'REDIRECT_X_HTTP_AUTHORIZATION' # mod_fcgi
365 authdata = request.env['REDIRECT_X_HTTP_AUTHORIZATION'].to_s.split
366 elsif request.env.has_key? 'HTTP_AUTHORIZATION' # regular location
367 authdata = request.env['HTTP_AUTHORIZATION'].to_s.split
369 # only basic authentication supported
370 if authdata and authdata[0] == 'Basic'
371 user, pass = Base64.decode64(authdata[1]).split(':',2)
376 # used by oauth plugin to get the current user
381 # used by oauth plugin to set the current user
382 def current_user=(user)
386 # override to stop oauth plugin sending errors
387 def invalid_oauth_response