1 class ApplicationController < ActionController::Base
2 include SessionPersistence
6 before_filter :fetch_body
8 if STATUS == :database_readonly or STATUS == :database_offline
9 def self.cache_sweeper(*sweepers)
15 @user = User.where(:id => session[:user]).where("status IN ('active', 'confirmed', 'suspended')").first
17 if @user.display_name != cookies["_osm_username"]
18 logger.info "Session user '#{@user.display_name}' does not match cookie user '#{cookies['_osm_username']}'"
21 elsif @user.status == "suspended"
23 session_expires_automatically
25 redirect_to :controller => "user", :action => "suspended"
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'
32 redirect_to :controller => "user", :action => "terms", :referer => params[:referer]
34 redirect_to :controller => "user", :action => "terms", :referer => request.fullpath
38 if @user = User.authenticate(:token => session[:token])
39 session[:user] = @user.id
42 rescue Exception => ex
43 logger.info("Exception authorizing user: #{ex.to_s}")
51 redirect_to :controller => 'user', :action => 'login', :referer => request.fullpath
53 render :nothing => true, :status => :forbidden
59 @oauth = @user.access_token(OAUTH_KEY) if @user and defined? OAUTH_KEY
63 # requires the user to be logged in by the token or HTTP methods, or have an
64 # OAuth token with the right capability. this method is a bit of a pain to call
65 # directly, since it's cumbersome to call filters with arguments in rails. to
66 # make it easier to read and write the code, there are some utility methods
68 def require_capability(cap)
69 # when the current token is nil, it means the user logged in with a different
70 # method, otherwise an OAuth token was used, which has to be checked.
71 unless current_token.nil?
72 unless current_token.read_attribute(cap)
73 report_error "OAuth token doesn't have that capability.", :forbidden
80 # require the user to have cookies enabled in their browser
82 if request.cookies["_osm_session"].to_s == ""
83 if params[:cookie_test].nil?
84 session[:cookie_test] = true
85 redirect_to params.merge(:cookie_test => "true")
88 flash.now[:warning] = t 'application.require_cookies.cookies_needed'
91 session.delete(:cookie_test)
95 # Utility methods to make the controller filter methods easier to read and write.
96 def require_allow_read_prefs
97 require_capability(:allow_read_prefs)
99 def require_allow_write_prefs
100 require_capability(:allow_write_prefs)
102 def require_allow_write_diary
103 require_capability(:allow_write_diary)
105 def require_allow_write_api
106 require_capability(:allow_write_api)
108 if REQUIRE_TERMS_AGREED and @user.terms_agreed.nil?
109 report_error "You must accept the contributor terms before you can edit.", :forbidden
113 def require_allow_read_gpx
114 require_capability(:allow_read_gpx)
116 def require_allow_write_gpx
117 require_capability(:allow_write_gpx)
119 def require_allow_write_notes
120 require_capability(:allow_write_notes)
124 # require that the user is a moderator, or fill out a helpful error message
125 # and return them to the index for the controller this is wrapped from.
126 def require_moderator
127 unless @user.moderator?
129 flash[:error] = t('application.require_moderator.not_a_moderator')
130 redirect_to :action => 'index'
132 render :nothing => true, :status => :forbidden
138 # sets up the @user object for use by other methods. this is mostly called
139 # from the authorize method, but can be called elsewhere if authorisation
142 # try and setup using OAuth
143 if not Authenticator.new(self, [:token]).allow?
144 username, passwd = get_auth_data # parse from headers
145 # authenticate per-scheme
147 @user = nil # no authentication provided - perhaps first connect (client should retry after 401)
148 elsif username == 'token'
149 @user = User.authenticate(:token => passwd) # preferred - random token for user from db, passed in basic auth
151 @user = User.authenticate(:username => username, :password => passwd) # basic auth
155 # have we identified the user?
157 # check if the user has been banned
158 if @user.blocks.active.exists?
159 # NOTE: need slightly more helpful message than this.
160 report_error t('application.setup_user_auth.blocked'), :forbidden
163 # if the user hasn't seen the contributor terms then don't
164 # allow editing - they have to go to the web site and see
165 # (but can decline) the CTs to continue.
166 if REQUIRE_TERMS_SEEN and not @user.terms_seen and flash[:skip_terms].nil?
168 report_error t('application.setup_user_auth.need_to_see_terms'), :forbidden
173 def authorize(realm='Web Password', errormessage="Couldn't authenticate you")
174 # make the @user object from any auth sources we have
177 # handle authenticate pass/fail
179 # no auth, the user does not exist or the password was wrong
180 response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
181 render :text => errormessage, :status => :unauthorized
187 # to be used as a before_filter *after* authorize. this checks that
188 # the user is a moderator and, if not, returns a forbidden error.
190 # NOTE: this isn't a very good way of doing it - it duplicates logic
191 # from require_moderator - but what we really need to do is a fairly
192 # drastic refactoring based on :format and respond_to? but not a
193 # good idea to do that in this branch.
194 def authorize_moderator(errormessage="Access restricted to moderators")
195 # check user is a moderator
196 unless @user.moderator?
197 render :text => errormessage, :status => :forbidden
202 def check_database_readable(need_api = false)
203 if STATUS == :database_offline or (need_api and STATUS == :api_offline)
204 redirect_to :controller => 'site', :action => 'offline'
208 def check_database_writable(need_api = false)
209 if STATUS == :database_offline or STATUS == :database_readonly or
210 (need_api and (STATUS == :api_offline or STATUS == :api_readonly))
211 redirect_to :controller => 'site', :action => 'offline'
215 def check_api_readable
216 if api_status == :offline
217 report_error "Database offline for maintenance", :service_unavailable
222 def check_api_writable
223 unless api_status == :online
224 report_error "Database offline for maintenance", :service_unavailable
230 if STATUS == :database_offline
232 elsif STATUS == :database_readonly
240 status = database_status
242 if STATUS == :api_offline
244 elsif STATUS == :api_readonly
252 status = database_status
254 status = :offline if STATUS == :gpx_offline
259 def require_public_data
260 unless @user.data_public?
261 report_error "You must make your edits public to upload new data", :forbidden
266 # Report and error to the user
267 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
268 # rather than only a status code and having the web engine make up a
269 # phrase from that, we can also put the error message into the status
270 # message. For now, rails won't let us)
271 def report_error(message, status = :bad_request)
272 # Todo: some sort of escaping of problem characters in the message
273 response.headers['Error'] = message
275 if request.headers['X-Error-Format'] and
276 request.headers['X-Error-Format'].downcase == "xml"
277 result = OSM::API.new.get_xml_doc
278 result.root.name = "osmError"
279 result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
280 result.root << (XML::Node.new("message") << message)
282 render :text => result.to_s, :content_type => "text/xml"
284 render :text => message, :status => status
289 response.header['Vary'] = 'Accept-Language'
292 if !@user.languages.empty?
293 request.user_preferred_languages = @user.languages
294 response.header['Vary'] = '*'
295 elsif !request.user_preferred_languages.empty?
296 @user.languages = request.user_preferred_languages
301 if request.compatible_language_from(I18n.available_locales).nil?
302 request.user_preferred_languages = request.user_preferred_languages.collect do |pl|
305 while pl.match(/^(.*)-[^-]+$/)
306 pls.push($1) if I18n.available_locales.include?($1.to_sym)
313 if @user and not request.compatible_language_from(I18n.available_locales).nil?
314 @user.languages = request.user_preferred_languages
319 I18n.locale = params[:locale] || request.compatible_language_from(I18n.available_locales) || I18n.default_locale
321 response.headers['Content-Language'] = I18n.locale.to_s
324 def api_call_handle_error
327 rescue ActiveRecord::RecordNotFound => ex
328 render :nothing => true, :status => :not_found
329 rescue LibXML::XML::Error, ArgumentError => ex
330 report_error ex.message, :bad_request
331 rescue ActiveRecord::RecordInvalid => ex
332 message = "#{ex.record.class} #{ex.record.id}: "
333 ex.record.errors.each { |attr,msg| message << "#{attr}: #{msg} (#{ex.record[attr].inspect})" }
334 report_error message, :bad_request
335 rescue OSM::APIError => ex
336 report_error ex.message, ex.status
337 rescue AbstractController::ActionNotFound => ex
339 rescue Exception => ex
340 logger.info("API threw unexpected #{ex.class} exception: #{ex.message}")
341 ex.backtrace.each { |l| logger.info(l) }
342 report_error "#{ex.class}: #{ex.message}", :internal_server_error
347 # asserts that the request method is the +method+ given as a parameter
348 # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
349 def assert_method(method)
350 ok = request.send((method.to_s.downcase + "?").to_sym)
351 raise OSM::APIBadMethodError.new(method) unless ok
355 # wrap an api call in a timeout
357 OSM::Timer.timeout(API_TIMEOUT) do
360 rescue Timeout::Error
361 raise OSM::APITimeoutError
365 # wrap a web page in a timeout
367 OSM::Timer.timeout(WEB_TIMEOUT) do
370 rescue ActionView::Template::Error => ex
371 ex = ex.original_exception
373 if ex.is_a?(ActiveRecord::StatementInvalid) and ex.message =~ /^Timeout::Error/
374 ex = Timeout::Error.new
377 if ex.is_a?(Timeout::Error)
378 render :action => "timeout"
382 rescue Timeout::Error
383 render :action => "timeout"
387 # extend caches_action to include the parameters, locale and logged in
388 # status in all cache keys
389 def self.caches_action(*actions)
390 options = actions.extract_options!
391 cache_path = options[:cache_path] || Hash.new
393 options[:unless] = case options[:unless]
394 when NilClass then Array.new
395 when Array then options[:unless]
396 else unlessp = [ options[:unless] ]
399 options[:unless].push(Proc.new do |controller|
400 controller.params.include?(:page)
403 options[:cache_path] = Proc.new do |controller|
404 cache_path.merge(controller.params).merge(:host => SERVER_URL, :locale => I18n.locale)
407 actions.push(options)
413 # extend expire_action to expire all variants
414 def expire_action(options = {})
415 I18n.available_locales.each do |locale|
416 super options.merge(:host => SERVER_URL, :locale => locale)
421 # is the requestor logged in?
427 # ensure that there is a "this_user" instance variable
429 unless @this_user = User.active.find_by_display_name(params[:display_name])
430 render_unknown_user params[:display_name]
435 # render a "no such user" page
436 def render_unknown_user(name)
437 @title = t "user.no_such_user.title"
438 @not_found_user = name
440 respond_to do |format|
441 format.html { render :template => "user/no_such_user", :status => :not_found }
442 format.all { render :nothing => true, :status => :not_found }
447 # Unfortunately if a PUT or POST request that has a body fails to
448 # read it then Apache will sometimes fail to return the response it
449 # is given to the client properly, instead erroring:
451 # https://issues.apache.org/bugzilla/show_bug.cgi?id=44782
453 # To work round this we call rewind on the body here, which is added
454 # as a filter, to force it to be fetched from Apache into a file.
461 # extract authorisation credentials from headers, returns user = nil if none
463 if request.env.has_key? 'X-HTTP_AUTHORIZATION' # where mod_rewrite might have put it
464 authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split
465 elsif request.env.has_key? 'REDIRECT_X_HTTP_AUTHORIZATION' # mod_fcgi
466 authdata = request.env['REDIRECT_X_HTTP_AUTHORIZATION'].to_s.split
467 elsif request.env.has_key? 'HTTP_AUTHORIZATION' # regular location
468 authdata = request.env['HTTP_AUTHORIZATION'].to_s.split
470 # only basic authentication supported
471 if authdata and authdata[0] == 'Basic'
472 user, pass = Base64.decode64(authdata[1]).split(':',2)
477 # used by oauth plugin to get the current user
482 # used by oauth plugin to set the current user
483 def current_user=(user)
487 # override to stop oauth plugin sending errors
488 def invalid_oauth_response