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.where(:id => session[:user], :status => %w[active confirmed suspended]).first
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
48 session[:user] = current_user.id if self.current_user = User.authenticate(:token => session[:token])
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)
73 # require the user to have cookies enabled in their browser
75 if request.cookies["_osm_session"].to_s == ""
76 if params[:cookie_test].nil?
77 session[:cookie_test] = true
78 redirect_to params.to_unsafe_h.merge(:only_path => true, :cookie_test => "true")
81 flash.now[:warning] = t "application.require_cookies.cookies_needed"
84 session.delete(:cookie_test)
88 def check_database_readable(need_api: false)
89 if Settings.status == "database_offline" || (need_api && Settings.status == "api_offline")
91 report_error "Database offline for maintenance", :service_unavailable
93 redirect_to :controller => "site", :action => "offline"
98 def check_database_writable(need_api: false)
99 if Settings.status == "database_offline" || Settings.status == "database_readonly" ||
100 (need_api && (Settings.status == "api_offline" || Settings.status == "api_readonly"))
102 report_error "Database offline for maintenance", :service_unavailable
104 redirect_to :controller => "site", :action => "offline"
109 def check_api_readable
110 if api_status == "offline"
111 report_error "Database offline for maintenance", :service_unavailable
116 def check_api_writable
117 unless api_status == "online"
118 report_error "Database offline for maintenance", :service_unavailable
125 when "database_offline"
127 when "database_readonly"
135 status = database_status
136 if status == "online"
147 def require_public_data
148 unless current_user.data_public?
149 report_error "You must make your edits public to upload new data", :forbidden
154 # Report and error to the user
155 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
156 # rather than only a status code and having the web engine make up a
157 # phrase from that, we can also put the error message into the status
158 # message. For now, rails won't let us)
159 def report_error(message, status = :bad_request)
160 # TODO: some sort of escaping of problem characters in the message
161 response.headers["Error"] = message
163 if request.headers["X-Error-Format"]&.casecmp("xml")&.zero?
164 result = OSM::API.new.xml_doc
165 result.root.name = "osmError"
166 result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
167 result.root << (XML::Node.new("message") << message)
169 render :xml => result.to_s
171 render :plain => message, :status => status
175 def preferred_languages
176 @preferred_languages ||= if params[:locale]
177 Locale.list(params[:locale])
179 current_user.preferred_languages
181 Locale.list(http_accept_language.user_preferred_languages)
185 helper_method :preferred_languages
188 if current_user&.languages&.empty? && !http_accept_language.user_preferred_languages.empty?
189 current_user.languages = http_accept_language.user_preferred_languages
193 I18n.locale = Locale.available.preferred(preferred_languages)
195 response.headers["Vary"] = "Accept-Language"
196 response.headers["Content-Language"] = I18n.locale.to_s
200 # wrap a web page in a timeout
201 def web_timeout(&block)
202 Timeout.timeout(Settings.web_timeout, Timeout::Error, &block)
203 rescue ActionView::Template::Error => e
206 if e.is_a?(Timeout::Error) ||
207 (e.is_a?(ActiveRecord::StatementInvalid) && e.message.include?("execution expired"))
208 ActiveRecord::Base.connection.raw_connection.cancel
209 render :action => "timeout"
213 rescue Timeout::Error
214 ActiveRecord::Base.connection.raw_connection.cancel
215 render :action => "timeout"
219 # Unfortunately if a PUT or POST request that has a body fails to
220 # read it then Apache will sometimes fail to return the response it
221 # is given to the client properly, instead erroring:
223 # https://issues.apache.org/bugzilla/show_bug.cgi?id=44782
225 # To work round this we call rewind on the body here, which is added
226 # as a filter, to force it to be fetched from Apache into a file.
232 append_content_security_policy_directives(
233 :child_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
234 :frame_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
235 :connect_src => [Settings.nominatim_url, Settings.overpass_url, Settings.fossgis_osrm_url, Settings.graphhopper_url, Settings.fossgis_valhalla_url],
236 :form_action => %w[render.openstreetmap.org],
237 :style_src => %w['unsafe-inline']
241 when "database_offline", "api_offline"
242 flash.now[:warning] = t("layouts.osm_offline")
243 when "database_readonly", "api_readonly"
244 flash.now[:warning] = t("layouts.osm_read_only")
247 request.xhr? ? "xhr" : "map"
250 def allow_thirdparty_images
251 append_content_security_policy_directives(:img_src => %w[*])
257 elsif current_user&.preferred_editor
258 current_user.preferred_editor
260 Settings.default_editor
264 helper_method :preferred_editor
267 if Settings.key?(:totp_key)
268 cookies["_osm_totp_token"] = {
269 :value => ROTP::TOTP.new(Settings.totp_key, :interval => 3600).now,
270 :domain => "openstreetmap.org",
271 :expires => 1.hour.from_now
276 def better_errors_allow_inline
279 append_content_security_policy_directives(
280 :script_src => %w['unsafe-inline'],
281 :style_src => %w['unsafe-inline']
288 Ability.new(current_user)
291 def deny_access(_exception)
292 if doorkeeper_token || current_token
294 report_error t("oauth.permissions.missing"), :forbidden
297 respond_to do |format|
298 format.html { redirect_to :controller => "/errors", :action => "forbidden" }
299 format.any { report_error t("application.permission_denied"), :forbidden }
302 respond_to do |format|
303 format.html { redirect_to login_path(:referer => request.fullpath) }
304 format.any { head :forbidden }
311 # extract authorisation credentials from headers, returns user = nil if none
313 if request.env.key? "X-HTTP_AUTHORIZATION" # where mod_rewrite might have put it
314 authdata = request.env["X-HTTP_AUTHORIZATION"].to_s.split
315 elsif request.env.key? "REDIRECT_X_HTTP_AUTHORIZATION" # mod_fcgi
316 authdata = request.env["REDIRECT_X_HTTP_AUTHORIZATION"].to_s.split
317 elsif request.env.key? "HTTP_AUTHORIZATION" # regular location
318 authdata = request.env["HTTP_AUTHORIZATION"].to_s.split
320 # only basic authentication supported
321 user, pass = Base64.decode64(authdata[1]).split(":", 2) if authdata && authdata[0] == "Basic"
325 # override to stop oauth plugin sending errors
326 def invalid_oauth_response; end
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) || current_token&.includes_scope?(scope)
353 helper_method :scope_enabled?