1 class ApplicationController < ActionController::Base
 
   4   include SessionPersistence
 
   6   protect_from_forgery :with => :exception
 
   8   add_flash_types :warning, :error
 
  10   rescue_from CanCan::AccessDenied, :with => :deny_access
 
  13   rescue_from RailsParam::InvalidParameterError, :with => :invalid_parameter
 
  15   after_action :close_body
 
  17   attr_accessor :current_user, :oauth_token
 
  19   helper_method :current_user
 
  20   helper_method :oauth_token
 
  22   def self.allow_thirdparty_images(**options)
 
  23     content_security_policy(**options) do |policy|
 
  24       policy.img_src("*", :data)
 
  28   def self.allow_social_login(**options)
 
  29     content_security_policy(options) do |policy|
 
  30       policy.form_action(*policy.form_action, "accounts.google.com", "*.facebook.com", "login.microsoftonline.com", "github.com", "meta.wikimedia.org")
 
  34   def self.allow_all_form_action(**options)
 
  35     content_security_policy(options) do |policy|
 
  36       policy.form_action(nil)
 
  42   def authorize_web(skip_terms: false)
 
  44       self.current_user = User.find_by(:id => session[:user], :status => %w[active confirmed suspended])
 
  46       if session[:fingerprint] &&
 
  47          session[:fingerprint] != current_user.fingerprint
 
  49         self.current_user = nil
 
  50       elsif current_user.status == "suspended"
 
  52         session_expires_automatically
 
  54         redirect_to :controller => "users", :action => "suspended"
 
  56       # don't allow access to any auth-requiring part of the site unless
 
  57       # the new CTs have been seen (and accept/decline chosen).
 
  58       elsif !current_user.terms_seen && !skip_terms
 
  59         flash[:notice] = t "accounts.terms.show.you need to accept or decline"
 
  61           redirect_to account_terms_path(:referer => params[:referer])
 
  63           redirect_to account_terms_path(:referer => request.fullpath)
 
  68     session[:fingerprint] = current_user.fingerprint if current_user && session[:fingerprint].nil?
 
  69   rescue StandardError => e
 
  70     logger.info("Exception authorizing user: #{e}")
 
  72     self.current_user = nil
 
  78         redirect_to login_path(:referer => request.fullpath)
 
  86     @oauth_token = current_user.oauth_token(Settings.oauth_application) if current_user && Settings.key?(:oauth_application)
 
  90   # require the user to have cookies enabled in their browser
 
  92     if request.cookies["_osm_session"].to_s == ""
 
  93       if params[:cookie_test].nil?
 
  94         session[:cookie_test] = true
 
  95         redirect_to params.to_unsafe_h.merge(:only_path => true, :cookie_test => "true")
 
  98         flash.now[:warning] = t "application.require_cookies.cookies_needed"
 
 101       session.delete(:cookie_test)
 
 105   def check_database_readable(need_api: false)
 
 106     if Settings.status == "database_offline" || (need_api && Settings.status == "api_offline")
 
 108         report_error "Database offline for maintenance", :service_unavailable
 
 110         redirect_to :controller => "site", :action => "offline"
 
 115   def check_database_writable(need_api: false)
 
 116     if Settings.status == "database_offline" || Settings.status == "database_readonly" ||
 
 117        (need_api && %w[api_offline api_readonly].include?(Settings.status))
 
 119         report_error "Database offline for maintenance", :service_unavailable
 
 121         redirect_to :controller => "site", :action => "offline"
 
 126   def check_api_readable
 
 127     report_error "Database offline for maintenance", :service_unavailable if api_status == "offline"
 
 130   def check_api_writable
 
 131     report_error "Database offline for maintenance", :service_unavailable unless api_status == "online"
 
 136     when "database_offline"
 
 138     when "database_readonly"
 
 146     status = database_status
 
 147     if status == "online"
 
 158   def require_public_data
 
 159     report_error "You must make your edits public to upload new data", :forbidden unless current_user.data_public?
 
 162   # Report and error to the user
 
 163   # (If anyone ever fixes Rails so it can set a http status "reason phrase",
 
 164   #  rather than only a status code and having the web engine make up a
 
 165   #  phrase from that, we can also put the error message into the status
 
 166   #  message. For now, rails won't let us)
 
 167   def report_error(message, status = :bad_request)
 
 168     # TODO: some sort of escaping of problem characters in the message
 
 169     response.headers["Error"] = message
 
 171     if request.headers["X-Error-Format"]&.casecmp?("xml")
 
 172       result = OSM::API.new.xml_doc
 
 173       result.root.name = "osmError"
 
 174       result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
 
 175       result.root << (XML::Node.new("message") << message)
 
 177       render :xml => result.to_s
 
 179       render :plain => message, :status => status
 
 183   def preferred_languages
 
 184     @preferred_languages ||= if params[:locale]
 
 185                                Locale.list(params[:locale])
 
 187                                current_user.preferred_languages
 
 188                              elsif request.cookies["_osm_locale"]
 
 189                                Locale.list(request.cookies["_osm_locale"])
 
 191                                Locale.list(http_accept_language.user_preferred_languages)
 
 195   helper_method :preferred_languages
 
 198     if current_user&.languages&.empty? && !http_accept_language.user_preferred_languages.empty?
 
 199       current_user.languages = http_accept_language.user_preferred_languages
 
 203     I18n.locale = Locale.available.preferred(preferred_languages)
 
 205     response.headers["Vary"] = "Accept-Language"
 
 206     response.headers["Content-Language"] = I18n.locale.to_s
 
 210   # wrap a web page in a timeout
 
 212     raise Timeout::Error if Settings.web_timeout.negative?
 
 214     Timeout.timeout(Settings.web_timeout, &)
 
 215   rescue ActionView::Template::Error => e
 
 218     if e.is_a?(Timeout::Error) ||
 
 219        (e.is_a?(ActiveRecord::StatementInvalid) && e.message.include?("execution expired"))
 
 224   rescue Timeout::Error
 
 228   def respond_to_timeout
 
 229     ActiveRecord::Base.connection.raw_connection.cancel
 
 230     render :action => "timeout", :status => :gateway_timeout
 
 234   # Unfortunately if a PUT or POST request that has a body fails to
 
 235   # read it then Apache will sometimes fail to return the response it
 
 236   # is given to the client properly, instead erroring:
 
 238   #   https://issues.apache.org/bugzilla/show_bug.cgi?id=44782
 
 240   # To work round this we call close on the body here, which is added
 
 241   # as a filter, to let Apache know we are done with it.
 
 247     policy = request.content_security_policy.clone
 
 249     policy.connect_src(*policy.connect_src, "http://127.0.0.1:8111", Settings.nominatim_url, Settings.overpass_url, Settings.fossgis_osrm_url, Settings.graphhopper_url, Settings.fossgis_valhalla_url)
 
 250     policy.form_action(*policy.form_action, "render.openstreetmap.org")
 
 251     policy.style_src(*policy.style_src, :unsafe_inline)
 
 253     request.content_security_policy = policy
 
 255     flash.now[:warning] = { :partial => "layouts/offline_flash" } unless api_status == "online"
 
 257     request.xhr? ? "xhr" : "map"
 
 263     elsif current_user&.preferred_editor
 
 264       current_user.preferred_editor
 
 266       Settings.default_editor
 
 270   def preferred_color_scheme(subject)
 
 272       current_user.preferences.find_by(:k => "#{subject}.color_scheme")&.v || "auto"
 
 278   helper_method :preferred_editor, :preferred_color_scheme
 
 281     if Settings.key?(:totp_key)
 
 282       cookies["_osm_totp_token"] = {
 
 283         :value => ROTP::TOTP.new(Settings.totp_key, :interval => 3600).now,
 
 284         :domain => "openstreetmap.org",
 
 285         :expires => 1.hour.from_now
 
 291     Ability.new(current_user)
 
 294   def deny_access(_exception)
 
 297       respond_to do |format|
 
 298         format.html { redirect_to :controller => "/errors", :action => "forbidden" }
 
 299         format.any { report_error t("application.permission_denied"), :forbidden }
 
 302       respond_to do |format|
 
 303         format.html { redirect_to login_path(:referer => request.fullpath) }
 
 304         format.any { head :forbidden }
 
 311   def invalid_parameter(_exception)
 
 313       respond_to do |format|
 
 314         format.html { redirect_to :controller => "/errors", :action => "bad_request" }
 
 315         format.any { head :bad_request }
 
 322   # clean any referer parameter
 
 323   def safe_referer(referer)
 
 325       referer = URI.parse(referer)
 
 327       if %w[http https].include?(referer.scheme)
 
 331       elsif referer.scheme || referer.host || referer.port
 
 335       referer = nil if referer&.path&.first != "/"
 
 336     rescue URI::InvalidURIError