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 before_action :fetch_body
16 around_action :better_errors_allow_inline, :if => proc { Rails.env.development? }
18 attr_accessor :current_user, :oauth_token
20 helper_method :current_user
21 helper_method :oauth_token
27 self.current_user = User.find_by(:id => session[:user], :status => %w[active confirmed suspended])
29 if session[:fingerprint] &&
30 session[:fingerprint] != current_user.fingerprint
32 self.current_user = nil
33 elsif current_user.status == "suspended"
35 session_expires_automatically
37 redirect_to :controller => "users", :action => "suspended"
39 # don't allow access to any auth-requiring part of the site unless
40 # the new CTs have been seen (and accept/decline chosen).
41 elsif !current_user.terms_seen && flash[:skip_terms].nil?
42 flash[:notice] = t "users.terms.you need to accept or decline"
44 redirect_to :controller => "users", :action => "terms", :referer => params[:referer]
46 redirect_to :controller => "users", :action => "terms", :referer => request.fullpath
51 session[:fingerprint] = current_user.fingerprint if current_user && session[:fingerprint].nil?
52 rescue StandardError => e
53 logger.info("Exception authorizing user: #{e}")
55 self.current_user = nil
61 redirect_to login_path(:referer => request.fullpath)
69 @oauth_token = current_user.oauth_token(Settings.oauth_application) if current_user && Settings.key?(:oauth_application)
72 def require_oauth_10a_support
73 report_error t("application.oauth_10a_disabled", :link => t("application.auth_disabled_link")), :forbidden unless Settings.oauth_10a_support
77 # require the user to have cookies enabled in their browser
79 if request.cookies["_osm_session"].to_s == ""
80 if params[:cookie_test].nil?
81 session[:cookie_test] = true
82 redirect_to params.to_unsafe_h.merge(:only_path => true, :cookie_test => "true")
85 flash.now[:warning] = t "application.require_cookies.cookies_needed"
88 session.delete(:cookie_test)
92 def check_database_readable(need_api: false)
93 if Settings.status == "database_offline" || (need_api && Settings.status == "api_offline")
95 report_error "Database offline for maintenance", :service_unavailable
97 redirect_to :controller => "site", :action => "offline"
102 def check_database_writable(need_api: false)
103 if Settings.status == "database_offline" || Settings.status == "database_readonly" ||
104 (need_api && (Settings.status == "api_offline" || Settings.status == "api_readonly"))
106 report_error "Database offline for maintenance", :service_unavailable
108 redirect_to :controller => "site", :action => "offline"
113 def check_api_readable
114 if api_status == "offline"
115 report_error "Database offline for maintenance", :service_unavailable
120 def check_api_writable
121 unless api_status == "online"
122 report_error "Database offline for maintenance", :service_unavailable
129 when "database_offline"
131 when "database_readonly"
139 status = database_status
140 if status == "online"
151 def require_public_data
152 unless current_user.data_public?
153 report_error "You must make your edits public to upload new data", :forbidden
158 # Report and error to the user
159 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
160 # rather than only a status code and having the web engine make up a
161 # phrase from that, we can also put the error message into the status
162 # message. For now, rails won't let us)
163 def report_error(message, status = :bad_request)
164 # TODO: some sort of escaping of problem characters in the message
165 response.headers["Error"] = message
167 if request.headers["X-Error-Format"]&.casecmp("xml")&.zero?
168 result = OSM::API.new.xml_doc
169 result.root.name = "osmError"
170 result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
171 result.root << (XML::Node.new("message") << message)
173 render :xml => result.to_s
175 render :plain => message, :status => status
179 def preferred_languages
180 @preferred_languages ||= if params[:locale]
181 Locale.list(params[:locale])
183 current_user.preferred_languages
185 Locale.list(http_accept_language.user_preferred_languages)
189 helper_method :preferred_languages
192 if current_user&.languages&.empty? && !http_accept_language.user_preferred_languages.empty?
193 current_user.languages = http_accept_language.user_preferred_languages
197 I18n.locale = Locale.available.preferred(preferred_languages)
199 response.headers["Vary"] = "Accept-Language"
200 response.headers["Content-Language"] = I18n.locale.to_s
204 # wrap a web page in a timeout
205 def web_timeout(&block)
206 Timeout.timeout(Settings.web_timeout, &block)
207 rescue ActionView::Template::Error => e
210 if e.is_a?(Timeout::Error) ||
211 (e.is_a?(ActiveRecord::StatementInvalid) && e.message.include?("execution expired"))
212 ActiveRecord::Base.connection.raw_connection.cancel
213 render :action => "timeout"
217 rescue Timeout::Error
218 ActiveRecord::Base.connection.raw_connection.cancel
219 render :action => "timeout"
223 # Unfortunately if a PUT or POST request that has a body fails to
224 # read it then Apache will sometimes fail to return the response it
225 # is given to the client properly, instead erroring:
227 # https://issues.apache.org/bugzilla/show_bug.cgi?id=44782
229 # To work round this we call rewind on the body here, which is added
230 # as a filter, to force it to be fetched from Apache into a file.
236 append_content_security_policy_directives(
237 :child_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
238 :frame_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
239 :connect_src => [Settings.nominatim_url, Settings.overpass_url, Settings.fossgis_osrm_url, Settings.graphhopper_url, Settings.fossgis_valhalla_url],
240 :form_action => %w[render.openstreetmap.org],
241 :style_src => %w['unsafe-inline']
245 when "database_offline", "api_offline"
246 flash.now[:warning] = t("layouts.osm_offline")
247 when "database_readonly", "api_readonly"
248 flash.now[:warning] = t("layouts.osm_read_only")
251 request.xhr? ? "xhr" : "map"
254 def allow_thirdparty_images
255 append_content_security_policy_directives(:img_src => %w[*])
261 elsif current_user&.preferred_editor
262 current_user.preferred_editor
264 Settings.default_editor
268 helper_method :preferred_editor
271 if Settings.key?(:totp_key)
272 cookies["_osm_totp_token"] = {
273 :value => ROTP::TOTP.new(Settings.totp_key, :interval => 3600).now,
274 :domain => "openstreetmap.org",
275 :expires => 1.hour.from_now
280 def better_errors_allow_inline
283 append_content_security_policy_directives(
284 :script_src => %w['unsafe-inline'],
285 :style_src => %w['unsafe-inline']
292 Ability.new(current_user)
295 def deny_access(_exception)
296 if doorkeeper_token || current_token
298 report_error t("oauth.permissions.missing"), :forbidden
301 respond_to do |format|
302 format.html { redirect_to :controller => "/errors", :action => "forbidden" }
303 format.any { report_error t("application.permission_denied"), :forbidden }
306 respond_to do |format|
307 format.html { redirect_to login_path(:referer => request.fullpath) }
308 format.any { head :forbidden }
315 def invalid_parameter(_exception)
317 respond_to do |format|
318 format.html { redirect_to :controller => "/errors", :action => "bad_request" }
319 format.any { head :bad_request }
326 # extract authorisation credentials from headers, returns user = nil if none
328 if request.env.key? "X-HTTP_AUTHORIZATION" # where mod_rewrite might have put it
329 authdata = request.env["X-HTTP_AUTHORIZATION"].to_s.split
330 elsif request.env.key? "REDIRECT_X_HTTP_AUTHORIZATION" # mod_fcgi
331 authdata = request.env["REDIRECT_X_HTTP_AUTHORIZATION"].to_s.split
332 elsif request.env.key? "HTTP_AUTHORIZATION" # regular location
333 authdata = request.env["HTTP_AUTHORIZATION"].to_s.split
335 # only basic authentication supported
336 user, pass = Base64.decode64(authdata[1]).split(":", 2) if authdata && authdata[0] == "Basic"
340 # override to stop oauth plugin sending errors
341 def invalid_oauth_response; end
343 # clean any referer parameter
344 def safe_referer(referer)
346 referer = URI.parse(referer)
348 if referer.scheme == "http" || referer.scheme == "https"
352 elsif referer.scheme || referer.host || referer.port
356 referer = nil if referer&.path&.first != "/"
357 rescue URI::InvalidURIError
364 def scope_enabled?(scope)
365 doorkeeper_token&.includes_scope?(scope) || current_token&.includes_scope?(scope)
368 helper_method :scope_enabled?