1 class ApplicationController < ActionController::Base
2 include SessionPersistence
4 protect_from_forgery :with => :exception
6 rescue_from CanCan::AccessDenied, :with => :deny_access
9 before_action :fetch_body
10 around_action :better_errors_allow_inline, :if => proc { Rails.env.development? }
12 attr_accessor :current_user
14 helper_method :current_user
20 self.current_user = User.where(:id => session[:user]).where("status IN ('active', 'confirmed', 'suspended')").first
22 if current_user.status == "suspended"
24 session_expires_automatically
26 redirect_to :controller => "users", :action => "suspended"
28 # don't allow access to any auth-requiring part of the site unless
29 # the new CTs have been seen (and accept/decline chosen).
30 elsif !current_user.terms_seen && flash[:skip_terms].nil?
31 flash[:notice] = t "users.terms.you need to accept or decline"
33 redirect_to :controller => "users", :action => "terms", :referer => params[:referer]
35 redirect_to :controller => "users", :action => "terms", :referer => request.fullpath
39 session[:user] = current_user.id if self.current_user = User.authenticate(:token => session[:token])
41 rescue StandardError => e
42 logger.info("Exception authorizing user: #{e}")
44 self.current_user = nil
50 redirect_to :controller => "users", :action => "login", :referer => request.fullpath
58 @oauth = current_user.access_token(Settings.oauth_key) if current_user && Settings.key?(:oauth_key)
62 # require the user to have cookies enabled in their browser
64 if request.cookies["_osm_session"].to_s == ""
65 if params[:cookie_test].nil?
66 session[:cookie_test] = true
67 redirect_to params.to_unsafe_h.merge(:cookie_test => "true")
70 flash.now[:warning] = t "application.require_cookies.cookies_needed"
73 session.delete(:cookie_test)
77 def check_database_readable(need_api = false)
78 if Settings.status == "database_offline" || (need_api && Settings.status == "api_offline")
80 report_error "Database offline for maintenance", :service_unavailable
82 redirect_to :controller => "site", :action => "offline"
87 def check_database_writable(need_api = false)
88 if Settings.status == "database_offline" || Settings.status == "database_readonly" ||
89 (need_api && (Settings.status == "api_offline" || Settings.status == "api_readonly"))
91 report_error "Database offline for maintenance", :service_unavailable
93 redirect_to :controller => "site", :action => "offline"
98 def check_api_readable
99 if api_status == "offline"
100 report_error "Database offline for maintenance", :service_unavailable
105 def check_api_writable
106 unless api_status == "online"
107 report_error "Database offline for maintenance", :service_unavailable
113 if Settings.status == "database_offline"
115 elsif Settings.status == "database_readonly"
123 status = database_status
124 if status == "online"
125 if Settings.status == "api_offline"
127 elsif Settings.status == "api_readonly"
134 def require_public_data
135 unless current_user.data_public?
136 report_error "You must make your edits public to upload new data", :forbidden
141 # Report and error to the user
142 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
143 # rather than only a status code and having the web engine make up a
144 # phrase from that, we can also put the error message into the status
145 # message. For now, rails won't let us)
146 def report_error(message, status = :bad_request)
147 # TODO: some sort of escaping of problem characters in the message
148 response.headers["Error"] = message
150 if request.headers["X-Error-Format"]&.casecmp("xml")&.zero?
151 result = OSM::API.new.get_xml_doc
152 result.root.name = "osmError"
153 result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
154 result.root << (XML::Node.new("message") << message)
156 render :xml => result.to_s
158 render :plain => message, :status => status
162 def preferred_languages(reset = false)
163 @preferred_languages = nil if reset
164 @preferred_languages ||= if params[:locale]
165 Locale.list(params[:locale])
167 current_user.preferred_languages
169 Locale.list(http_accept_language.user_preferred_languages)
173 helper_method :preferred_languages
175 def set_locale(reset = false)
176 if current_user&.languages&.empty? && !http_accept_language.user_preferred_languages.empty?
177 current_user.languages = http_accept_language.user_preferred_languages
181 I18n.locale = Locale.available.preferred(preferred_languages(reset))
183 response.headers["Vary"] = "Accept-Language"
184 response.headers["Content-Language"] = I18n.locale.to_s
187 def api_call_handle_error
189 rescue ActionController::UnknownFormat
191 rescue ActiveRecord::RecordNotFound => e
193 rescue LibXML::XML::Error, ArgumentError => e
194 report_error e.message, :bad_request
195 rescue ActiveRecord::RecordInvalid => e
196 message = "#{e.record.class} #{e.record.id}: "
197 e.record.errors.each { |attr, msg| message << "#{attr}: #{msg} (#{e.record[attr].inspect})" }
198 report_error message, :bad_request
199 rescue OSM::APIError => e
200 report_error e.message, e.status
201 rescue AbstractController::ActionNotFound => e
203 rescue StandardError => e
204 logger.info("API threw unexpected #{e.class} exception: #{e.message}")
205 e.backtrace.each { |l| logger.info(l) }
206 report_error "#{e.class}: #{e.message}", :internal_server_error
210 # asserts that the request method is the +method+ given as a parameter
211 # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
212 def assert_method(method)
213 ok = request.send((method.to_s.downcase + "?").to_sym)
214 raise OSM::APIBadMethodError, method unless ok
218 # wrap an api call in a timeout
220 OSM::Timer.timeout(Settings.api_timeout, Timeout::Error) do
223 rescue Timeout::Error
224 raise OSM::APITimeoutError
228 # wrap a web page in a timeout
230 OSM::Timer.timeout(Settings.web_timeout, Timeout::Error) do
233 rescue ActionView::Template::Error => e
236 if e.is_a?(Timeout::Error) ||
237 (e.is_a?(ActiveRecord::StatementInvalid) && e.message =~ /execution expired/)
238 render :action => "timeout"
242 rescue Timeout::Error
243 render :action => "timeout"
247 # ensure that there is a "user" instance variable
249 render_unknown_user params[:display_name] unless @user = User.active.find_by(:display_name => params[:display_name])
253 # render a "no such user" page
254 def render_unknown_user(name)
255 @title = t "users.no_such_user.title"
256 @not_found_user = name
258 respond_to do |format|
259 format.html { render :template => "users/no_such_user", :status => :not_found }
260 format.all { head :not_found }
265 # Unfortunately if a PUT or POST request that has a body fails to
266 # read it then Apache will sometimes fail to return the response it
267 # is given to the client properly, instead erroring:
269 # https://issues.apache.org/bugzilla/show_bug.cgi?id=44782
271 # To work round this we call rewind on the body here, which is added
272 # as a filter, to force it to be fetched from Apache into a file.
278 append_content_security_policy_directives(
279 :child_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
280 :frame_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
281 :connect_src => [Settings.nominatim_url, Settings.overpass_url, Settings.fossgis_osrm_url, Settings.graphhopper_url],
282 :form_action => %w[render.openstreetmap.org],
283 :style_src => %w['unsafe-inline']
286 if Settings.status == "database_offline" || Settings.status == "api_offline"
287 flash.now[:warning] = t("layouts.osm_offline")
288 elsif Settings.status == "database_readonly" || Settings.status == "api_readonly"
289 flash.now[:warning] = t("layouts.osm_read_only")
292 request.xhr? ? "xhr" : "map"
295 def allow_thirdparty_images
296 append_content_security_policy_directives(:img_src => %w[*])
300 editor = if params[:editor]
302 elsif current_user&.preferred_editor
303 current_user.preferred_editor
305 Settings.default_editor
311 helper_method :preferred_editor
314 if Settings.key?(:totp_key)
315 cookies["_osm_totp_token"] = {
316 :value => ROTP::TOTP.new(Settings.totp_key, :interval => 3600).now,
317 :domain => "openstreetmap.org",
318 :expires => 1.hour.from_now
323 def better_errors_allow_inline
326 append_content_security_policy_directives(
327 :script_src => %w['unsafe-inline'],
328 :style_src => %w['unsafe-inline']
335 Ability.new(current_user)
338 def deny_access(_exception)
341 report_error t("oauth.permissions.missing"), :forbidden
344 respond_to do |format|
345 format.html { redirect_to :controller => "errors", :action => "forbidden" }
346 format.any { report_error t("application.permission_denied"), :forbidden }
349 respond_to do |format|
350 format.html { redirect_to :controller => "users", :action => "login", :referer => request.fullpath }
351 format.any { head :forbidden }
358 # extract authorisation credentials from headers, returns user = nil if none
360 if request.env.key? "X-HTTP_AUTHORIZATION" # where mod_rewrite might have put it
361 authdata = request.env["X-HTTP_AUTHORIZATION"].to_s.split
362 elsif request.env.key? "REDIRECT_X_HTTP_AUTHORIZATION" # mod_fcgi
363 authdata = request.env["REDIRECT_X_HTTP_AUTHORIZATION"].to_s.split
364 elsif request.env.key? "HTTP_AUTHORIZATION" # regular location
365 authdata = request.env["HTTP_AUTHORIZATION"].to_s.split
367 # only basic authentication supported
368 user, pass = Base64.decode64(authdata[1]).split(":", 2) if authdata && authdata[0] == "Basic"
372 # override to stop oauth plugin sending errors
373 def invalid_oauth_response; end