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 current_user.status == "suspended"
28 session_expires_automatically
30 redirect_to :controller => "users", :action => "suspended"
32 # don't allow access to any auth-requiring part of the site unless
33 # the new CTs have been seen (and accept/decline chosen).
34 elsif !current_user.terms_seen && flash[:skip_terms].nil?
35 flash[:notice] = t "users.terms.you need to accept or decline"
37 redirect_to :controller => "users", :action => "terms", :referer => params[:referer]
39 redirect_to :controller => "users", :action => "terms", :referer => request.fullpath
43 session[:user] = current_user.id if self.current_user = User.authenticate(:token => session[:token])
45 rescue StandardError => e
46 logger.info("Exception authorizing user: #{e}")
48 self.current_user = nil
54 redirect_to :controller => "users", :action => "login", :referer => request.fullpath
62 @oauth_token = current_user.access_token(Settings.oauth_key) if current_user && Settings.key?(:oauth_key)
66 # require the user to have cookies enabled in their browser
68 if request.cookies["_osm_session"].to_s == ""
69 if params[:cookie_test].nil?
70 session[:cookie_test] = true
71 redirect_to params.to_unsafe_h.merge(:only_path => true, :cookie_test => "true")
74 flash.now[:warning] = t "application.require_cookies.cookies_needed"
77 session.delete(:cookie_test)
81 def check_database_readable(need_api = false)
82 if Settings.status == "database_offline" || (need_api && Settings.status == "api_offline")
84 report_error "Database offline for maintenance", :service_unavailable
86 redirect_to :controller => "site", :action => "offline"
91 def check_database_writable(need_api = false)
92 if Settings.status == "database_offline" || Settings.status == "database_readonly" ||
93 (need_api && (Settings.status == "api_offline" || Settings.status == "api_readonly"))
95 report_error "Database offline for maintenance", :service_unavailable
97 redirect_to :controller => "site", :action => "offline"
102 def check_api_readable
103 if api_status == "offline"
104 report_error "Database offline for maintenance", :service_unavailable
109 def check_api_writable
110 unless api_status == "online"
111 report_error "Database offline for maintenance", :service_unavailable
118 when "database_offline"
120 when "database_readonly"
128 status = database_status
129 if status == "online"
140 def require_public_data
141 unless current_user.data_public?
142 report_error "You must make your edits public to upload new data", :forbidden
147 # Report and error to the user
148 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
149 # rather than only a status code and having the web engine make up a
150 # phrase from that, we can also put the error message into the status
151 # message. For now, rails won't let us)
152 def report_error(message, status = :bad_request)
153 # TODO: some sort of escaping of problem characters in the message
154 response.headers["Error"] = message
156 if request.headers["X-Error-Format"]&.casecmp("xml")&.zero?
157 result = OSM::API.new.get_xml_doc
158 result.root.name = "osmError"
159 result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
160 result.root << (XML::Node.new("message") << message)
162 render :xml => result.to_s
164 render :plain => message, :status => status
168 def preferred_languages(reset = false)
169 @preferred_languages = nil if reset
170 @preferred_languages ||= if params[:locale]
171 Locale.list(params[:locale])
173 current_user.preferred_languages
175 Locale.list(http_accept_language.user_preferred_languages)
179 helper_method :preferred_languages
181 def set_locale(reset = false)
182 if current_user&.languages&.empty? && !http_accept_language.user_preferred_languages.empty?
183 current_user.languages = http_accept_language.user_preferred_languages
187 I18n.locale = Locale.available.preferred(preferred_languages(reset))
189 response.headers["Vary"] = "Accept-Language"
190 response.headers["Content-Language"] = I18n.locale.to_s
193 def api_call_handle_error
195 rescue ActionController::UnknownFormat
197 rescue ActiveRecord::RecordNotFound => e
199 rescue LibXML::XML::Error, ArgumentError => e
200 report_error e.message, :bad_request
201 rescue ActiveRecord::RecordInvalid => e
202 message = "#{e.record.class} #{e.record.id}: "
203 e.record.errors.each { |attr, msg| message << "#{attr}: #{msg} (#{e.record[attr].inspect})" }
204 report_error message, :bad_request
205 rescue OSM::APIError => e
206 report_error e.message, e.status
207 rescue AbstractController::ActionNotFound => e
209 rescue StandardError => e
210 logger.info("API threw unexpected #{e.class} exception: #{e.message}")
211 e.backtrace.each { |l| logger.info(l) }
212 report_error "#{e.class}: #{e.message}", :internal_server_error
216 # asserts that the request method is the +method+ given as a parameter
217 # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
218 def assert_method(method)
219 ok = request.send(:"#{method.to_s.downcase}?")
220 raise OSM::APIBadMethodError, method unless ok
224 # wrap an api call in a timeout
225 def api_call_timeout(&block)
226 OSM::Timer.timeout(Settings.api_timeout, Timeout::Error, &block)
227 rescue Timeout::Error
228 raise OSM::APITimeoutError
232 # wrap a web page in a timeout
233 def web_timeout(&block)
234 OSM::Timer.timeout(Settings.web_timeout, Timeout::Error, &block)
235 rescue ActionView::Template::Error => e
238 if e.is_a?(Timeout::Error) ||
239 (e.is_a?(ActiveRecord::StatementInvalid) && e.message.include?("execution expired"))
240 render :action => "timeout"
244 rescue Timeout::Error
245 render :action => "timeout"
249 # ensure that there is a "user" instance variable
251 render_unknown_user params[:display_name] unless @user = User.active.find_by(:display_name => params[:display_name])
255 # render a "no such user" page
256 def render_unknown_user(name)
257 @title = t "users.no_such_user.title"
258 @not_found_user = name
260 respond_to do |format|
261 format.html { render :template => "users/no_such_user", :status => :not_found }
262 format.all { head :not_found }
267 # Unfortunately if a PUT or POST request that has a body fails to
268 # read it then Apache will sometimes fail to return the response it
269 # is given to the client properly, instead erroring:
271 # https://issues.apache.org/bugzilla/show_bug.cgi?id=44782
273 # To work round this we call rewind on the body here, which is added
274 # as a filter, to force it to be fetched from Apache into a file.
280 append_content_security_policy_directives(
281 :child_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
282 :frame_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
283 :connect_src => [Settings.nominatim_url, Settings.overpass_url, Settings.fossgis_osrm_url, Settings.graphhopper_url],
284 :form_action => %w[render.openstreetmap.org],
285 :style_src => %w['unsafe-inline']
289 when "database_offline", "api_offline"
290 flash.now[:warning] = t("layouts.osm_offline")
291 when "database_readonly", "api_readonly"
292 flash.now[:warning] = t("layouts.osm_read_only")
295 request.xhr? ? "xhr" : "map"
298 def allow_thirdparty_images
299 append_content_security_policy_directives(:img_src => %w[*])
305 elsif current_user&.preferred_editor
306 current_user.preferred_editor
308 Settings.default_editor
312 helper_method :preferred_editor
315 if Settings.key?(:totp_key)
316 cookies["_osm_totp_token"] = {
317 :value => ROTP::TOTP.new(Settings.totp_key, :interval => 3600).now,
318 :domain => "openstreetmap.org",
319 :expires => 1.hour.from_now
324 def better_errors_allow_inline
327 append_content_security_policy_directives(
328 :script_src => %w['unsafe-inline'],
329 :style_src => %w['unsafe-inline']
336 Ability.new(current_user)
339 def deny_access(_exception)
342 report_error t("oauth.permissions.missing"), :forbidden
345 respond_to do |format|
346 format.html { redirect_to :controller => "errors", :action => "forbidden" }
347 format.any { report_error t("application.permission_denied"), :forbidden }
350 respond_to do |format|
351 format.html { redirect_to :controller => "users", :action => "login", :referer => request.fullpath }
352 format.any { head :forbidden }
359 # extract authorisation credentials from headers, returns user = nil if none
361 if request.env.key? "X-HTTP_AUTHORIZATION" # where mod_rewrite might have put it
362 authdata = request.env["X-HTTP_AUTHORIZATION"].to_s.split
363 elsif request.env.key? "REDIRECT_X_HTTP_AUTHORIZATION" # mod_fcgi
364 authdata = request.env["REDIRECT_X_HTTP_AUTHORIZATION"].to_s.split
365 elsif request.env.key? "HTTP_AUTHORIZATION" # regular location
366 authdata = request.env["HTTP_AUTHORIZATION"].to_s.split
368 # only basic authentication supported
369 user, pass = Base64.decode64(authdata[1]).split(":", 2) if authdata && authdata[0] == "Basic"
373 # override to stop oauth plugin sending errors
374 def invalid_oauth_response; end
376 # clean any referer parameter
377 def safe_referer(referer)
378 referer = URI.parse(referer)
380 if referer.scheme == "http" || referer.scheme == "https"
384 elsif referer.scheme || referer.host || referer.port