1 class ApplicationController < ActionController::Base
2 include SessionPersistence
6 if STATUS == :database_readonly or STATUS == :database_offline
7 def self.cache_sweeper(*sweepers)
13 @user = User.where(:id => session[:user]).where("status IN ('active', 'confirmed', 'suspended')").first
15 if @user.display_name != cookies["_osm_username"]
16 logger.info "Session user '#{@user.display_name}' does not match cookie user '#{cookies['_osm_username']}'"
19 elsif @user.status == "suspended"
21 session_expires_automatically
23 redirect_to :controller => "user", :action => "suspended"
25 # don't allow access to any auth-requiring part of the site unless
26 # the new CTs have been seen (and accept/decline chosen).
27 elsif !@user.terms_seen and flash[:skip_terms].nil?
28 flash[:notice] = t 'user.terms.you need to accept or decline'
30 redirect_to :controller => "user", :action => "terms", :referer => params[:referer]
32 redirect_to :controller => "user", :action => "terms", :referer => request.fullpath
36 if @user = User.authenticate(:token => session[:token])
37 session[:user] = @user.id
40 rescue Exception => ex
41 logger.info("Exception authorizing user: #{ex.to_s}")
49 redirect_to :controller => 'user', :action => 'login', :referer => request.fullpath
51 render :nothing => true, :status => :forbidden
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 # require that the user is a moderator, or fill out a helpful error message
116 # and return them to the blocks index.
117 def require_moderator
118 unless @user.moderator?
120 flash[:error] = t('application.require_moderator.not_a_moderator')
121 redirect_to :action => 'index'
123 render :nothing => true, :status => :forbidden
129 # sets up the @user object for use by other methods. this is mostly called
130 # from the authorize method, but can be called elsewhere if authorisation
133 # try and setup using OAuth
134 if not Authenticator.new(self, [:token]).allow?
135 username, passwd = get_auth_data # parse from headers
136 # authenticate per-scheme
138 @user = nil # no authentication provided - perhaps first connect (client should retry after 401)
139 elsif username == 'token'
140 @user = User.authenticate(:token => passwd) # preferred - random token for user from db, passed in basic auth
142 @user = User.authenticate(:username => username, :password => passwd) # basic auth
146 # have we identified the user?
148 # check if the user has been banned
149 if not @user.active_blocks.empty?
150 # NOTE: need slightly more helpful message than this.
151 report_error t('application.setup_user_auth.blocked'), :forbidden
154 # if the user hasn't seen the contributor terms then don't
155 # allow editing - they have to go to the web site and see
156 # (but can decline) the CTs to continue.
157 if REQUIRE_TERMS_SEEN and not @user.terms_seen and flash[:skip_terms].nil?
159 report_error t('application.setup_user_auth.need_to_see_terms'), :forbidden
164 def authorize(realm='Web Password', errormessage="Couldn't authenticate you")
165 # make the @user object from any auth sources we have
168 # handle authenticate pass/fail
170 # no auth, the user does not exist or the password was wrong
171 response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
172 render :text => errormessage, :status => :unauthorized
178 # to be used as a before_filter *after* authorize. this checks that
179 # the user is a moderator and, if not, returns a forbidden error.
181 def authorize_moderator(errormessage="Access restricted to moderators")
182 # check user is a moderator
183 unless @user.moderator?
184 render :text => errormessage, :status => :forbidden
189 def check_database_readable(need_api = false)
190 if STATUS == :database_offline or (need_api and STATUS == :api_offline)
191 redirect_to :controller => 'site', :action => 'offline'
195 def check_database_writable(need_api = false)
196 if STATUS == :database_offline or STATUS == :database_readonly or
197 (need_api and (STATUS == :api_offline or STATUS == :api_readonly))
198 redirect_to :controller => 'site', :action => 'offline'
202 def check_api_readable
203 if STATUS == :database_offline or STATUS == :api_offline
204 report_error "Database offline for maintenance", :service_unavailable
209 def check_api_writable
210 if STATUS == :database_offline or STATUS == :database_readonly or
211 STATUS == :api_offline or STATUS == :api_readonly
212 report_error "Database offline for maintenance", :service_unavailable
217 def require_public_data
218 unless @user.data_public?
219 report_error "You must make your edits public to upload new data", :forbidden
224 # Report and error to the user
225 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
226 # rather than only a status code and having the web engine make up a
227 # phrase from that, we can also put the error message into the status
228 # message. For now, rails won't let us)
229 def report_error(message, status = :bad_request)
230 # Todo: some sort of escaping of problem characters in the message
231 response.headers['Error'] = message
233 if request.headers['X-Error-Format'] and
234 request.headers['X-Error-Format'].downcase == "xml"
235 result = OSM::API.new.get_xml_doc
236 result.root.name = "osmError"
237 result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
238 result.root << (XML::Node.new("message") << message)
240 render :text => result.to_s, :content_type => "text/xml"
242 render :text => message, :status => status
247 response.header['Vary'] = 'Accept-Language'
250 if !@user.languages.empty?
251 request.user_preferred_languages = @user.languages
252 response.header['Vary'] = '*'
253 elsif !request.user_preferred_languages.empty?
254 @user.languages = request.user_preferred_languages
259 if request.compatible_language_from(I18n.available_locales).nil?
260 request.user_preferred_languages = request.user_preferred_languages.collect do |pl|
263 while pl.match(/^(.*)-[^-]+$/)
264 pls.push($1) if I18n.available_locales.include?($1.to_sym)
271 if @user and not request.compatible_language_from(I18n.available_locales).nil?
272 @user.languages = request.user_preferred_languages
277 I18n.locale = request.compatible_language_from(I18n.available_locales) || I18n.default_locale
279 response.headers['Content-Language'] = I18n.locale.to_s
282 def api_call_handle_error
285 rescue ActiveRecord::RecordNotFound => ex
286 render :nothing => true, :status => :not_found
287 rescue LibXML::XML::Error, ArgumentError => ex
288 report_error ex.message, :bad_request
289 rescue ActiveRecord::RecordInvalid => ex
290 message = "#{ex.record.class} #{ex.record.id}: "
291 ex.record.errors.each { |attr,msg| message << "#{attr}: #{msg} (#{ex.record[attr].inspect})" }
292 report_error message, :bad_request
293 rescue OSM::APIError => ex
294 report_error ex.message, ex.status
295 rescue AbstractController::ActionNotFound => ex
297 rescue Exception => ex
298 logger.info("API threw unexpected #{ex.class} exception: #{ex.message}")
299 ex.backtrace.each { |l| logger.info(l) }
300 report_error "#{ex.class}: #{ex.message}", :internal_server_error
305 # asserts that the request method is the +method+ given as a parameter
306 # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
307 def assert_method(method)
308 ok = request.send((method.to_s.downcase + "?").to_sym)
309 raise OSM::APIBadMethodError.new(method) unless ok
313 # wrap an api call in a timeout
315 OSM::Timer.timeout(API_TIMEOUT) do
318 rescue Timeout::Error
319 raise OSM::APITimeoutError
323 # wrap a web page in a timeout
325 OSM::Timer.timeout(WEB_TIMEOUT) do
328 rescue ActionView::Template::Error => ex
329 ex = ex.original_exception
331 if ex.is_a?(ActiveRecord::StatementInvalid) and ex.message =~ /^Timeout::Error/
332 ex = Timeout::Error.new
335 if ex.is_a?(Timeout::Error)
336 render :action => "timeout"
340 rescue Timeout::Error
341 render :action => "timeout"
345 # extend caches_action to include the parameters, locale and logged in
346 # status in all cache keys
347 def self.caches_action(*actions)
348 options = actions.extract_options!
349 cache_path = options[:cache_path] || Hash.new
351 options[:unless] = case options[:unless]
352 when NilClass then Array.new
353 when Array then options[:unless]
354 else unlessp = [ options[:unless] ]
357 options[:unless].push(Proc.new do |controller|
358 controller.params.include?(:page)
361 options[:cache_path] = Proc.new do |controller|
362 cache_path.merge(controller.params).merge(:host => SERVER_URL, :locale => I18n.locale)
365 actions.push(options)
371 # extend expire_action to expire all variants
372 def expire_action(options = {})
373 I18n.available_locales.each do |locale|
374 super options.merge(:host => SERVER_URL, :locale => locale)
379 # is the requestor logged in?
385 # ensure that there is a "this_user" instance variable
387 unless @this_user = User.active.find_by_display_name(params[:display_name])
388 render_unknown_user params[:display_name]
393 # render a "no such user" page
394 def render_unknown_user(name)
395 @title = t "user.no_such_user.title"
396 @not_found_user = name
398 render :template => "user/no_such_user", :status => :not_found
403 # extract authorisation credentials from headers, returns user = nil if none
405 if request.env.has_key? 'X-HTTP_AUTHORIZATION' # where mod_rewrite might have put it
406 authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split
407 elsif request.env.has_key? 'REDIRECT_X_HTTP_AUTHORIZATION' # mod_fcgi
408 authdata = request.env['REDIRECT_X_HTTP_AUTHORIZATION'].to_s.split
409 elsif request.env.has_key? 'HTTP_AUTHORIZATION' # regular location
410 authdata = request.env['HTTP_AUTHORIZATION'].to_s.split
412 # only basic authentication supported
413 if authdata and authdata[0] == 'Basic'
414 user, pass = Base64.decode64(authdata[1]).split(':',2)
419 # used by oauth plugin to get the current user
424 # used by oauth plugin to set the current user
425 def current_user=(user)
429 # override to stop oauth plugin sending errors
430 def invalid_oauth_response