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
15 attr_accessor :oauth_token
17 helper_method :current_user
18 helper_method :oauth_token
19 helper_method :preferred_langauges
25 self.current_user = User.where(:id => session[:user]).where("status IN ('active', 'confirmed', 'suspended')").first
27 if current_user.status == "suspended"
29 session_expires_automatically
31 redirect_to :controller => "users", :action => "suspended"
33 # don't allow access to any auth-requiring part of the site unless
34 # the new CTs have been seen (and accept/decline chosen).
35 elsif !current_user.terms_seen && flash[:skip_terms].nil?
36 flash[:notice] = t "users.terms.you need to accept or decline"
38 redirect_to :controller => "users", :action => "terms", :referer => params[:referer]
40 redirect_to :controller => "users", :action => "terms", :referer => request.fullpath
44 session[:user] = current_user.id if self.current_user = User.authenticate(:token => session[:token])
46 rescue StandardError => e
47 logger.info("Exception authorizing user: #{e}")
49 self.current_user = nil
55 redirect_to :controller => "users", :action => "login", :referer => request.fullpath
63 @oauth_token = current_user.access_token(Settings.oauth_key) if current_user && Settings.key?(:oauth_key)
67 # require the user to have cookies enabled in their browser
69 if request.cookies["_osm_session"].to_s == ""
70 if params[:cookie_test].nil?
71 session[:cookie_test] = true
72 redirect_to params.to_unsafe_h.merge(:only_path => true, :cookie_test => "true")
75 flash.now[:warning] = t "application.require_cookies.cookies_needed"
78 session.delete(:cookie_test)
82 def check_database_readable(need_api = false)
83 if Settings.status == "database_offline" || (need_api && Settings.status == "api_offline")
85 report_error "Database offline for maintenance", :service_unavailable
87 redirect_to :controller => "site", :action => "offline"
92 def check_database_writable(need_api = false)
93 if Settings.status == "database_offline" || Settings.status == "database_readonly" ||
94 (need_api && (Settings.status == "api_offline" || Settings.status == "api_readonly"))
96 report_error "Database offline for maintenance", :service_unavailable
98 redirect_to :controller => "site", :action => "offline"
103 def check_api_readable
104 if api_status == "offline"
105 report_error "Database offline for maintenance", :service_unavailable
110 def check_api_writable
111 unless api_status == "online"
112 report_error "Database offline for maintenance", :service_unavailable
118 if Settings.status == "database_offline"
120 elsif Settings.status == "database_readonly"
128 status = database_status
129 if status == "online"
130 if Settings.status == "api_offline"
132 elsif Settings.status == "api_readonly"
139 def require_public_data
140 unless current_user.data_public?
141 report_error "You must make your edits public to upload new data", :forbidden
146 # Report and error to the user
147 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
148 # rather than only a status code and having the web engine make up a
149 # phrase from that, we can also put the error message into the status
150 # message. For now, rails won't let us)
151 def report_error(message, status = :bad_request)
152 # TODO: some sort of escaping of problem characters in the message
153 response.headers["Error"] = message
155 if request.headers["X-Error-Format"]&.casecmp("xml")&.zero?
156 result = OSM::API.new.get_xml_doc
157 result.root.name = "osmError"
158 result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
159 result.root << (XML::Node.new("message") << message)
161 render :xml => result.to_s
163 render :plain => message, :status => status
167 def preferred_languages(reset = false)
168 @preferred_languages = nil if reset
169 @preferred_languages ||= if params[:locale]
170 Locale.list(params[:locale])
172 current_user.preferred_languages
174 Locale.list(http_accept_language.user_preferred_languages)
178 helper_method :preferred_languages
180 def set_locale(reset = false)
181 if current_user&.languages&.empty? && !http_accept_language.user_preferred_languages.empty?
182 current_user.languages = http_accept_language.user_preferred_languages
186 I18n.locale = Locale.available.preferred(preferred_languages(reset))
188 response.headers["Vary"] = "Accept-Language"
189 response.headers["Content-Language"] = I18n.locale.to_s
192 def api_call_handle_error
194 rescue ActionController::UnknownFormat
196 rescue ActiveRecord::RecordNotFound => e
198 rescue LibXML::XML::Error, ArgumentError => e
199 report_error e.message, :bad_request
200 rescue ActiveRecord::RecordInvalid => e
201 message = "#{e.record.class} #{e.record.id}: "
202 e.record.errors.each { |attr, msg| message << "#{attr}: #{msg} (#{e.record[attr].inspect})" }
203 report_error message, :bad_request
204 rescue OSM::APIError => e
205 report_error e.message, e.status
206 rescue AbstractController::ActionNotFound => e
208 rescue StandardError => e
209 logger.info("API threw unexpected #{e.class} exception: #{e.message}")
210 e.backtrace.each { |l| logger.info(l) }
211 report_error "#{e.class}: #{e.message}", :internal_server_error
215 # asserts that the request method is the +method+ given as a parameter
216 # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
217 def assert_method(method)
218 ok = request.send((method.to_s.downcase + "?").to_sym)
219 raise OSM::APIBadMethodError, method unless ok
223 # wrap an api call in a timeout
225 OSM::Timer.timeout(Settings.api_timeout, Timeout::Error) do
228 rescue Timeout::Error
229 raise OSM::APITimeoutError
233 # wrap a web page in a timeout
235 OSM::Timer.timeout(Settings.web_timeout, Timeout::Error) do
238 rescue ActionView::Template::Error => e
241 if e.is_a?(Timeout::Error) ||
242 (e.is_a?(ActiveRecord::StatementInvalid) && e.message.include?("execution expired"))
243 render :action => "timeout"
247 rescue Timeout::Error
248 render :action => "timeout"
252 # ensure that there is a "user" instance variable
254 render_unknown_user params[:display_name] unless @user = User.active.find_by(:display_name => params[:display_name])
258 # render a "no such user" page
259 def render_unknown_user(name)
260 @title = t "users.no_such_user.title"
261 @not_found_user = name
263 respond_to do |format|
264 format.html { render :template => "users/no_such_user", :status => :not_found }
265 format.all { head :not_found }
270 # Unfortunately if a PUT or POST request that has a body fails to
271 # read it then Apache will sometimes fail to return the response it
272 # is given to the client properly, instead erroring:
274 # https://issues.apache.org/bugzilla/show_bug.cgi?id=44782
276 # To work round this we call rewind on the body here, which is added
277 # as a filter, to force it to be fetched from Apache into a file.
283 append_content_security_policy_directives(
284 :child_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
285 :frame_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
286 :connect_src => [Settings.nominatim_url, Settings.overpass_url, Settings.fossgis_osrm_url, Settings.graphhopper_url],
287 :form_action => %w[render.openstreetmap.org],
288 :style_src => %w['unsafe-inline']
291 if Settings.status == "database_offline" || Settings.status == "api_offline"
292 flash.now[:warning] = t("layouts.osm_offline")
293 elsif Settings.status == "database_readonly" || Settings.status == "api_readonly"
294 flash.now[:warning] = t("layouts.osm_read_only")
297 request.xhr? ? "xhr" : "map"
300 def allow_thirdparty_images
301 append_content_security_policy_directives(:img_src => %w[*])
305 editor = if params[:editor]
307 elsif current_user&.preferred_editor
308 current_user.preferred_editor
310 Settings.default_editor
316 helper_method :preferred_editor
319 if Settings.key?(:totp_key)
320 cookies["_osm_totp_token"] = {
321 :value => ROTP::TOTP.new(Settings.totp_key, :interval => 3600).now,
322 :domain => "openstreetmap.org",
323 :expires => 1.hour.from_now
328 def better_errors_allow_inline
331 append_content_security_policy_directives(
332 :script_src => %w['unsafe-inline'],
333 :style_src => %w['unsafe-inline']
340 Ability.new(current_user)
343 def deny_access(_exception)
346 report_error t("oauth.permissions.missing"), :forbidden
349 respond_to do |format|
350 format.html { redirect_to :controller => "errors", :action => "forbidden" }
351 format.any { report_error t("application.permission_denied"), :forbidden }
354 respond_to do |format|
355 format.html { redirect_to :controller => "users", :action => "login", :referer => request.fullpath }
356 format.any { head :forbidden }
363 # extract authorisation credentials from headers, returns user = nil if none
365 if request.env.key? "X-HTTP_AUTHORIZATION" # where mod_rewrite might have put it
366 authdata = request.env["X-HTTP_AUTHORIZATION"].to_s.split
367 elsif request.env.key? "REDIRECT_X_HTTP_AUTHORIZATION" # mod_fcgi
368 authdata = request.env["REDIRECT_X_HTTP_AUTHORIZATION"].to_s.split
369 elsif request.env.key? "HTTP_AUTHORIZATION" # regular location
370 authdata = request.env["HTTP_AUTHORIZATION"].to_s.split
372 # only basic authentication supported
373 user, pass = Base64.decode64(authdata[1]).split(":", 2) if authdata && authdata[0] == "Basic"
377 # override to stop oauth plugin sending errors
378 def invalid_oauth_response; end
380 # clean any referer parameter
381 def safe_referer(referer)
382 referer = URI.parse(referer)
384 if referer.scheme == "http" || referer.scheme == "https"
388 elsif referer.scheme || referer.host || referer.port