1 class ApplicationController < ActionController::Base
2 include SessionPersistence
4 protect_from_forgery :with => :exception
6 add_flash_types :warning, :error
8 rescue_from CanCan::AccessDenied, :with => :deny_access
11 before_action :fetch_body
12 around_action :better_errors_allow_inline, :if => proc { Rails.env.development? }
14 attr_accessor :current_user, :oauth_token
16 helper_method :current_user
17 helper_method :oauth_token
18 helper_method :preferred_langauges
24 self.current_user = User.where(:id => session[:user]).where("status IN ('active', 'confirmed', 'suspended')").first
26 if session[:fingerprint] &&
27 session[:fingerprint] != current_user.fingerprint
29 self.current_user = nil
30 elsif current_user.status == "suspended"
32 session_expires_automatically
34 redirect_to :controller => "users", :action => "suspended"
36 # don't allow access to any auth-requiring part of the site unless
37 # the new CTs have been seen (and accept/decline chosen).
38 elsif !current_user.terms_seen && flash[:skip_terms].nil?
39 flash[:notice] = t "users.terms.you need to accept or decline"
41 redirect_to :controller => "users", :action => "terms", :referer => params[:referer]
43 redirect_to :controller => "users", :action => "terms", :referer => request.fullpath
47 session[:user] = current_user.id if self.current_user = User.authenticate(:token => session[:token])
50 session[:fingerprint] = current_user.fingerprint if current_user && session[:fingerprint].nil?
51 rescue StandardError => e
52 logger.info("Exception authorizing user: #{e}")
54 self.current_user = nil
60 redirect_to :controller => "users", :action => "login", :referer => request.fullpath
68 @oauth_token = current_user.access_token(Settings.oauth_key) if current_user && Settings.key?(:oauth_key)
72 # require the user to have cookies enabled in their browser
74 if request.cookies["_osm_session"].to_s == ""
75 if params[:cookie_test].nil?
76 session[:cookie_test] = true
77 redirect_to params.to_unsafe_h.merge(:only_path => true, :cookie_test => "true")
80 flash.now[:warning] = t "application.require_cookies.cookies_needed"
83 session.delete(:cookie_test)
87 def check_database_readable(need_api = false)
88 if Settings.status == "database_offline" || (need_api && Settings.status == "api_offline")
90 report_error "Database offline for maintenance", :service_unavailable
92 redirect_to :controller => "site", :action => "offline"
97 def check_database_writable(need_api = false)
98 if Settings.status == "database_offline" || Settings.status == "database_readonly" ||
99 (need_api && (Settings.status == "api_offline" || Settings.status == "api_readonly"))
101 report_error "Database offline for maintenance", :service_unavailable
103 redirect_to :controller => "site", :action => "offline"
108 def check_api_readable
109 if api_status == "offline"
110 report_error "Database offline for maintenance", :service_unavailable
115 def check_api_writable
116 unless api_status == "online"
117 report_error "Database offline for maintenance", :service_unavailable
124 when "database_offline"
126 when "database_readonly"
134 status = database_status
135 if status == "online"
146 def require_public_data
147 unless current_user.data_public?
148 report_error "You must make your edits public to upload new data", :forbidden
153 # Report and error to the user
154 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
155 # rather than only a status code and having the web engine make up a
156 # phrase from that, we can also put the error message into the status
157 # message. For now, rails won't let us)
158 def report_error(message, status = :bad_request)
159 # TODO: some sort of escaping of problem characters in the message
160 response.headers["Error"] = message
162 if request.headers["X-Error-Format"]&.casecmp("xml")&.zero?
163 result = OSM::API.new.get_xml_doc
164 result.root.name = "osmError"
165 result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
166 result.root << (XML::Node.new("message") << message)
168 render :xml => result.to_s
170 render :plain => message, :status => status
174 def preferred_languages(reset = false)
175 @preferred_languages = nil if reset
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
187 def set_locale(reset = false)
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(reset))
195 response.headers["Vary"] = "Accept-Language"
196 response.headers["Content-Language"] = I18n.locale.to_s
199 def api_call_handle_error
201 rescue ActionController::UnknownFormat
203 rescue ActiveRecord::RecordNotFound => e
205 rescue LibXML::XML::Error, ArgumentError => e
206 report_error e.message, :bad_request
207 rescue ActiveRecord::RecordInvalid => e
208 message = "#{e.record.class} #{e.record.id}: "
209 e.record.errors.each { |attr, msg| message << "#{attr}: #{msg} (#{e.record[attr].inspect})" }
210 report_error message, :bad_request
211 rescue OSM::APIError => e
212 report_error e.message, e.status
213 rescue AbstractController::ActionNotFound => e
215 rescue StandardError => e
216 logger.info("API threw unexpected #{e.class} exception: #{e.message}")
217 e.backtrace.each { |l| logger.info(l) }
218 report_error "#{e.class}: #{e.message}", :internal_server_error
222 # asserts that the request method is the +method+ given as a parameter
223 # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
224 def assert_method(method)
225 ok = request.send(:"#{method.to_s.downcase}?")
226 raise OSM::APIBadMethodError, method unless ok
230 # wrap an api call in a timeout
231 def api_call_timeout(&block)
232 OSM::Timer.timeout(Settings.api_timeout, Timeout::Error, &block)
233 rescue Timeout::Error
234 raise OSM::APITimeoutError
238 # wrap a web page in a timeout
239 def web_timeout(&block)
240 OSM::Timer.timeout(Settings.web_timeout, Timeout::Error, &block)
241 rescue ActionView::Template::Error => e
244 if e.is_a?(Timeout::Error) ||
245 (e.is_a?(ActiveRecord::StatementInvalid) && e.message.include?("execution expired"))
246 render :action => "timeout"
250 rescue Timeout::Error
251 render :action => "timeout"
255 # ensure that there is a "user" instance variable
257 render_unknown_user params[:display_name] unless @user = User.active.find_by(:display_name => params[:display_name])
261 # render a "no such user" page
262 def render_unknown_user(name)
263 @title = t "users.no_such_user.title"
264 @not_found_user = name
266 respond_to do |format|
267 format.html { render :template => "users/no_such_user", :status => :not_found }
268 format.all { head :not_found }
273 # Unfortunately if a PUT or POST request that has a body fails to
274 # read it then Apache will sometimes fail to return the response it
275 # is given to the client properly, instead erroring:
277 # https://issues.apache.org/bugzilla/show_bug.cgi?id=44782
279 # To work round this we call rewind on the body here, which is added
280 # as a filter, to force it to be fetched from Apache into a file.
286 append_content_security_policy_directives(
287 :child_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
288 :frame_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
289 :connect_src => [Settings.nominatim_url, Settings.overpass_url, Settings.fossgis_osrm_url, Settings.graphhopper_url],
290 :form_action => %w[render.openstreetmap.org],
291 :style_src => %w['unsafe-inline']
295 when "database_offline", "api_offline"
296 flash.now[:warning] = t("layouts.osm_offline")
297 when "database_readonly", "api_readonly"
298 flash.now[:warning] = t("layouts.osm_read_only")
301 request.xhr? ? "xhr" : "map"
304 def allow_thirdparty_images
305 append_content_security_policy_directives(:img_src => %w[*])
311 elsif current_user&.preferred_editor
312 current_user.preferred_editor
314 Settings.default_editor
318 helper_method :preferred_editor
321 if Settings.key?(:totp_key)
322 cookies["_osm_totp_token"] = {
323 :value => ROTP::TOTP.new(Settings.totp_key, :interval => 3600).now,
324 :domain => "openstreetmap.org",
325 :expires => 1.hour.from_now
330 def better_errors_allow_inline
333 append_content_security_policy_directives(
334 :script_src => %w['unsafe-inline'],
335 :style_src => %w['unsafe-inline']
342 Ability.new(current_user)
345 def deny_access(_exception)
348 report_error t("oauth.permissions.missing"), :forbidden
351 respond_to do |format|
352 format.html { redirect_to :controller => "errors", :action => "forbidden" }
353 format.any { report_error t("application.permission_denied"), :forbidden }
356 respond_to do |format|
357 format.html { redirect_to :controller => "users", :action => "login", :referer => request.fullpath }
358 format.any { head :forbidden }
365 # extract authorisation credentials from headers, returns user = nil if none
367 if request.env.key? "X-HTTP_AUTHORIZATION" # where mod_rewrite might have put it
368 authdata = request.env["X-HTTP_AUTHORIZATION"].to_s.split
369 elsif request.env.key? "REDIRECT_X_HTTP_AUTHORIZATION" # mod_fcgi
370 authdata = request.env["REDIRECT_X_HTTP_AUTHORIZATION"].to_s.split
371 elsif request.env.key? "HTTP_AUTHORIZATION" # regular location
372 authdata = request.env["HTTP_AUTHORIZATION"].to_s.split
374 # only basic authentication supported
375 user, pass = Base64.decode64(authdata[1]).split(":", 2) if authdata && authdata[0] == "Basic"
379 # override to stop oauth plugin sending errors
380 def invalid_oauth_response; end
382 # clean any referer parameter
383 def safe_referer(referer)
384 referer = URI.parse(referer)
386 if referer.scheme == "http" || referer.scheme == "https"
390 elsif referer.scheme || referer.host || referer.port