1 class ApplicationController < ActionController::Base
2 include SessionPersistence
4 protect_from_forgery :with => :exception
6 rescue_from CanCan::AccessDenied, :with => :deny_access
8 before_action :fetch_body
9 around_action :better_errors_allow_inline, :if => proc { Rails.env.development? }
11 attr_accessor :current_user
12 helper_method :current_user
16 self.current_user = User.where(:id => session[:user]).where("status IN ('active', 'confirmed', 'suspended')").first
18 if current_user.status == "suspended"
20 session_expires_automatically
22 redirect_to :controller => "users", :action => "suspended"
24 # don't allow access to any auth-requiring part of the site unless
25 # the new CTs have been seen (and accept/decline chosen).
26 elsif !current_user.terms_seen && flash[:skip_terms].nil?
27 flash[:notice] = t "users.terms.you need to accept or decline"
29 redirect_to :controller => "users", :action => "terms", :referer => params[:referer]
31 redirect_to :controller => "users", :action => "terms", :referer => request.fullpath
35 session[:user] = current_user.id if self.current_user = User.authenticate(:token => session[:token])
37 rescue StandardError => ex
38 logger.info("Exception authorizing user: #{ex}")
40 self.current_user = nil
46 redirect_to :controller => "users", :action => "login", :referer => request.fullpath
54 @oauth = current_user.access_token(OAUTH_KEY) if current_user && defined? OAUTH_KEY
58 # requires the user to be logged in by the token or HTTP methods, or have an
59 # OAuth token with the right capability. this method is a bit of a pain to call
60 # directly, since it's cumbersome to call filters with arguments in rails. to
61 # make it easier to read and write the code, there are some utility methods
63 def require_capability(cap)
64 # when the current token is nil, it means the user logged in with a different
65 # method, otherwise an OAuth token was used, which has to be checked.
66 unless current_token.nil?
67 unless current_token.read_attribute(cap)
69 report_error t("oauth.permissions.missing"), :forbidden
76 # require the user to have cookies enabled in their browser
78 if request.cookies["_osm_session"].to_s == ""
79 if params[:cookie_test].nil?
80 session[:cookie_test] = true
81 redirect_to params.to_unsafe_h.merge(:cookie_test => "true")
84 flash.now[:warning] = t "application.require_cookies.cookies_needed"
87 session.delete(:cookie_test)
91 # Utility methods to make the controller filter methods easier to read and write.
92 def require_allow_read_prefs
93 require_capability(:allow_read_prefs)
96 def require_allow_write_prefs
97 require_capability(:allow_write_prefs)
100 def require_allow_write_diary
101 require_capability(:allow_write_diary)
104 def require_allow_write_api
105 require_capability(:allow_write_api)
107 if REQUIRE_TERMS_AGREED && current_user.terms_agreed.nil?
108 report_error "You must accept the contributor terms before you can edit.", :forbidden
113 def require_allow_read_gpx
114 require_capability(:allow_read_gpx)
117 def require_allow_write_gpx
118 require_capability(:allow_write_gpx)
122 # sets up the current_user for use by other methods. this is mostly called
123 # from the authorize method, but can be called elsewhere if authorisation
126 # try and setup using OAuth
127 unless Authenticator.new(self, [:token]).allow?
128 username, passwd = get_auth_data # parse from headers
129 # authenticate per-scheme
130 self.current_user = if username.nil?
131 nil # no authentication provided - perhaps first connect (client should retry after 401)
132 elsif username == "token"
133 User.authenticate(:token => passwd) # preferred - random token for user from db, passed in basic auth
135 User.authenticate(:username => username, :password => passwd) # basic auth
139 # have we identified the user?
141 # check if the user has been banned
142 user_block = current_user.blocks.active.take
143 unless user_block.nil?
145 if user_block.zero_hour?
146 report_error t("application.setup_user_auth.blocked_zero_hour"), :forbidden
148 report_error t("application.setup_user_auth.blocked"), :forbidden
152 # if the user hasn't seen the contributor terms then don't
153 # allow editing - they have to go to the web site and see
154 # (but can decline) the CTs to continue.
155 if REQUIRE_TERMS_SEEN && !current_user.terms_seen && flash[:skip_terms].nil?
157 report_error t("application.setup_user_auth.need_to_see_terms"), :forbidden
162 def authorize(realm = "Web Password", errormessage = "Couldn't authenticate you")
163 # make the current_user object from any auth sources we have
166 # handle authenticate pass/fail
168 # no auth, the user does not exist or the password was wrong
169 response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
170 render :plain => errormessage, :status => :unauthorized
176 # to be used as a before_filter *after* authorize. this checks that
177 # the user is a moderator and, if not, returns a forbidden error.
178 def authorize_moderator(errormessage = "Access restricted to moderators")
179 # check user is a moderator
180 unless current_user.moderator?
181 render :plain => errormessage, :status => :forbidden
186 def check_database_readable(need_api = false)
187 if STATUS == :database_offline || (need_api && STATUS == :api_offline)
189 report_error "Database offline for maintenance", :service_unavailable
191 redirect_to :controller => "site", :action => "offline"
196 def check_database_writable(need_api = false)
197 if STATUS == :database_offline || STATUS == :database_readonly ||
198 (need_api && (STATUS == :api_offline || STATUS == :api_readonly))
200 report_error "Database offline for maintenance", :service_unavailable
202 redirect_to :controller => "site", :action => "offline"
207 def check_api_readable
208 if api_status == :offline
209 report_error "Database offline for maintenance", :service_unavailable
214 def check_api_writable
215 unless api_status == :online
216 report_error "Database offline for maintenance", :service_unavailable
222 if STATUS == :database_offline
224 elsif STATUS == :database_readonly
232 status = database_status
234 if STATUS == :api_offline
236 elsif STATUS == :api_readonly
244 status = database_status
245 status = :offline if status == :online && STATUS == :gpx_offline
249 def require_public_data
250 unless current_user.data_public?
251 report_error "You must make your edits public to upload new data", :forbidden
256 # Report and error to the user
257 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
258 # rather than only a status code and having the web engine make up a
259 # phrase from that, we can also put the error message into the status
260 # message. For now, rails won't let us)
261 def report_error(message, status = :bad_request)
262 # TODO: some sort of escaping of problem characters in the message
263 response.headers["Error"] = message
265 if request.headers["X-Error-Format"]&.casecmp("xml")&.zero?
266 result = OSM::API.new.get_xml_doc
267 result.root.name = "osmError"
268 result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
269 result.root << (XML::Node.new("message") << message)
271 render :xml => result.to_s
273 render :plain => message, :status => status
277 def preferred_languages(reset = false)
278 @preferred_languages = nil if reset
279 @preferred_languages ||= if params[:locale]
280 Locale.list(params[:locale])
282 current_user.preferred_languages
284 Locale.list(http_accept_language.user_preferred_languages)
288 helper_method :preferred_languages
290 def set_locale(reset = false)
291 if current_user&.languages&.empty? && !http_accept_language.user_preferred_languages.empty?
292 current_user.languages = http_accept_language.user_preferred_languages
296 I18n.locale = Locale.available.preferred(preferred_languages(reset))
298 response.headers["Vary"] = "Accept-Language"
299 response.headers["Content-Language"] = I18n.locale.to_s
302 def api_call_handle_error
304 rescue ActiveRecord::RecordNotFound => ex
306 rescue LibXML::XML::Error, ArgumentError => ex
307 report_error ex.message, :bad_request
308 rescue ActiveRecord::RecordInvalid => ex
309 message = "#{ex.record.class} #{ex.record.id}: "
310 ex.record.errors.each { |attr, msg| message << "#{attr}: #{msg} (#{ex.record[attr].inspect})" }
311 report_error message, :bad_request
312 rescue OSM::APIError => ex
313 report_error ex.message, ex.status
314 rescue AbstractController::ActionNotFound => ex
316 rescue StandardError => ex
317 logger.info("API threw unexpected #{ex.class} exception: #{ex.message}")
318 ex.backtrace.each { |l| logger.info(l) }
319 report_error "#{ex.class}: #{ex.message}", :internal_server_error
323 # asserts that the request method is the +method+ given as a parameter
324 # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
325 def assert_method(method)
326 ok = request.send((method.to_s.downcase + "?").to_sym)
327 raise OSM::APIBadMethodError, method unless ok
331 # wrap an api call in a timeout
333 OSM::Timer.timeout(API_TIMEOUT, Timeout::Error) do
336 rescue Timeout::Error
337 raise OSM::APITimeoutError
341 # wrap a web page in a timeout
343 OSM::Timer.timeout(WEB_TIMEOUT, Timeout::Error) do
346 rescue ActionView::Template::Error => ex
349 if ex.is_a?(Timeout::Error) ||
350 (ex.is_a?(ActiveRecord::StatementInvalid) && ex.message =~ /execution expired/)
351 render :action => "timeout"
355 rescue Timeout::Error
356 render :action => "timeout"
360 # ensure that there is a "user" instance variable
362 render_unknown_user params[:display_name] unless @user = User.active.find_by(:display_name => params[:display_name])
366 # render a "no such user" page
367 def render_unknown_user(name)
368 @title = t "users.no_such_user.title"
369 @not_found_user = name
371 respond_to do |format|
372 format.html { render :template => "users/no_such_user", :status => :not_found }
373 format.all { head :not_found }
378 # Unfortunately if a PUT or POST request that has a body fails to
379 # read it then Apache will sometimes fail to return the response it
380 # is given to the client properly, instead erroring:
382 # https://issues.apache.org/bugzilla/show_bug.cgi?id=44782
384 # To work round this we call rewind on the body here, which is added
385 # as a filter, to force it to be fetched from Apache into a file.
391 append_content_security_policy_directives(
392 :child_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
393 :frame_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
394 :connect_src => [NOMINATIM_URL, OVERPASS_URL, OSRM_URL, GRAPHHOPPER_URL],
395 :form_action => %w[render.openstreetmap.org],
396 :style_src => %w['unsafe-inline'],
397 :script_src => [MAPQUEST_DIRECTIONS_URL],
398 :img_src => %w[developer.mapquest.com]
401 if STATUS == :database_offline || STATUS == :api_offline
402 flash.now[:warning] = t("layouts.osm_offline")
403 elsif STATUS == :database_readonly || STATUS == :api_readonly
404 flash.now[:warning] = t("layouts.osm_read_only")
407 request.xhr? ? "xhr" : "map"
410 def allow_thirdparty_images
411 append_content_security_policy_directives(:img_src => %w[*])
415 editor = if params[:editor]
417 elsif current_user&.preferred_editor
418 current_user.preferred_editor
426 helper_method :preferred_editor
429 if defined?(TOTP_KEY)
430 cookies["_osm_totp_token"] = {
431 :value => ROTP::TOTP.new(TOTP_KEY, :interval => 3600).now,
432 :domain => "openstreetmap.org",
433 :expires => 1.hour.from_now
438 def better_errors_allow_inline
441 append_content_security_policy_directives(
442 :script_src => %w['unsafe-inline'],
443 :style_src => %w['unsafe-inline']
450 # Use capabilities from the oauth token if it exists and is a valid access token
451 if Authenticator.new(self, [:token]).allow?
452 Ability.new(nil).merge(Capability.new(current_token))
454 Ability.new(current_user)
458 def deny_access(exception)
459 if @api_deny_access_handling
460 api_deny_access(exception)
462 web_deny_access(exception)
466 def web_deny_access(_exception)
469 report_error t("oauth.permissions.missing"), :forbidden
472 respond_to do |format|
473 format.html { redirect_to :controller => "errors", :action => "forbidden" }
474 format.any { report_error t("application.permission_denied"), :forbidden }
477 respond_to do |format|
478 format.html { redirect_to :controller => "users", :action => "login", :referer => request.fullpath }
479 format.any { head :forbidden }
486 def api_deny_access(_exception)
489 report_error t("oauth.permissions.missing"), :forbidden
493 realm = "Web Password"
494 errormessage = "Couldn't authenticate you"
495 response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
496 render :plain => errormessage, :status => :unauthorized
500 attr_accessor :api_access_handling
502 def api_deny_access_handler
503 @api_deny_access_handling = true
508 # extract authorisation credentials from headers, returns user = nil if none
510 if request.env.key? "X-HTTP_AUTHORIZATION" # where mod_rewrite might have put it
511 authdata = request.env["X-HTTP_AUTHORIZATION"].to_s.split
512 elsif request.env.key? "REDIRECT_X_HTTP_AUTHORIZATION" # mod_fcgi
513 authdata = request.env["REDIRECT_X_HTTP_AUTHORIZATION"].to_s.split
514 elsif request.env.key? "HTTP_AUTHORIZATION" # regular location
515 authdata = request.env["HTTP_AUTHORIZATION"].to_s.split
517 # only basic authentication supported
518 user, pass = Base64.decode64(authdata[1]).split(":", 2) if authdata && authdata[0] == "Basic"
522 # override to stop oauth plugin sending errors
523 def invalid_oauth_response; end