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 # requires the user to be logged in by the token or HTTP methods, or have an
60 # OAuth token with the right capability. this method is a bit of a pain to call
61 # directly, since it's cumbersome to call filters with arguments in rails. to
62 # make it easier to read and write the code, there are some utility methods
64 def require_capability(cap)
65 # when the current token is nil, it means the user logged in with a different
66 # method, otherwise an OAuth token was used, which has to be checked.
67 unless current_token.nil?
68 unless current_token.read_attribute(cap)
69 report_error "OAuth token doesn't have that capability.", :forbidden
76 # require the user to have cookies enabled in their browser
78 if request.cookies["_osm_session"].to_s == ""
79 if params[:cookie_test].nil?
80 session[:cookie_test] = true
81 redirect_to params.merge(:cookie_test => "true")
84 flash.now[:warning] = t 'application.require_cookies.cookies_needed'
87 session.delete(:cookie_test)
91 # Utility methods to make the controller filter methods easier to read and write.
92 def require_allow_read_prefs
93 require_capability(:allow_read_prefs)
95 def require_allow_write_prefs
96 require_capability(:allow_write_prefs)
98 def require_allow_write_diary
99 require_capability(:allow_write_diary)
101 def require_allow_write_api
102 require_capability(:allow_write_api)
104 if REQUIRE_TERMS_AGREED and @user.terms_agreed.nil?
105 report_error "You must accept the contributor terms before you can edit.", :forbidden
109 def require_allow_read_gpx
110 require_capability(:allow_read_gpx)
112 def require_allow_write_gpx
113 require_capability(:allow_write_gpx)
117 # require that the user is a moderator, or fill out a helpful error message
118 # and return them to the index for the controller this is wrapped from.
119 def require_moderator
120 unless @user.moderator?
122 flash[:error] = t('application.require_moderator.not_a_moderator')
123 redirect_to :action => 'index'
125 render :nothing => true, :status => :forbidden
131 # sets up the @user object for use by other methods. this is mostly called
132 # from the authorize method, but can be called elsewhere if authorisation
135 # try and setup using OAuth
136 if not Authenticator.new(self, [:token]).allow?
137 username, passwd = get_auth_data # parse from headers
138 # authenticate per-scheme
140 @user = nil # no authentication provided - perhaps first connect (client should retry after 401)
141 elsif username == 'token'
142 @user = User.authenticate(:token => passwd) # preferred - random token for user from db, passed in basic auth
144 @user = User.authenticate(:username => username, :password => passwd) # basic auth
148 # have we identified the user?
150 # check if the user has been banned
151 if @user.blocks.active.exists?
152 # NOTE: need slightly more helpful message than this.
153 report_error t('application.setup_user_auth.blocked'), :forbidden
156 # if the user hasn't seen the contributor terms then don't
157 # allow editing - they have to go to the web site and see
158 # (but can decline) the CTs to continue.
159 if REQUIRE_TERMS_SEEN and not @user.terms_seen and flash[:skip_terms].nil?
161 report_error t('application.setup_user_auth.need_to_see_terms'), :forbidden
166 def authorize(realm='Web Password', errormessage="Couldn't authenticate you")
167 # make the @user object from any auth sources we have
170 # handle authenticate pass/fail
172 # no auth, the user does not exist or the password was wrong
173 response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
174 render :text => errormessage, :status => :unauthorized
180 # to be used as a before_filter *after* authorize. this checks that
181 # the user is a moderator and, if not, returns a forbidden error.
183 # NOTE: this isn't a very good way of doing it - it duplicates logic
184 # from require_moderator - but what we really need to do is a fairly
185 # drastic refactoring based on :format and respond_to? but not a
186 # good idea to do that in this branch.
187 def authorize_moderator(errormessage="Access restricted to moderators")
188 # check user is a moderator
189 unless @user.moderator?
190 render :text => errormessage, :status => :forbidden
195 def check_database_readable(need_api = false)
196 if STATUS == :database_offline or (need_api and STATUS == :api_offline)
197 redirect_to :controller => 'site', :action => 'offline'
201 def check_database_writable(need_api = false)
202 if STATUS == :database_offline or STATUS == :database_readonly or
203 (need_api and (STATUS == :api_offline or STATUS == :api_readonly))
204 redirect_to :controller => 'site', :action => 'offline'
208 def check_api_readable
209 if api_status == :offline
210 report_error "Database offline for maintenance", :service_unavailable
215 def check_api_writable
216 unless api_status == :online
217 report_error "Database offline for maintenance", :service_unavailable
223 if STATUS == :database_offline
225 elsif STATUS == :database_readonly
233 status = database_status
235 if STATUS == :api_offline
237 elsif STATUS == :api_readonly
245 status = database_status
247 status = :offline if STATUS == :gpx_offline
252 def require_public_data
253 unless @user.data_public?
254 report_error "You must make your edits public to upload new data", :forbidden
259 # Report and error to the user
260 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
261 # rather than only a status code and having the web engine make up a
262 # phrase from that, we can also put the error message into the status
263 # message. For now, rails won't let us)
264 def report_error(message, status = :bad_request)
265 # Todo: some sort of escaping of problem characters in the message
266 response.headers['Error'] = message
268 if request.headers['X-Error-Format'] and
269 request.headers['X-Error-Format'].downcase == "xml"
270 result = OSM::API.new.get_xml_doc
271 result.root.name = "osmError"
272 result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
273 result.root << (XML::Node.new("message") << message)
275 render :text => result.to_s, :content_type => "text/xml"
277 render :text => message, :status => status
282 response.header['Vary'] = 'Accept-Language'
285 if !@user.languages.empty?
286 request.user_preferred_languages = @user.languages
287 response.header['Vary'] = '*'
288 elsif !request.user_preferred_languages.empty?
289 @user.languages = request.user_preferred_languages
294 if request.compatible_language_from(I18n.available_locales).nil?
295 request.user_preferred_languages = request.user_preferred_languages.collect do |pl|
298 while pl.match(/^(.*)-[^-]+$/)
299 pls.push($1) if I18n.available_locales.include?($1.to_sym)
306 if @user and not request.compatible_language_from(I18n.available_locales).nil?
307 @user.languages = request.user_preferred_languages
312 I18n.locale = params[:locale] || request.compatible_language_from(I18n.available_locales) || I18n.default_locale
314 response.headers['Content-Language'] = I18n.locale.to_s
317 def api_call_handle_error
320 rescue ActiveRecord::RecordNotFound => ex
321 render :nothing => true, :status => :not_found
322 rescue LibXML::XML::Error, ArgumentError => ex
323 report_error ex.message, :bad_request
324 rescue ActiveRecord::RecordInvalid => ex
325 message = "#{ex.record.class} #{ex.record.id}: "
326 ex.record.errors.each { |attr,msg| message << "#{attr}: #{msg} (#{ex.record[attr].inspect})" }
327 report_error message, :bad_request
328 rescue OSM::APIError => ex
329 report_error ex.message, ex.status
330 rescue AbstractController::ActionNotFound => ex
332 rescue Exception => ex
333 logger.info("API threw unexpected #{ex.class} exception: #{ex.message}")
334 ex.backtrace.each { |l| logger.info(l) }
335 report_error "#{ex.class}: #{ex.message}", :internal_server_error
340 # asserts that the request method is the +method+ given as a parameter
341 # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
342 def assert_method(method)
343 ok = request.send((method.to_s.downcase + "?").to_sym)
344 raise OSM::APIBadMethodError.new(method) unless ok
348 # wrap an api call in a timeout
350 OSM::Timer.timeout(API_TIMEOUT) do
353 rescue Timeout::Error
354 raise OSM::APITimeoutError
358 # wrap a web page in a timeout
360 OSM::Timer.timeout(WEB_TIMEOUT) do
363 rescue ActionView::Template::Error => ex
364 ex = ex.original_exception
366 if ex.is_a?(ActiveRecord::StatementInvalid) and ex.message =~ /^Timeout::Error/
367 ex = Timeout::Error.new
370 if ex.is_a?(Timeout::Error)
371 render :action => "timeout"
375 rescue Timeout::Error
376 render :action => "timeout"
380 # extend caches_action to include the parameters, locale and logged in
381 # status in all cache keys
382 def self.caches_action(*actions)
383 options = actions.extract_options!
384 cache_path = options[:cache_path] || Hash.new
386 options[:unless] = case options[:unless]
387 when NilClass then Array.new
388 when Array then options[:unless]
389 else unlessp = [ options[:unless] ]
392 options[:unless].push(Proc.new do |controller|
393 controller.params.include?(:page)
396 options[:cache_path] = Proc.new do |controller|
397 cache_path.merge(controller.params).merge(:host => SERVER_URL, :locale => I18n.locale)
400 actions.push(options)
406 # extend expire_action to expire all variants
407 def expire_action(options = {})
408 I18n.available_locales.each do |locale|
409 super options.merge(:host => SERVER_URL, :locale => locale)
414 # is the requestor logged in?
420 # ensure that there is a "this_user" instance variable
422 unless @this_user = User.active.find_by_display_name(params[:display_name])
423 render_unknown_user params[:display_name]
428 # render a "no such user" page
429 def render_unknown_user(name)
430 @title = t "user.no_such_user.title"
431 @not_found_user = name
433 respond_to do |format|
434 format.html { render :template => "user/no_such_user", :status => :not_found }
435 format.all { render :nothing => true, :status => :not_found }
440 # Unfortunately if a PUT or POST request that has a body fails to
441 # read it then Apache will sometimes fail to return the response it
442 # is given to the client properly, instead erroring:
444 # https://issues.apache.org/bugzilla/show_bug.cgi?id=44782
446 # To work round this we call rewind on the body here, which is added
447 # as a filter, to force it to be fetched from Apache into a file.
454 # extract authorisation credentials from headers, returns user = nil if none
456 if request.env.has_key? 'X-HTTP_AUTHORIZATION' # where mod_rewrite might have put it
457 authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split
458 elsif request.env.has_key? 'REDIRECT_X_HTTP_AUTHORIZATION' # mod_fcgi
459 authdata = request.env['REDIRECT_X_HTTP_AUTHORIZATION'].to_s.split
460 elsif request.env.has_key? 'HTTP_AUTHORIZATION' # regular location
461 authdata = request.env['HTTP_AUTHORIZATION'].to_s.split
463 # only basic authentication supported
464 if authdata and authdata[0] == 'Basic'
465 user, pass = Base64.decode64(authdata[1]).split(':',2)
470 # used by oauth plugin to get the current user
475 # used by oauth plugin to set the current user
476 def current_user=(user)
480 # override to stop oauth plugin sending errors
481 def invalid_oauth_response