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
13 helper_method :current_user
19 self.current_user = User.where(:id => session[:user]).where("status IN ('active', 'confirmed', 'suspended')").first
21 if current_user.status == "suspended"
23 session_expires_automatically
25 redirect_to :controller => "users", :action => "suspended"
27 # don't allow access to any auth-requiring part of the site unless
28 # the new CTs have been seen (and accept/decline chosen).
29 elsif !current_user.terms_seen && flash[:skip_terms].nil?
30 flash[:notice] = t "users.terms.you need to accept or decline"
32 redirect_to :controller => "users", :action => "terms", :referer => params[:referer]
34 redirect_to :controller => "users", :action => "terms", :referer => request.fullpath
38 session[:user] = current_user.id if self.current_user = User.authenticate(:token => session[:token])
40 rescue StandardError => e
41 logger.info("Exception authorizing user: #{e}")
43 self.current_user = nil
49 redirect_to :controller => "users", :action => "login", :referer => request.fullpath
57 @oauth = current_user.access_token(Settings.oauth_key) if current_user && Settings.key?(:oauth_key)
61 # require the user to have cookies enabled in their browser
63 if request.cookies["_osm_session"].to_s == ""
64 if params[:cookie_test].nil?
65 session[:cookie_test] = true
66 redirect_to params.to_unsafe_h.merge(:cookie_test => "true")
69 flash.now[:warning] = t "application.require_cookies.cookies_needed"
72 session.delete(:cookie_test)
76 def check_database_readable(need_api = false)
77 if Settings.status == "database_offline" || (need_api && Settings.status == "api_offline")
79 report_error "Database offline for maintenance", :service_unavailable
81 redirect_to :controller => "site", :action => "offline"
86 def check_database_writable(need_api = false)
87 if Settings.status == "database_offline" || Settings.status == "database_readonly" ||
88 (need_api && (Settings.status == "api_offline" || Settings.status == "api_readonly"))
90 report_error "Database offline for maintenance", :service_unavailable
92 redirect_to :controller => "site", :action => "offline"
97 def check_api_readable
98 if api_status == "offline"
99 report_error "Database offline for maintenance", :service_unavailable
104 def check_api_writable
105 unless api_status == "online"
106 report_error "Database offline for maintenance", :service_unavailable
112 if Settings.status == "database_offline"
114 elsif Settings.status == "database_readonly"
122 status = database_status
123 if status == "online"
124 if Settings.status == "api_offline"
126 elsif Settings.status == "api_readonly"
133 def require_public_data
134 unless current_user.data_public?
135 report_error "You must make your edits public to upload new data", :forbidden
140 # Report and error to the user
141 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
142 # rather than only a status code and having the web engine make up a
143 # phrase from that, we can also put the error message into the status
144 # message. For now, rails won't let us)
145 def report_error(message, status = :bad_request)
146 # TODO: some sort of escaping of problem characters in the message
147 response.headers["Error"] = message
149 if request.headers["X-Error-Format"]&.casecmp("xml")&.zero?
150 result = OSM::API.new.get_xml_doc
151 result.root.name = "osmError"
152 result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
153 result.root << (XML::Node.new("message") << message)
155 render :xml => result.to_s
157 render :plain => message, :status => status
161 def preferred_languages(reset = false)
162 @preferred_languages = nil if reset
163 @preferred_languages ||= if params[:locale]
164 Locale.list(params[:locale])
166 current_user.preferred_languages
168 Locale.list(http_accept_language.user_preferred_languages)
172 helper_method :preferred_languages
174 def set_locale(reset = false)
175 if current_user&.languages&.empty? && !http_accept_language.user_preferred_languages.empty?
176 current_user.languages = http_accept_language.user_preferred_languages
180 I18n.locale = Locale.available.preferred(preferred_languages(reset))
182 response.headers["Vary"] = "Accept-Language"
183 response.headers["Content-Language"] = I18n.locale.to_s
186 def api_call_handle_error
188 rescue ActionController::UnknownFormat
190 rescue ActiveRecord::RecordNotFound => e
192 rescue LibXML::XML::Error, ArgumentError => e
193 report_error e.message, :bad_request
194 rescue ActiveRecord::RecordInvalid => e
195 message = "#{e.record.class} #{e.record.id}: "
196 e.record.errors.each { |attr, msg| message << "#{attr}: #{msg} (#{e.record[attr].inspect})" }
197 report_error message, :bad_request
198 rescue OSM::APIError => e
199 report_error e.message, e.status
200 rescue AbstractController::ActionNotFound => e
202 rescue StandardError => e
203 logger.info("API threw unexpected #{e.class} exception: #{e.message}")
204 e.backtrace.each { |l| logger.info(l) }
205 report_error "#{e.class}: #{e.message}", :internal_server_error
209 # asserts that the request method is the +method+ given as a parameter
210 # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
211 def assert_method(method)
212 ok = request.send((method.to_s.downcase + "?").to_sym)
213 raise OSM::APIBadMethodError, method unless ok
217 # wrap an api call in a timeout
219 OSM::Timer.timeout(Settings.api_timeout, Timeout::Error) do
222 rescue Timeout::Error
223 raise OSM::APITimeoutError
227 # wrap a web page in a timeout
229 OSM::Timer.timeout(Settings.web_timeout, Timeout::Error) do
232 rescue ActionView::Template::Error => e
235 if e.is_a?(Timeout::Error) ||
236 (e.is_a?(ActiveRecord::StatementInvalid) && e.message =~ /execution expired/)
237 render :action => "timeout"
241 rescue Timeout::Error
242 render :action => "timeout"
246 # ensure that there is a "user" instance variable
248 render_unknown_user params[:display_name] unless @user = User.active.find_by(:display_name => params[:display_name])
252 # render a "no such user" page
253 def render_unknown_user(name)
254 @title = t "users.no_such_user.title"
255 @not_found_user = name
257 respond_to do |format|
258 format.html { render :template => "users/no_such_user", :status => :not_found }
259 format.all { head :not_found }
264 # Unfortunately if a PUT or POST request that has a body fails to
265 # read it then Apache will sometimes fail to return the response it
266 # is given to the client properly, instead erroring:
268 # https://issues.apache.org/bugzilla/show_bug.cgi?id=44782
270 # To work round this we call rewind on the body here, which is added
271 # as a filter, to force it to be fetched from Apache into a file.
277 append_content_security_policy_directives(
278 :child_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
279 :frame_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
280 :connect_src => [Settings.nominatim_url, Settings.overpass_url, Settings.fossgis_osrm_url, Settings.graphhopper_url],
281 :form_action => %w[render.openstreetmap.org],
282 :style_src => %w['unsafe-inline']
285 if Settings.status == "database_offline" || Settings.status == "api_offline"
286 flash.now[:warning] = t("layouts.osm_offline")
287 elsif Settings.status == "database_readonly" || Settings.status == "api_readonly"
288 flash.now[:warning] = t("layouts.osm_read_only")
291 request.xhr? ? "xhr" : "map"
294 def allow_thirdparty_images
295 append_content_security_policy_directives(:img_src => %w[*])
299 editor = if params[:editor]
301 elsif current_user&.preferred_editor
302 current_user.preferred_editor
304 Settings.default_editor
310 helper_method :preferred_editor
313 if Settings.key?(:totp_key)
314 cookies["_osm_totp_token"] = {
315 :value => ROTP::TOTP.new(Settings.totp_key, :interval => 3600).now,
316 :domain => "openstreetmap.org",
317 :expires => 1.hour.from_now
322 def better_errors_allow_inline
325 append_content_security_policy_directives(
326 :script_src => %w['unsafe-inline'],
327 :style_src => %w['unsafe-inline']
334 Ability.new(current_user)
337 def deny_access(_exception)
340 report_error t("oauth.permissions.missing"), :forbidden
343 respond_to do |format|
344 format.html { redirect_to :controller => "errors", :action => "forbidden" }
345 format.any { report_error t("application.permission_denied"), :forbidden }
348 respond_to do |format|
349 format.html { redirect_to :controller => "users", :action => "login", :referer => request.fullpath }
350 format.any { head :forbidden }
357 # extract authorisation credentials from headers, returns user = nil if none
359 if request.env.key? "X-HTTP_AUTHORIZATION" # where mod_rewrite might have put it
360 authdata = request.env["X-HTTP_AUTHORIZATION"].to_s.split
361 elsif request.env.key? "REDIRECT_X_HTTP_AUTHORIZATION" # mod_fcgi
362 authdata = request.env["REDIRECT_X_HTTP_AUTHORIZATION"].to_s.split
363 elsif request.env.key? "HTTP_AUTHORIZATION" # regular location
364 authdata = request.env["HTTP_AUTHORIZATION"].to_s.split
366 # only basic authentication supported
367 user, pass = Base64.decode64(authdata[1]).split(":", 2) if authdata && authdata[0] == "Basic"
371 # override to stop oauth plugin sending errors
372 def invalid_oauth_response; end