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|
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
218 def web_timeout(&block)
219 raise Timeout::Error if Settings.web_timeout.negative?
221 Timeout.timeout(Settings.web_timeout, &block)
222 rescue ActionView::Template::Error => e
225 if e.is_a?(Timeout::Error) ||
226 (e.is_a?(ActiveRecord::StatementInvalid) && e.message.include?("execution expired"))
227 ActiveRecord::Base.connection.raw_connection.cancel
228 render :action => "timeout"
232 rescue Timeout::Error
233 ActiveRecord::Base.connection.raw_connection.cancel
234 render :action => "timeout"
238 # Unfortunately if a PUT or POST request that has a body fails to
239 # read it then Apache will sometimes fail to return the response it
240 # is given to the client properly, instead erroring:
242 # https://issues.apache.org/bugzilla/show_bug.cgi?id=44782
244 # To work round this we call rewind on the body here, which is added
245 # as a filter, to force it to be fetched from Apache into a file.
251 policy = request.content_security_policy.clone
253 policy.child_src(*policy.child_src, "http://127.0.0.1:8111", "https://127.0.0.1:8112")
254 policy.frame_src(*policy.frame_src, "http://127.0.0.1:8111", "https://127.0.0.1:8112")
255 policy.connect_src(*policy.connect_src, Settings.nominatim_url, Settings.overpass_url, Settings.fossgis_osrm_url, Settings.graphhopper_url, Settings.fossgis_valhalla_url)
256 policy.form_action(*policy.form_action, "render.openstreetmap.org")
257 policy.style_src(*policy.style_src, :unsafe_inline)
259 request.content_security_policy = policy
262 when "database_offline", "api_offline"
263 flash.now[:warning] = t("layouts.osm_offline")
264 when "database_readonly", "api_readonly"
265 flash.now[:warning] = t("layouts.osm_read_only")
268 request.xhr? ? "xhr" : "map"
274 elsif current_user&.preferred_editor
275 current_user.preferred_editor
277 Settings.default_editor
281 helper_method :preferred_editor
284 if Settings.key?(:totp_key)
285 cookies["_osm_totp_token"] = {
286 :value => ROTP::TOTP.new(Settings.totp_key, :interval => 3600).now,
287 :domain => "openstreetmap.org",
288 :expires => 1.hour.from_now
294 Ability.new(current_user)
297 def deny_access(_exception)
300 report_error t("oauth.permissions.missing"), :forbidden
303 respond_to do |format|
304 format.html { redirect_to :controller => "/errors", :action => "forbidden" }
305 format.any { report_error t("application.permission_denied"), :forbidden }
308 respond_to do |format|
309 format.html { redirect_to login_path(:referer => request.fullpath) }
310 format.any { head :forbidden }
317 def invalid_parameter(_exception)
319 respond_to do |format|
320 format.html { redirect_to :controller => "/errors", :action => "bad_request" }
321 format.any { head :bad_request }
328 # clean any referer parameter
329 def safe_referer(referer)
331 referer = URI.parse(referer)
333 if referer.scheme == "http" || referer.scheme == "https"
337 elsif referer.scheme || referer.host || referer.port
341 referer = nil if referer&.path&.first != "/"
342 rescue URI::InvalidURIError
349 def scope_enabled?(scope)
350 doorkeeper_token&.includes_scope?(scope)
353 helper_method :scope_enabled?