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)
71 # require the user to have cookies enabled in their browser
73 if request.cookies["_osm_session"].to_s == ""
74 if params[:cookie_test].nil?
75 session[:cookie_test] = true
76 redirect_to params.to_unsafe_h.merge(:only_path => true, :cookie_test => "true")
79 flash.now[:warning] = t "application.require_cookies.cookies_needed"
82 session.delete(:cookie_test)
86 def check_database_readable(need_api: false)
87 if Settings.status == "database_offline" || (need_api && Settings.status == "api_offline")
89 report_error "Database offline for maintenance", :service_unavailable
91 redirect_to :controller => "site", :action => "offline"
96 def check_database_writable(need_api: false)
97 if Settings.status == "database_offline" || Settings.status == "database_readonly" ||
98 (need_api && (Settings.status == "api_offline" || Settings.status == "api_readonly"))
100 report_error "Database offline for maintenance", :service_unavailable
102 redirect_to :controller => "site", :action => "offline"
107 def check_api_readable
108 if api_status == "offline"
109 report_error "Database offline for maintenance", :service_unavailable
114 def check_api_writable
115 unless api_status == "online"
116 report_error "Database offline for maintenance", :service_unavailable
123 when "database_offline"
125 when "database_readonly"
133 status = database_status
134 if status == "online"
145 def require_public_data
146 unless current_user.data_public?
147 report_error "You must make your edits public to upload new data", :forbidden
152 # Report and error to the user
153 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
154 # rather than only a status code and having the web engine make up a
155 # phrase from that, we can also put the error message into the status
156 # message. For now, rails won't let us)
157 def report_error(message, status = :bad_request)
158 # TODO: some sort of escaping of problem characters in the message
159 response.headers["Error"] = message
161 if request.headers["X-Error-Format"]&.casecmp("xml")&.zero?
162 result = OSM::API.new.xml_doc
163 result.root.name = "osmError"
164 result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
165 result.root << (XML::Node.new("message") << message)
167 render :xml => result.to_s
169 render :plain => message, :status => status
173 def preferred_languages
174 @preferred_languages ||= if params[:locale]
175 Locale.list(params[:locale])
177 current_user.preferred_languages
179 Locale.list(http_accept_language.user_preferred_languages)
183 helper_method :preferred_languages
186 if current_user&.languages&.empty? && !http_accept_language.user_preferred_languages.empty?
187 current_user.languages = http_accept_language.user_preferred_languages
191 I18n.locale = Locale.available.preferred(preferred_languages)
193 response.headers["Vary"] = "Accept-Language"
194 response.headers["Content-Language"] = I18n.locale.to_s
198 # wrap a web page in a timeout
199 def web_timeout(&block)
200 Timeout.timeout(Settings.web_timeout, &block)
201 rescue ActionView::Template::Error => e
204 if e.is_a?(Timeout::Error) ||
205 (e.is_a?(ActiveRecord::StatementInvalid) && e.message.include?("execution expired"))
206 ActiveRecord::Base.connection.raw_connection.cancel
207 render :action => "timeout"
211 rescue Timeout::Error
212 ActiveRecord::Base.connection.raw_connection.cancel
213 render :action => "timeout"
217 # Unfortunately if a PUT or POST request that has a body fails to
218 # read it then Apache will sometimes fail to return the response it
219 # is given to the client properly, instead erroring:
221 # https://issues.apache.org/bugzilla/show_bug.cgi?id=44782
223 # To work round this we call rewind on the body here, which is added
224 # as a filter, to force it to be fetched from Apache into a file.
230 append_content_security_policy_directives(
231 :child_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
232 :frame_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
233 :connect_src => [Settings.nominatim_url, Settings.overpass_url, Settings.fossgis_osrm_url, Settings.graphhopper_url, Settings.fossgis_valhalla_url],
234 :form_action => %w[render.openstreetmap.org],
235 :style_src => %w['unsafe-inline']
239 when "database_offline", "api_offline"
240 flash.now[:warning] = t("layouts.osm_offline")
241 when "database_readonly", "api_readonly"
242 flash.now[:warning] = t("layouts.osm_read_only")
245 request.xhr? ? "xhr" : "map"
248 def allow_thirdparty_images
249 append_content_security_policy_directives(:img_src => %w[*])
255 elsif current_user&.preferred_editor
256 current_user.preferred_editor
258 Settings.default_editor
262 helper_method :preferred_editor
265 if Settings.key?(:totp_key)
266 cookies["_osm_totp_token"] = {
267 :value => ROTP::TOTP.new(Settings.totp_key, :interval => 3600).now,
268 :domain => "openstreetmap.org",
269 :expires => 1.hour.from_now
274 def better_errors_allow_inline
277 append_content_security_policy_directives(
278 :script_src => %w['unsafe-inline'],
279 :style_src => %w['unsafe-inline']
286 Ability.new(current_user)
289 def deny_access(_exception)
290 if doorkeeper_token || current_token
292 report_error t("oauth.permissions.missing"), :forbidden
295 respond_to do |format|
296 format.html { redirect_to :controller => "/errors", :action => "forbidden" }
297 format.any { report_error t("application.permission_denied"), :forbidden }
300 respond_to do |format|
301 format.html { redirect_to login_path(:referer => request.fullpath) }
302 format.any { head :forbidden }
309 # extract authorisation credentials from headers, returns user = nil if none
311 if request.env.key? "X-HTTP_AUTHORIZATION" # where mod_rewrite might have put it
312 authdata = request.env["X-HTTP_AUTHORIZATION"].to_s.split
313 elsif request.env.key? "REDIRECT_X_HTTP_AUTHORIZATION" # mod_fcgi
314 authdata = request.env["REDIRECT_X_HTTP_AUTHORIZATION"].to_s.split
315 elsif request.env.key? "HTTP_AUTHORIZATION" # regular location
316 authdata = request.env["HTTP_AUTHORIZATION"].to_s.split
318 # only basic authentication supported
319 user, pass = Base64.decode64(authdata[1]).split(":", 2) if authdata && authdata[0] == "Basic"
323 # override to stop oauth plugin sending errors
324 def invalid_oauth_response; end
326 # clean any referer parameter
327 def safe_referer(referer)
329 referer = URI.parse(referer)
331 if referer.scheme == "http" || referer.scheme == "https"
335 elsif referer.scheme || referer.host || referer.port
339 referer = nil if referer&.path&.first != "/"
340 rescue URI::InvalidURIError
347 def scope_enabled?(scope)
348 doorkeeper_token&.includes_scope?(scope) || current_token&.includes_scope?(scope)
351 helper_method :scope_enabled?