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
20 helper_method :preferred_langauges
26 self.current_user = User.where(:id => session[:user]).where("status IN ('active', 'confirmed', 'suspended')").first
28 if session[:fingerprint] &&
29 session[:fingerprint] != current_user.fingerprint
31 self.current_user = nil
32 elsif current_user.status == "suspended"
34 session_expires_automatically
36 redirect_to :controller => "users", :action => "suspended"
38 # don't allow access to any auth-requiring part of the site unless
39 # the new CTs have been seen (and accept/decline chosen).
40 elsif !current_user.terms_seen && flash[:skip_terms].nil?
41 flash[:notice] = t "users.terms.you need to accept or decline"
43 redirect_to :controller => "users", :action => "terms", :referer => params[:referer]
45 redirect_to :controller => "users", :action => "terms", :referer => request.fullpath
49 session[:user] = current_user.id if self.current_user = User.authenticate(:token => session[:token])
52 session[:fingerprint] = current_user.fingerprint if current_user && session[:fingerprint].nil?
53 rescue StandardError => e
54 logger.info("Exception authorizing user: #{e}")
56 self.current_user = nil
62 redirect_to login_path(:referer => request.fullpath)
70 @oauth_token = current_user.access_token(Settings.oauth_key) if current_user && Settings.key?(:oauth_key)
74 # require the user to have cookies enabled in their browser
76 if request.cookies["_osm_session"].to_s == ""
77 if params[:cookie_test].nil?
78 session[:cookie_test] = true
79 redirect_to params.to_unsafe_h.merge(:only_path => true, :cookie_test => "true")
82 flash.now[:warning] = t "application.require_cookies.cookies_needed"
85 session.delete(:cookie_test)
89 def check_database_readable(need_api: false)
90 if Settings.status == "database_offline" || (need_api && Settings.status == "api_offline")
92 report_error "Database offline for maintenance", :service_unavailable
94 redirect_to :controller => "site", :action => "offline"
99 def check_database_writable(need_api: false)
100 if Settings.status == "database_offline" || Settings.status == "database_readonly" ||
101 (need_api && (Settings.status == "api_offline" || Settings.status == "api_readonly"))
103 report_error "Database offline for maintenance", :service_unavailable
105 redirect_to :controller => "site", :action => "offline"
110 def check_api_readable
111 if api_status == "offline"
112 report_error "Database offline for maintenance", :service_unavailable
117 def check_api_writable
118 unless api_status == "online"
119 report_error "Database offline for maintenance", :service_unavailable
126 when "database_offline"
128 when "database_readonly"
136 status = database_status
137 if status == "online"
148 def require_public_data
149 unless current_user.data_public?
150 report_error "You must make your edits public to upload new data", :forbidden
155 # Report and error to the user
156 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
157 # rather than only a status code and having the web engine make up a
158 # phrase from that, we can also put the error message into the status
159 # message. For now, rails won't let us)
160 def report_error(message, status = :bad_request)
161 # TODO: some sort of escaping of problem characters in the message
162 response.headers["Error"] = message
164 if request.headers["X-Error-Format"]&.casecmp("xml")&.zero?
165 result = OSM::API.new.get_xml_doc
166 result.root.name = "osmError"
167 result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
168 result.root << (XML::Node.new("message") << message)
170 render :xml => result.to_s
172 render :plain => message, :status => status
176 def preferred_languages
177 @preferred_languages ||= if params[:locale]
178 Locale.list(params[:locale])
180 current_user.preferred_languages
182 Locale.list(http_accept_language.user_preferred_languages)
186 helper_method :preferred_languages
189 if current_user&.languages&.empty? && !http_accept_language.user_preferred_languages.empty?
190 current_user.languages = http_accept_language.user_preferred_languages
194 I18n.locale = Locale.available.preferred(preferred_languages)
196 response.headers["Vary"] = "Accept-Language"
197 response.headers["Content-Language"] = I18n.locale.to_s
200 def api_call_handle_error
202 rescue ActionController::UnknownFormat
204 rescue ActiveRecord::RecordNotFound => e
206 rescue LibXML::XML::Error, ArgumentError => e
207 report_error e.message, :bad_request
208 rescue ActiveRecord::RecordInvalid => e
209 message = "#{e.record.class} #{e.record.id}: "
210 e.record.errors.each { |error| message << "#{error.attribute}: #{error.message} (#{e.record[error.attribute].inspect})" }
211 report_error message, :bad_request
212 rescue OSM::APIError => e
213 report_error e.message, e.status
214 rescue AbstractController::ActionNotFound => e
216 rescue StandardError => e
217 logger.info("API threw unexpected #{e.class} exception: #{e.message}")
218 e.backtrace.each { |l| logger.info(l) }
219 report_error "#{e.class}: #{e.message}", :internal_server_error
223 # asserts that the request method is the +method+ given as a parameter
224 # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
225 def assert_method(method)
226 ok = request.send(:"#{method.to_s.downcase}?")
227 raise OSM::APIBadMethodError, method unless ok
231 # wrap an api call in a timeout
232 def api_call_timeout(&block)
233 Timeout.timeout(Settings.api_timeout, Timeout::Error, &block)
234 rescue Timeout::Error
235 raise OSM::APITimeoutError
239 # wrap a web page in a timeout
240 def web_timeout(&block)
241 Timeout.timeout(Settings.web_timeout, Timeout::Error, &block)
242 rescue ActionView::Template::Error => e
245 if e.is_a?(Timeout::Error) ||
246 (e.is_a?(ActiveRecord::StatementInvalid) && e.message.include?("execution expired"))
247 render :action => "timeout"
251 rescue Timeout::Error
252 render :action => "timeout"
256 # ensure that there is a "user" instance variable
258 render_unknown_user params[:display_name] unless @user = User.active.find_by(:display_name => params[:display_name])
262 # render a "no such user" page
263 def render_unknown_user(name)
264 @title = t "users.no_such_user.title"
265 @not_found_user = name
267 respond_to do |format|
268 format.html { render :template => "users/no_such_user", :status => :not_found }
269 format.all { head :not_found }
274 # Unfortunately if a PUT or POST request that has a body fails to
275 # read it then Apache will sometimes fail to return the response it
276 # is given to the client properly, instead erroring:
278 # https://issues.apache.org/bugzilla/show_bug.cgi?id=44782
280 # To work round this we call rewind on the body here, which is added
281 # as a filter, to force it to be fetched from Apache into a file.
287 append_content_security_policy_directives(
288 :child_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
289 :frame_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
290 :connect_src => [Settings.nominatim_url, Settings.overpass_url, Settings.fossgis_osrm_url, Settings.graphhopper_url],
291 :form_action => %w[render.openstreetmap.org],
292 :style_src => %w['unsafe-inline']
296 when "database_offline", "api_offline"
297 flash.now[:warning] = t("layouts.osm_offline")
298 when "database_readonly", "api_readonly"
299 flash.now[:warning] = t("layouts.osm_read_only")
302 request.xhr? ? "xhr" : "map"
305 def allow_thirdparty_images
306 append_content_security_policy_directives(:img_src => %w[*])
312 elsif current_user&.preferred_editor
313 current_user.preferred_editor
315 Settings.default_editor
319 helper_method :preferred_editor
322 if Settings.key?(:totp_key)
323 cookies["_osm_totp_token"] = {
324 :value => ROTP::TOTP.new(Settings.totp_key, :interval => 3600).now,
325 :domain => "openstreetmap.org",
326 :expires => 1.hour.from_now
331 def better_errors_allow_inline
334 append_content_security_policy_directives(
335 :script_src => %w['unsafe-inline'],
336 :style_src => %w['unsafe-inline']
343 Ability.new(current_user)
346 def deny_access(_exception)
347 if doorkeeper_token || current_token
349 report_error t("oauth.permissions.missing"), :forbidden
352 respond_to do |format|
353 format.html { redirect_to :controller => "errors", :action => "forbidden" }
354 format.any { report_error t("application.permission_denied"), :forbidden }
357 respond_to do |format|
358 format.html { redirect_to login_path(:referer => request.fullpath) }
359 format.any { head :forbidden }
366 # extract authorisation credentials from headers, returns user = nil if none
368 if request.env.key? "X-HTTP_AUTHORIZATION" # where mod_rewrite might have put it
369 authdata = request.env["X-HTTP_AUTHORIZATION"].to_s.split
370 elsif request.env.key? "REDIRECT_X_HTTP_AUTHORIZATION" # mod_fcgi
371 authdata = request.env["REDIRECT_X_HTTP_AUTHORIZATION"].to_s.split
372 elsif request.env.key? "HTTP_AUTHORIZATION" # regular location
373 authdata = request.env["HTTP_AUTHORIZATION"].to_s.split
375 # only basic authentication supported
376 user, pass = Base64.decode64(authdata[1]).split(":", 2) if authdata && authdata[0] == "Basic"
380 # override to stop oauth plugin sending errors
381 def invalid_oauth_response; end
383 # clean any referer parameter
384 def safe_referer(referer)
385 referer = URI.parse(referer)
387 if referer.scheme == "http" || referer.scheme == "https"
391 elsif referer.scheme || referer.host || referer.port
395 referer = nil if referer&.path&.first != "/"