1 class ApplicationController < ActionController::Base
 
   2   include SessionPersistence
 
   6   before_filter :fetch_body
 
  10       @user = User.where(:id => session[:user]).where("status IN ('active', 'confirmed', 'suspended')").first
 
  12     if @user.status == "suspended"
 
  14         session_expires_automatically
 
  16         redirect_to :controller => "user", :action => "suspended"
 
  18         # don't allow access to any auth-requiring part of the site unless
 
  19         # the new CTs have been seen (and accept/decline chosen).
 
  20       elsif !@user.terms_seen and flash[:skip_terms].nil?
 
  21         flash[:notice] = t 'user.terms.you need to accept or decline'
 
  23           redirect_to :controller => "user", :action => "terms", :referer => params[:referer]
 
  25           redirect_to :controller => "user", :action => "terms", :referer => request.fullpath
 
  29       if @user = User.authenticate(:token => session[:token])
 
  30         session[:user] = @user.id
 
  33   rescue Exception => ex
 
  34     logger.info("Exception authorizing user: #{ex.to_s}")
 
  42         redirect_to :controller => 'user', :action => 'login', :referer => request.fullpath
 
  44         render :text => "", :status => :forbidden
 
  50     @oauth = @user.access_token(OAUTH_KEY) if @user and defined? OAUTH_KEY
 
  54   # requires the user to be logged in by the token or HTTP methods, or have an 
 
  55   # OAuth token with the right capability. this method is a bit of a pain to call 
 
  56   # directly, since it's cumbersome to call filters with arguments in rails. to
 
  57   # make it easier to read and write the code, there are some utility methods
 
  59   def require_capability(cap)
 
  60     # when the current token is nil, it means the user logged in with a different
 
  61     # method, otherwise an OAuth token was used, which has to be checked.
 
  62     unless current_token.nil?
 
  63       unless current_token.read_attribute(cap)
 
  64         report_error "OAuth token doesn't have that capability.", :forbidden
 
  71   # require the user to have cookies enabled in their browser
 
  73     if request.cookies["_osm_session"].to_s == ""
 
  74       if params[:cookie_test].nil?
 
  75         session[:cookie_test] = true
 
  76         redirect_to Hash[params].merge(:cookie_test => "true")
 
  79         flash.now[:warning] = t 'application.require_cookies.cookies_needed'
 
  82       session.delete(:cookie_test)
 
  86   # Utility methods to make the controller filter methods easier to read and write.
 
  87   def require_allow_read_prefs
 
  88     require_capability(:allow_read_prefs)
 
  90   def require_allow_write_prefs
 
  91     require_capability(:allow_write_prefs)
 
  93   def require_allow_write_diary
 
  94     require_capability(:allow_write_diary)
 
  96   def require_allow_write_api
 
  97     require_capability(:allow_write_api)
 
  99     if REQUIRE_TERMS_AGREED and @user.terms_agreed.nil?
 
 100       report_error "You must accept the contributor terms before you can edit.", :forbidden
 
 104   def require_allow_read_gpx
 
 105     require_capability(:allow_read_gpx)
 
 107   def require_allow_write_gpx
 
 108     require_capability(:allow_write_gpx)
 
 110   def require_allow_write_notes
 
 111     require_capability(:allow_write_notes)
 
 115   # require that the user is a moderator, or fill out a helpful error message
 
 116   # and return them to the index for the controller this is wrapped from.
 
 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 :text => "", :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 @user.blocks.active.exists?
 
 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   # NOTE: this isn't a very good way of doing it - it duplicates logic
 
 182   # from require_moderator - but what we really need to do is a fairly
 
 183   # drastic refactoring based on :format and respond_to? but not a 
 
 184   # good idea to do that in this branch.
 
 185   def authorize_moderator(errormessage="Access restricted to moderators") 
 
 186     # check user is a moderator
 
 187     unless @user.moderator?
 
 188       render :text => errormessage, :status => :forbidden
 
 193   def check_database_readable(need_api = false)
 
 194     if STATUS == :database_offline or (need_api and STATUS == :api_offline)
 
 196         report_error "Database offline for maintenance", :service_unavailable
 
 198         redirect_to :controller => 'site', :action => 'offline'
 
 203   def check_database_writable(need_api = false)
 
 204     if STATUS == :database_offline or STATUS == :database_readonly or
 
 205        (need_api and (STATUS == :api_offline or STATUS == :api_readonly))
 
 207         report_error "Database offline for maintenance", :service_unavailable
 
 209         redirect_to :controller => 'site', :action => 'offline'
 
 214   def check_api_readable
 
 215     if api_status == :offline
 
 216       report_error "Database offline for maintenance", :service_unavailable
 
 221   def check_api_writable
 
 222     unless api_status == :online
 
 223       report_error "Database offline for maintenance", :service_unavailable
 
 229     if STATUS == :database_offline
 
 231     elsif STATUS == :database_readonly
 
 239     status = database_status
 
 241       if STATUS == :api_offline
 
 243       elsif STATUS == :api_readonly
 
 251     status = database_status
 
 253       status = :offline if STATUS == :gpx_offline
 
 258   def require_public_data
 
 259     unless @user.data_public?
 
 260       report_error "You must make your edits public to upload new data", :forbidden
 
 265   # Report and error to the user
 
 266   # (If anyone ever fixes Rails so it can set a http status "reason phrase",
 
 267   #  rather than only a status code and having the web engine make up a 
 
 268   #  phrase from that, we can also put the error message into the status
 
 269   #  message. For now, rails won't let us)
 
 270   def report_error(message, status = :bad_request)
 
 271     # Todo: some sort of escaping of problem characters in the message
 
 272     response.headers['Error'] = message
 
 274     if request.headers['X-Error-Format'] and
 
 275        request.headers['X-Error-Format'].downcase == "xml"
 
 276       result = OSM::API.new.get_xml_doc
 
 277       result.root.name = "osmError"
 
 278       result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
 
 279       result.root << (XML::Node.new("message") << message)
 
 281       render :text => result.to_s, :content_type => "text/xml"
 
 283       render :text => message, :status => status, :content_type => "text/plain"
 
 288     response.header['Vary'] = 'Accept-Language'
 
 290     if @user && !@user.languages.empty?
 
 291       http_accept_language.user_preferred_languages = @user.languages
 
 292       response.header['Vary'] = '*'
 
 295     I18n.locale = select_locale
 
 297     if @user && @user.languages.empty? && !http_accept_language.user_preferred_languages.empty?
 
 298       @user.languages = http_accept_language.user_preferred_languages
 
 302     response.headers['Content-Language'] = I18n.locale.to_s
 
 305   def select_locale(locales = I18n.available_locales)
 
 307       http_accept_language.user_preferred_languages = [ params[:locale] ]
 
 310     if http_accept_language.compatible_language_from(locales).nil?
 
 311       http_accept_language.user_preferred_languages = http_accept_language.user_preferred_languages.collect do |pl|
 
 314         while pl.match(/^(.*)-[^-]+$/)
 
 315           pls.push($1) if locales.include?($1) or locales.include?($1.to_sym)
 
 323     http_accept_language.compatible_language_from(locales) || I18n.default_locale
 
 326   helper_method :select_locale
 
 328   def api_call_handle_error
 
 331     rescue ActiveRecord::RecordNotFound => ex
 
 332       render :text => "", :status => :not_found
 
 333     rescue LibXML::XML::Error, ArgumentError => ex
 
 334       report_error ex.message, :bad_request
 
 335     rescue ActiveRecord::RecordInvalid => ex
 
 336       message = "#{ex.record.class} #{ex.record.id}: "
 
 337       ex.record.errors.each { |attr,msg| message << "#{attr}: #{msg} (#{ex.record[attr].inspect})" }
 
 338       report_error message, :bad_request
 
 339     rescue OSM::APIError => ex
 
 340       report_error ex.message, ex.status
 
 341     rescue AbstractController::ActionNotFound => ex
 
 343     rescue Exception => ex
 
 344       logger.info("API threw unexpected #{ex.class} exception: #{ex.message}")
 
 345       ex.backtrace.each { |l| logger.info(l) }
 
 346       report_error "#{ex.class}: #{ex.message}", :internal_server_error
 
 351   # asserts that the request method is the +method+ given as a parameter
 
 352   # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
 
 353   def assert_method(method)
 
 354     ok = request.send((method.to_s.downcase + "?").to_sym)
 
 355     raise OSM::APIBadMethodError.new(method) unless ok
 
 359   # wrap an api call in a timeout
 
 361     OSM::Timer.timeout(API_TIMEOUT) do
 
 364   rescue Timeout::Error
 
 365     raise OSM::APITimeoutError
 
 369   # wrap a web page in a timeout
 
 371     OSM::Timer.timeout(WEB_TIMEOUT) do
 
 374   rescue ActionView::Template::Error => ex
 
 375     ex = ex.original_exception
 
 377     if ex.is_a?(ActiveRecord::StatementInvalid) and ex.message =~ /execution expired/
 
 378       ex = Timeout::Error.new
 
 381     if ex.is_a?(Timeout::Error)
 
 382       render :action => "timeout"
 
 386   rescue Timeout::Error
 
 387     render :action => "timeout"
 
 391   # is the requestor logged in?
 
 397   # ensure that there is a "this_user" instance variable
 
 399     unless @this_user = User.active.find_by_display_name(params[:display_name])
 
 400       render_unknown_user params[:display_name]
 
 405   # render a "no such user" page
 
 406   def render_unknown_user(name)
 
 407     @title = t "user.no_such_user.title"
 
 408     @not_found_user = name
 
 410     respond_to do |format|
 
 411       format.html { render :template => "user/no_such_user", :status => :not_found }
 
 412       format.all { render :text => "", :status => :not_found }
 
 417   # Unfortunately if a PUT or POST request that has a body fails to
 
 418   # read it then Apache will sometimes fail to return the response it
 
 419   # is given to the client properly, instead erroring:
 
 421   #   https://issues.apache.org/bugzilla/show_bug.cgi?id=44782
 
 423   # To work round this we call rewind on the body here, which is added
 
 424   # as a filter, to force it to be fetched from Apache into a file.
 
 430     request.xhr? ? 'xhr' : 'map'
 
 434     editor = if params[:editor]
 
 436     elsif @user and @user.preferred_editor
 
 437       @user.preferred_editor
 
 442     if request.env['HTTP_USER_AGENT'] =~ /MSIE|Trident/ and editor == 'id'
 
 449   helper_method :preferred_editor
 
 453   # extract authorisation credentials from headers, returns user = nil if none
 
 455     if request.env.has_key? 'X-HTTP_AUTHORIZATION'          # where mod_rewrite might have put it 
 
 456       authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split 
 
 457     elsif request.env.has_key? 'REDIRECT_X_HTTP_AUTHORIZATION'          # mod_fcgi 
 
 458       authdata = request.env['REDIRECT_X_HTTP_AUTHORIZATION'].to_s.split 
 
 459     elsif request.env.has_key? 'HTTP_AUTHORIZATION'         # regular location
 
 460       authdata = request.env['HTTP_AUTHORIZATION'].to_s.split
 
 462     # only basic authentication supported
 
 463     if authdata and authdata[0] == 'Basic' 
 
 464       user, pass = Base64.decode64(authdata[1]).split(':',2)
 
 469   # used by oauth plugin to get the current user
 
 474   # used by oauth plugin to set the current user
 
 475   def current_user=(user)
 
 479   # override to stop oauth plugin sending errors
 
 480   def invalid_oauth_response