1 class ApplicationController < ActionController::Base
 
   2   include SessionPersistence
 
   4   protect_from_forgery :with => :exception
 
   6   rescue_from CanCan::AccessDenied, :with => :deny_access
 
   9   before_action :fetch_body
 
  10   around_action :better_errors_allow_inline, :if => proc { Rails.env.development? }
 
  12   attr_accessor :current_user
 
  13   helper_method :current_user
 
  17       self.current_user = User.where(:id => session[:user]).where("status IN ('active', 'confirmed', 'suspended')").first
 
  19       if current_user.status == "suspended"
 
  21         session_expires_automatically
 
  23         redirect_to :controller => "users", :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 !current_user.terms_seen && flash[:skip_terms].nil?
 
  28         flash[:notice] = t "users.terms.you need to accept or decline"
 
  30           redirect_to :controller => "users", :action => "terms", :referer => params[:referer]
 
  32           redirect_to :controller => "users", :action => "terms", :referer => request.fullpath
 
  36       session[:user] = current_user.id if self.current_user = User.authenticate(:token => session[:token])
 
  38   rescue StandardError => ex
 
  39     logger.info("Exception authorizing user: #{ex}")
 
  41     self.current_user = nil
 
  47         redirect_to :controller => "users", :action => "login", :referer => request.fullpath
 
  55     @oauth = current_user.access_token(OAUTH_KEY) if current_user && defined? OAUTH_KEY
 
  59   # require the user to have cookies enabled in their browser
 
  61     if request.cookies["_osm_session"].to_s == ""
 
  62       if params[:cookie_test].nil?
 
  63         session[:cookie_test] = true
 
  64         redirect_to params.to_unsafe_h.merge(:cookie_test => "true")
 
  67         flash.now[:warning] = t "application.require_cookies.cookies_needed"
 
  70       session.delete(:cookie_test)
 
  75   # sets up the current_user for use by other methods. this is mostly called
 
  76   # from the authorize method, but can be called elsewhere if authorisation
 
  79     # try and setup using OAuth
 
  80     unless Authenticator.new(self, [:token]).allow?
 
  81       username, passwd = get_auth_data # parse from headers
 
  82       # authenticate per-scheme
 
  83       self.current_user = if username.nil?
 
  84                             nil # no authentication provided - perhaps first connect (client should retry after 401)
 
  85                           elsif username == "token"
 
  86                             User.authenticate(:token => passwd) # preferred - random token for user from db, passed in basic auth
 
  88                             User.authenticate(:username => username, :password => passwd) # basic auth
 
  92     # have we identified the user?
 
  94       # check if the user has been banned
 
  95       user_block = current_user.blocks.active.take
 
  96       unless user_block.nil?
 
  98         if user_block.zero_hour?
 
  99           report_error t("application.setup_user_auth.blocked_zero_hour"), :forbidden
 
 101           report_error t("application.setup_user_auth.blocked"), :forbidden
 
 105       # if the user hasn't seen the contributor terms then don't
 
 106       # allow editing - they have to go to the web site and see
 
 107       # (but can decline) the CTs to continue.
 
 108       if REQUIRE_TERMS_SEEN && !current_user.terms_seen && flash[:skip_terms].nil?
 
 110         report_error t("application.setup_user_auth.need_to_see_terms"), :forbidden
 
 115   def authorize(realm = "Web Password", errormessage = "Couldn't authenticate you")
 
 116     # make the current_user object from any auth sources we have
 
 119     # handle authenticate pass/fail
 
 121       # no auth, the user does not exist or the password was wrong
 
 122       response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
 
 123       render :plain => errormessage, :status => :unauthorized
 
 128   def check_database_readable(need_api = false)
 
 129     if STATUS == :database_offline || (need_api && STATUS == :api_offline)
 
 131         report_error "Database offline for maintenance", :service_unavailable
 
 133         redirect_to :controller => "site", :action => "offline"
 
 138   def check_database_writable(need_api = false)
 
 139     if STATUS == :database_offline || STATUS == :database_readonly ||
 
 140        (need_api && (STATUS == :api_offline || STATUS == :api_readonly))
 
 142         report_error "Database offline for maintenance", :service_unavailable
 
 144         redirect_to :controller => "site", :action => "offline"
 
 149   def check_api_readable
 
 150     if api_status == :offline
 
 151       report_error "Database offline for maintenance", :service_unavailable
 
 156   def check_api_writable
 
 157     unless api_status == :online
 
 158       report_error "Database offline for maintenance", :service_unavailable
 
 164     if STATUS == :database_offline
 
 166     elsif STATUS == :database_readonly
 
 174     status = database_status
 
 176       if STATUS == :api_offline
 
 178       elsif STATUS == :api_readonly
 
 186     status = database_status
 
 187     status = :offline if status == :online && STATUS == :gpx_offline
 
 191   def require_public_data
 
 192     unless current_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"]&.casecmp("xml")&.zero?
 
 208       result = OSM::API.new.get_xml_doc
 
 209       result.root.name = "osmError"
 
 210       result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
 
 211       result.root << (XML::Node.new("message") << message)
 
 213       render :xml => result.to_s
 
 215       render :plain => message, :status => status
 
 219   def preferred_languages(reset = false)
 
 220     @preferred_languages = nil if reset
 
 221     @preferred_languages ||= if params[:locale]
 
 222                                Locale.list(params[:locale])
 
 224                                current_user.preferred_languages
 
 226                                Locale.list(http_accept_language.user_preferred_languages)
 
 230   helper_method :preferred_languages
 
 232   def set_locale(reset = false)
 
 233     if current_user&.languages&.empty? && !http_accept_language.user_preferred_languages.empty?
 
 234       current_user.languages = http_accept_language.user_preferred_languages
 
 238     I18n.locale = Locale.available.preferred(preferred_languages(reset))
 
 240     response.headers["Vary"] = "Accept-Language"
 
 241     response.headers["Content-Language"] = I18n.locale.to_s
 
 244   def api_call_handle_error
 
 246   rescue ActiveRecord::RecordNotFound => ex
 
 248   rescue LibXML::XML::Error, ArgumentError => ex
 
 249     report_error ex.message, :bad_request
 
 250   rescue ActiveRecord::RecordInvalid => ex
 
 251     message = "#{ex.record.class} #{ex.record.id}: "
 
 252     ex.record.errors.each { |attr, msg| message << "#{attr}: #{msg} (#{ex.record[attr].inspect})" }
 
 253     report_error message, :bad_request
 
 254   rescue OSM::APIError => ex
 
 255     report_error ex.message, ex.status
 
 256   rescue AbstractController::ActionNotFound => ex
 
 258   rescue StandardError => ex
 
 259     logger.info("API threw unexpected #{ex.class} exception: #{ex.message}")
 
 260     ex.backtrace.each { |l| logger.info(l) }
 
 261     report_error "#{ex.class}: #{ex.message}", :internal_server_error
 
 265   # asserts that the request method is the +method+ given as a parameter
 
 266   # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
 
 267   def assert_method(method)
 
 268     ok = request.send((method.to_s.downcase + "?").to_sym)
 
 269     raise OSM::APIBadMethodError, method unless ok
 
 273   # wrap an api call in a timeout
 
 275     OSM::Timer.timeout(API_TIMEOUT, Timeout::Error) do
 
 278   rescue Timeout::Error
 
 279     raise OSM::APITimeoutError
 
 283   # wrap a web page in a timeout
 
 285     OSM::Timer.timeout(WEB_TIMEOUT, Timeout::Error) do
 
 288   rescue ActionView::Template::Error => ex
 
 291     if ex.is_a?(Timeout::Error) ||
 
 292        (ex.is_a?(ActiveRecord::StatementInvalid) && ex.message =~ /execution expired/)
 
 293       render :action => "timeout"
 
 297   rescue Timeout::Error
 
 298     render :action => "timeout"
 
 302   # ensure that there is a "user" instance variable
 
 304     render_unknown_user params[:display_name] unless @user = User.active.find_by(:display_name => params[:display_name])
 
 308   # render a "no such user" page
 
 309   def render_unknown_user(name)
 
 310     @title = t "users.no_such_user.title"
 
 311     @not_found_user = name
 
 313     respond_to do |format|
 
 314       format.html { render :template => "users/no_such_user", :status => :not_found }
 
 315       format.all { head :not_found }
 
 320   # Unfortunately if a PUT or POST request that has a body fails to
 
 321   # read it then Apache will sometimes fail to return the response it
 
 322   # is given to the client properly, instead erroring:
 
 324   #   https://issues.apache.org/bugzilla/show_bug.cgi?id=44782
 
 326   # To work round this we call rewind on the body here, which is added
 
 327   # as a filter, to force it to be fetched from Apache into a file.
 
 333     append_content_security_policy_directives(
 
 334       :child_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
 
 335       :frame_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
 
 336       :connect_src => [NOMINATIM_URL, OVERPASS_URL, OSRM_URL, GRAPHHOPPER_URL],
 
 337       :form_action => %w[render.openstreetmap.org],
 
 338       :style_src => %w['unsafe-inline'],
 
 339       :script_src => [MAPQUEST_DIRECTIONS_URL],
 
 340       :img_src => %w[developer.mapquest.com]
 
 343     if STATUS == :database_offline || STATUS == :api_offline
 
 344       flash.now[:warning] = t("layouts.osm_offline")
 
 345     elsif STATUS == :database_readonly || STATUS == :api_readonly
 
 346       flash.now[:warning] = t("layouts.osm_read_only")
 
 349     request.xhr? ? "xhr" : "map"
 
 352   def allow_thirdparty_images
 
 353     append_content_security_policy_directives(:img_src => %w[*])
 
 357     editor = if params[:editor]
 
 359              elsif current_user&.preferred_editor
 
 360                current_user.preferred_editor
 
 368   helper_method :preferred_editor
 
 371     if defined?(TOTP_KEY)
 
 372       cookies["_osm_totp_token"] = {
 
 373         :value => ROTP::TOTP.new(TOTP_KEY, :interval => 3600).now,
 
 374         :domain => "openstreetmap.org",
 
 375         :expires => 1.hour.from_now
 
 380   def better_errors_allow_inline
 
 383     append_content_security_policy_directives(
 
 384       :script_src => %w['unsafe-inline'],
 
 385       :style_src => %w['unsafe-inline']
 
 392     # Use capabilities from the oauth token if it exists and is a valid access token
 
 393     if Authenticator.new(self, [:token]).allow?
 
 394       Ability.new(nil).merge(Capability.new(current_token))
 
 396       Ability.new(current_user)
 
 400   def deny_access(exception)
 
 401     if @api_deny_access_handling
 
 402       api_deny_access(exception)
 
 404       web_deny_access(exception)
 
 408   def web_deny_access(_exception)
 
 411       report_error t("oauth.permissions.missing"), :forbidden
 
 414       respond_to do |format|
 
 415         format.html { redirect_to :controller => "errors", :action => "forbidden" }
 
 416         format.any { report_error t("application.permission_denied"), :forbidden }
 
 419       respond_to do |format|
 
 420         format.html { redirect_to :controller => "users", :action => "login", :referer => request.fullpath }
 
 421         format.any { head :forbidden }
 
 428   def api_deny_access(_exception)
 
 431       report_error t("oauth.permissions.missing"), :forbidden
 
 435       realm = "Web Password"
 
 436       errormessage = "Couldn't authenticate you"
 
 437       response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
 
 438       render :plain => errormessage, :status => :unauthorized
 
 442   attr_accessor :api_access_handling
 
 444   def api_deny_access_handler
 
 445     @api_deny_access_handling = true
 
 450   # extract authorisation credentials from headers, returns user = nil if none
 
 452     if request.env.key? "X-HTTP_AUTHORIZATION" # where mod_rewrite might have put it
 
 453       authdata = request.env["X-HTTP_AUTHORIZATION"].to_s.split
 
 454     elsif request.env.key? "REDIRECT_X_HTTP_AUTHORIZATION" # mod_fcgi
 
 455       authdata = request.env["REDIRECT_X_HTTP_AUTHORIZATION"].to_s.split
 
 456     elsif request.env.key? "HTTP_AUTHORIZATION" # regular location
 
 457       authdata = request.env["HTTP_AUTHORIZATION"].to_s.split
 
 459     # only basic authentication supported
 
 460     user, pass = Base64.decode64(authdata[1]).split(":", 2) if authdata && authdata[0] == "Basic"
 
 464   # override to stop oauth plugin sending errors
 
 465   def invalid_oauth_response; end