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 before_action :fetch_body
14 around_action :better_errors_allow_inline, :if => proc { Rails.env.development? }
16 attr_accessor :current_user, :oauth_token
18 helper_method :current_user
19 helper_method :oauth_token
25 self.current_user = User.find_by(:id => session[:user], :status => %w[active confirmed suspended])
27 if session[:fingerprint] &&
28 session[:fingerprint] != current_user.fingerprint
30 self.current_user = nil
31 elsif current_user.status == "suspended"
33 session_expires_automatically
35 redirect_to :controller => "users", :action => "suspended"
37 # don't allow access to any auth-requiring part of the site unless
38 # the new CTs have been seen (and accept/decline chosen).
39 elsif !current_user.terms_seen && flash[:skip_terms].nil?
40 flash[:notice] = t "users.terms.you need to accept or decline"
42 redirect_to :controller => "users", :action => "terms", :referer => params[:referer]
44 redirect_to :controller => "users", :action => "terms", :referer => request.fullpath
49 session[:fingerprint] = current_user.fingerprint if current_user && session[:fingerprint].nil?
50 rescue StandardError => e
51 logger.info("Exception authorizing user: #{e}")
53 self.current_user = nil
59 redirect_to login_path(:referer => request.fullpath)
67 @oauth_token = current_user.oauth_token(Settings.oauth_application) if current_user && Settings.key?(:oauth_application)
70 def require_oauth_10a_support
71 report_error t("application.oauth_10a_disabled", :link => t("application.auth_disabled_link")), :forbidden unless Settings.oauth_10a_support
75 # require the user to have cookies enabled in their browser
77 if request.cookies["_osm_session"].to_s == ""
78 if params[:cookie_test].nil?
79 session[:cookie_test] = true
80 redirect_to params.to_unsafe_h.merge(:only_path => true, :cookie_test => "true")
83 flash.now[:warning] = t "application.require_cookies.cookies_needed"
86 session.delete(:cookie_test)
90 def check_database_readable(need_api: false)
91 if Settings.status == "database_offline" || (need_api && Settings.status == "api_offline")
93 report_error "Database offline for maintenance", :service_unavailable
95 redirect_to :controller => "site", :action => "offline"
100 def check_database_writable(need_api: false)
101 if Settings.status == "database_offline" || Settings.status == "database_readonly" ||
102 (need_api && (Settings.status == "api_offline" || Settings.status == "api_readonly"))
104 report_error "Database offline for maintenance", :service_unavailable
106 redirect_to :controller => "site", :action => "offline"
111 def check_api_readable
112 if api_status == "offline"
113 report_error "Database offline for maintenance", :service_unavailable
118 def check_api_writable
119 unless api_status == "online"
120 report_error "Database offline for maintenance", :service_unavailable
127 when "database_offline"
129 when "database_readonly"
137 status = database_status
138 if status == "online"
149 def require_public_data
150 unless current_user.data_public?
151 report_error "You must make your edits public to upload new data", :forbidden
156 # Report and error to the user
157 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
158 # rather than only a status code and having the web engine make up a
159 # phrase from that, we can also put the error message into the status
160 # message. For now, rails won't let us)
161 def report_error(message, status = :bad_request)
162 # TODO: some sort of escaping of problem characters in the message
163 response.headers["Error"] = message
165 if request.headers["X-Error-Format"]&.casecmp("xml")&.zero?
166 result = OSM::API.new.xml_doc
167 result.root.name = "osmError"
168 result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
169 result.root << (XML::Node.new("message") << message)
171 render :xml => result.to_s
173 render :plain => message, :status => status
177 def preferred_languages
178 @preferred_languages ||= if params[:locale]
179 Locale.list(params[:locale])
181 current_user.preferred_languages
183 Locale.list(http_accept_language.user_preferred_languages)
187 helper_method :preferred_languages
190 if current_user&.languages&.empty? && !http_accept_language.user_preferred_languages.empty?
191 current_user.languages = http_accept_language.user_preferred_languages
195 I18n.locale = Locale.available.preferred(preferred_languages)
197 response.headers["Vary"] = "Accept-Language"
198 response.headers["Content-Language"] = I18n.locale.to_s
202 # wrap a web page in a timeout
203 def web_timeout(&block)
204 Timeout.timeout(Settings.web_timeout, &block)
205 rescue ActionView::Template::Error => e
208 if e.is_a?(Timeout::Error) ||
209 (e.is_a?(ActiveRecord::StatementInvalid) && e.message.include?("execution expired"))
210 ActiveRecord::Base.connection.raw_connection.cancel
211 render :action => "timeout"
215 rescue Timeout::Error
216 ActiveRecord::Base.connection.raw_connection.cancel
217 render :action => "timeout"
221 # Unfortunately if a PUT or POST request that has a body fails to
222 # read it then Apache will sometimes fail to return the response it
223 # is given to the client properly, instead erroring:
225 # https://issues.apache.org/bugzilla/show_bug.cgi?id=44782
227 # To work round this we call rewind on the body here, which is added
228 # as a filter, to force it to be fetched from Apache into a file.
234 append_content_security_policy_directives(
235 :child_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
236 :frame_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
237 :connect_src => [Settings.nominatim_url, Settings.overpass_url, Settings.fossgis_osrm_url, Settings.graphhopper_url, Settings.fossgis_valhalla_url],
238 :form_action => %w[render.openstreetmap.org],
239 :style_src => %w['unsafe-inline']
243 when "database_offline", "api_offline"
244 flash.now[:warning] = t("layouts.osm_offline")
245 when "database_readonly", "api_readonly"
246 flash.now[:warning] = t("layouts.osm_read_only")
249 request.xhr? ? "xhr" : "map"
252 def allow_thirdparty_images
253 append_content_security_policy_directives(:img_src => %w[*])
259 elsif current_user&.preferred_editor
260 current_user.preferred_editor
262 Settings.default_editor
266 helper_method :preferred_editor
269 if Settings.key?(:totp_key)
270 cookies["_osm_totp_token"] = {
271 :value => ROTP::TOTP.new(Settings.totp_key, :interval => 3600).now,
272 :domain => "openstreetmap.org",
273 :expires => 1.hour.from_now
278 def better_errors_allow_inline
281 append_content_security_policy_directives(
282 :script_src => %w['unsafe-inline'],
283 :style_src => %w['unsafe-inline']
290 Ability.new(current_user)
293 def deny_access(_exception)
294 if doorkeeper_token || current_token
296 report_error t("oauth.permissions.missing"), :forbidden
299 respond_to do |format|
300 format.html { redirect_to :controller => "/errors", :action => "forbidden" }
301 format.any { report_error t("application.permission_denied"), :forbidden }
304 respond_to do |format|
305 format.html { redirect_to login_path(:referer => request.fullpath) }
306 format.any { head :forbidden }
313 # extract authorisation credentials from headers, returns user = nil if none
315 if request.env.key? "X-HTTP_AUTHORIZATION" # where mod_rewrite might have put it
316 authdata = request.env["X-HTTP_AUTHORIZATION"].to_s.split
317 elsif request.env.key? "REDIRECT_X_HTTP_AUTHORIZATION" # mod_fcgi
318 authdata = request.env["REDIRECT_X_HTTP_AUTHORIZATION"].to_s.split
319 elsif request.env.key? "HTTP_AUTHORIZATION" # regular location
320 authdata = request.env["HTTP_AUTHORIZATION"].to_s.split
322 # only basic authentication supported
323 user, pass = Base64.decode64(authdata[1]).split(":", 2) if authdata && authdata[0] == "Basic"
327 # override to stop oauth plugin sending errors
328 def invalid_oauth_response; end
330 # clean any referer parameter
331 def safe_referer(referer)
333 referer = URI.parse(referer)
335 if referer.scheme == "http" || referer.scheme == "https"
339 elsif referer.scheme || referer.host || referer.port
343 referer = nil if referer&.path&.first != "/"
344 rescue URI::InvalidURIError
351 def scope_enabled?(scope)
352 doorkeeper_token&.includes_scope?(scope) || current_token&.includes_scope?(scope)
355 helper_method :scope_enabled?