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
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)
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 && flash[:skip_terms].nil?
59 flash[:notice] = t "users.terms.you need to accept or decline"
61 redirect_to :controller => "users", :action => "terms", :referer => params[:referer]
63 redirect_to :controller => "users", :action => "terms", :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 && (Settings.status == "api_offline" || Settings.status == "api_readonly"))
119 report_error "Database offline for maintenance", :service_unavailable
121 redirect_to :controller => "site", :action => "offline"
126 def check_api_readable
127 if api_status == "offline"
128 report_error "Database offline for maintenance", :service_unavailable
133 def check_api_writable
134 unless api_status == "online"
135 report_error "Database offline for maintenance", :service_unavailable
142 when "database_offline"
144 when "database_readonly"
152 status = database_status
153 if status == "online"
164 def require_public_data
165 unless current_user.data_public?
166 report_error "You must make your edits public to upload new data", :forbidden
171 # Report and error to the user
172 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
173 # rather than only a status code and having the web engine make up a
174 # phrase from that, we can also put the error message into the status
175 # message. For now, rails won't let us)
176 def report_error(message, status = :bad_request)
177 # TODO: some sort of escaping of problem characters in the message
178 response.headers["Error"] = message
180 if request.headers["X-Error-Format"]&.casecmp?("xml")
181 result = OSM::API.new.xml_doc
182 result.root.name = "osmError"
183 result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
184 result.root << (XML::Node.new("message") << message)
186 render :xml => result.to_s
188 render :plain => message, :status => status
192 def preferred_languages
193 @preferred_languages ||= if params[:locale]
194 Locale.list(params[:locale])
196 current_user.preferred_languages
198 Locale.list(http_accept_language.user_preferred_languages)
202 helper_method :preferred_languages
205 if current_user&.languages&.empty? && !http_accept_language.user_preferred_languages.empty?
206 current_user.languages = http_accept_language.user_preferred_languages
210 I18n.locale = Locale.available.preferred(preferred_languages)
212 response.headers["Vary"] = "Accept-Language"
213 response.headers["Content-Language"] = I18n.locale.to_s
217 # wrap a web page in a timeout
219 raise Timeout::Error if Settings.web_timeout.negative?
221 Timeout.timeout(Settings.web_timeout, &)
222 rescue ActionView::Template::Error => e
225 if e.is_a?(Timeout::Error) ||
226 (e.is_a?(ActiveRecord::StatementInvalid) && e.message.include?("execution expired"))
231 rescue Timeout::Error
235 def respond_to_timeout
236 ActiveRecord::Base.connection.raw_connection.cancel
237 render :action => "timeout", :status => :gateway_timeout
241 # Unfortunately if a PUT or POST request that has a body fails to
242 # read it then Apache will sometimes fail to return the response it
243 # is given to the client properly, instead erroring:
245 # https://issues.apache.org/bugzilla/show_bug.cgi?id=44782
247 # To work round this we call rewind on the body here, which is added
248 # as a filter, to force it to be fetched from Apache into a file.
254 policy = request.content_security_policy.clone
256 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)
257 policy.form_action(*policy.form_action, "render.openstreetmap.org")
258 policy.style_src(*policy.style_src, :unsafe_inline)
260 request.content_security_policy = policy
263 when "database_offline", "api_offline"
264 flash.now[:warning] = t("layouts.osm_offline")
265 when "database_readonly", "api_readonly"
266 flash.now[:warning] = t("layouts.osm_read_only")
269 request.xhr? ? "xhr" : "map"
275 elsif current_user&.preferred_editor
276 current_user.preferred_editor
278 Settings.default_editor
282 def preferred_color_scheme(subject)
284 current_user.preferences.find_by(:k => "#{subject}.color_scheme")&.v || "auto"
290 helper_method :preferred_editor, :preferred_color_scheme
293 if Settings.key?(:totp_key)
294 cookies["_osm_totp_token"] = {
295 :value => ROTP::TOTP.new(Settings.totp_key, :interval => 3600).now,
296 :domain => "openstreetmap.org",
297 :expires => 1.hour.from_now
303 Ability.new(current_user)
306 def deny_access(_exception)
309 report_error t("oauth.permissions.missing"), :forbidden
312 respond_to do |format|
313 format.html { redirect_to :controller => "/errors", :action => "forbidden" }
314 format.any { report_error t("application.permission_denied"), :forbidden }
317 respond_to do |format|
318 format.html { redirect_to login_path(:referer => request.fullpath) }
319 format.any { head :forbidden }
326 def invalid_parameter(_exception)
328 respond_to do |format|
329 format.html { redirect_to :controller => "/errors", :action => "bad_request" }
330 format.any { head :bad_request }
337 # clean any referer parameter
338 def safe_referer(referer)
340 referer = URI.parse(referer)
342 if referer.scheme == "http" || referer.scheme == "https"
346 elsif referer.scheme || referer.host || referer.port
350 referer = nil if referer&.path&.first != "/"
351 rescue URI::InvalidURIError
358 def scope_enabled?(scope)
359 doorkeeper_token&.includes_scope?(scope)
362 helper_method :scope_enabled?