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
17 self.current_user = User.where(:id => session[:user]).where("status IN ('active', 'confirmed', 'suspended')").first
19 if current_user.status == "suspended"
21 session_expires_automatically
23 redirect_to :controller => "users", :action => "suspended"
25 # don't allow access to any auth-requiring part of the site unless
26 # the new CTs have been seen (and accept/decline chosen).
27 elsif !current_user.terms_seen && flash[:skip_terms].nil?
28 flash[:notice] = t "users.terms.you need to accept or decline"
30 redirect_to :controller => "users", :action => "terms", :referer => params[:referer]
32 redirect_to :controller => "users", :action => "terms", :referer => request.fullpath
36 session[:user] = current_user.id if self.current_user = User.authenticate(:token => session[:token])
38 rescue StandardError => ex
39 logger.info("Exception authorizing user: #{ex}")
41 self.current_user = nil
47 redirect_to :controller => "users", :action => "login", :referer => request.fullpath
55 @oauth = current_user.access_token(OAUTH_KEY) if current_user && defined? OAUTH_KEY
59 # requires the user to be logged in by the token or HTTP methods, or have an
60 # OAuth token with the right capability. this method is a bit of a pain to call
61 # directly, since it's cumbersome to call filters with arguments in rails. to
62 # make it easier to read and write the code, there are some utility methods
64 def require_capability(cap)
65 # when the current token is nil, it means the user logged in with a different
66 # method, otherwise an OAuth token was used, which has to be checked.
67 unless current_token.nil?
68 unless current_token.read_attribute(cap)
70 report_error t("oauth.permissions.missing"), :forbidden
77 # require the user to have cookies enabled in their browser
79 if request.cookies["_osm_session"].to_s == ""
80 if params[:cookie_test].nil?
81 session[:cookie_test] = true
82 redirect_to params.to_unsafe_h.merge(:cookie_test => "true")
85 flash.now[:warning] = t "application.require_cookies.cookies_needed"
88 session.delete(:cookie_test)
92 # Utility methods to make the controller filter methods easier to read and write.
93 def require_allow_read_prefs
94 require_capability(:allow_read_prefs)
97 def require_allow_write_prefs
98 require_capability(:allow_write_prefs)
101 def require_allow_write_diary
102 require_capability(:allow_write_diary)
105 def require_allow_write_api
106 require_capability(:allow_write_api)
108 if REQUIRE_TERMS_AGREED && current_user.terms_agreed.nil?
109 report_error "You must accept the contributor terms before you can edit.", :forbidden
114 def require_allow_read_gpx
115 require_capability(:allow_read_gpx)
118 def require_allow_write_gpx
119 require_capability(:allow_write_gpx)
123 # sets up the current_user for use by other methods. this is mostly called
124 # from the authorize method, but can be called elsewhere if authorisation
127 # try and setup using OAuth
128 unless Authenticator.new(self, [:token]).allow?
129 username, passwd = get_auth_data # parse from headers
130 # authenticate per-scheme
131 self.current_user = if username.nil?
132 nil # no authentication provided - perhaps first connect (client should retry after 401)
133 elsif username == "token"
134 User.authenticate(:token => passwd) # preferred - random token for user from db, passed in basic auth
136 User.authenticate(:username => username, :password => passwd) # basic auth
140 # have we identified the user?
142 # check if the user has been banned
143 user_block = current_user.blocks.active.take
144 unless user_block.nil?
146 if user_block.zero_hour?
147 report_error t("application.setup_user_auth.blocked_zero_hour"), :forbidden
149 report_error t("application.setup_user_auth.blocked"), :forbidden
153 # if the user hasn't seen the contributor terms then don't
154 # allow editing - they have to go to the web site and see
155 # (but can decline) the CTs to continue.
156 if REQUIRE_TERMS_SEEN && !current_user.terms_seen && flash[:skip_terms].nil?
158 report_error t("application.setup_user_auth.need_to_see_terms"), :forbidden
163 def authorize(realm = "Web Password", errormessage = "Couldn't authenticate you")
164 # make the current_user object from any auth sources we have
167 # handle authenticate pass/fail
169 # no auth, the user does not exist or the password was wrong
170 response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
171 render :plain => errormessage, :status => :unauthorized
177 # to be used as a before_filter *after* authorize. this checks that
178 # the user is a moderator and, if not, returns a forbidden error.
179 def authorize_moderator(errormessage = "Access restricted to moderators")
180 # check user is a moderator
181 unless current_user.moderator?
182 render :plain => errormessage, :status => :forbidden
187 def check_database_readable(need_api = false)
188 if STATUS == :database_offline || (need_api && STATUS == :api_offline)
190 report_error "Database offline for maintenance", :service_unavailable
192 redirect_to :controller => "site", :action => "offline"
197 def check_database_writable(need_api = false)
198 if STATUS == :database_offline || STATUS == :database_readonly ||
199 (need_api && (STATUS == :api_offline || STATUS == :api_readonly))
201 report_error "Database offline for maintenance", :service_unavailable
203 redirect_to :controller => "site", :action => "offline"
208 def check_api_readable
209 if api_status == :offline
210 report_error "Database offline for maintenance", :service_unavailable
215 def check_api_writable
216 unless api_status == :online
217 report_error "Database offline for maintenance", :service_unavailable
223 if STATUS == :database_offline
225 elsif STATUS == :database_readonly
233 status = database_status
235 if STATUS == :api_offline
237 elsif STATUS == :api_readonly
245 status = database_status
246 status = :offline if status == :online && STATUS == :gpx_offline
250 def require_public_data
251 unless current_user.data_public?
252 report_error "You must make your edits public to upload new data", :forbidden
257 # Report and error to the user
258 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
259 # rather than only a status code and having the web engine make up a
260 # phrase from that, we can also put the error message into the status
261 # message. For now, rails won't let us)
262 def report_error(message, status = :bad_request)
263 # TODO: some sort of escaping of problem characters in the message
264 response.headers["Error"] = message
266 if request.headers["X-Error-Format"]&.casecmp("xml")&.zero?
267 result = OSM::API.new.get_xml_doc
268 result.root.name = "osmError"
269 result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
270 result.root << (XML::Node.new("message") << message)
272 render :xml => result.to_s
274 render :plain => message, :status => status
278 def preferred_languages(reset = false)
279 @preferred_languages = nil if reset
280 @preferred_languages ||= if params[:locale]
281 Locale.list(params[:locale])
283 current_user.preferred_languages
285 Locale.list(http_accept_language.user_preferred_languages)
289 helper_method :preferred_languages
291 def set_locale(reset = false)
292 if current_user&.languages&.empty? && !http_accept_language.user_preferred_languages.empty?
293 current_user.languages = http_accept_language.user_preferred_languages
297 I18n.locale = Locale.available.preferred(preferred_languages(reset))
299 response.headers["Vary"] = "Accept-Language"
300 response.headers["Content-Language"] = I18n.locale.to_s
303 def api_call_handle_error
305 rescue ActiveRecord::RecordNotFound => ex
307 rescue LibXML::XML::Error, ArgumentError => ex
308 report_error ex.message, :bad_request
309 rescue ActiveRecord::RecordInvalid => ex
310 message = "#{ex.record.class} #{ex.record.id}: "
311 ex.record.errors.each { |attr, msg| message << "#{attr}: #{msg} (#{ex.record[attr].inspect})" }
312 report_error message, :bad_request
313 rescue OSM::APIError => ex
314 report_error ex.message, ex.status
315 rescue AbstractController::ActionNotFound => ex
317 rescue StandardError => ex
318 logger.info("API threw unexpected #{ex.class} exception: #{ex.message}")
319 ex.backtrace.each { |l| logger.info(l) }
320 report_error "#{ex.class}: #{ex.message}", :internal_server_error
324 # asserts that the request method is the +method+ given as a parameter
325 # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
326 def assert_method(method)
327 ok = request.send((method.to_s.downcase + "?").to_sym)
328 raise OSM::APIBadMethodError, method unless ok
332 # wrap an api call in a timeout
334 OSM::Timer.timeout(API_TIMEOUT, Timeout::Error) do
337 rescue Timeout::Error
338 raise OSM::APITimeoutError
342 # wrap a web page in a timeout
344 OSM::Timer.timeout(WEB_TIMEOUT, Timeout::Error) do
347 rescue ActionView::Template::Error => ex
350 if ex.is_a?(Timeout::Error) ||
351 (ex.is_a?(ActiveRecord::StatementInvalid) && ex.message =~ /execution expired/)
352 render :action => "timeout"
356 rescue Timeout::Error
357 render :action => "timeout"
361 # ensure that there is a "user" instance variable
363 render_unknown_user params[:display_name] unless @user = User.active.find_by(:display_name => params[:display_name])
367 # render a "no such user" page
368 def render_unknown_user(name)
369 @title = t "users.no_such_user.title"
370 @not_found_user = name
372 respond_to do |format|
373 format.html { render :template => "users/no_such_user", :status => :not_found }
374 format.all { head :not_found }
379 # Unfortunately if a PUT or POST request that has a body fails to
380 # read it then Apache will sometimes fail to return the response it
381 # is given to the client properly, instead erroring:
383 # https://issues.apache.org/bugzilla/show_bug.cgi?id=44782
385 # To work round this we call rewind on the body here, which is added
386 # as a filter, to force it to be fetched from Apache into a file.
392 append_content_security_policy_directives(
393 :child_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
394 :frame_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
395 :connect_src => [NOMINATIM_URL, OVERPASS_URL, OSRM_URL, GRAPHHOPPER_URL],
396 :form_action => %w[render.openstreetmap.org],
397 :style_src => %w['unsafe-inline'],
398 :script_src => [MAPQUEST_DIRECTIONS_URL],
399 :img_src => %w[developer.mapquest.com]
402 if STATUS == :database_offline || STATUS == :api_offline
403 flash.now[:warning] = t("layouts.osm_offline")
404 elsif STATUS == :database_readonly || STATUS == :api_readonly
405 flash.now[:warning] = t("layouts.osm_read_only")
408 request.xhr? ? "xhr" : "map"
411 def allow_thirdparty_images
412 append_content_security_policy_directives(:img_src => %w[*])
416 editor = if params[:editor]
418 elsif current_user&.preferred_editor
419 current_user.preferred_editor
427 helper_method :preferred_editor
430 if defined?(TOTP_KEY)
431 cookies["_osm_totp_token"] = {
432 :value => ROTP::TOTP.new(TOTP_KEY, :interval => 3600).now,
433 :domain => "openstreetmap.org",
434 :expires => 1.hour.from_now
439 def better_errors_allow_inline
442 append_content_security_policy_directives(
443 :script_src => %w['unsafe-inline'],
444 :style_src => %w['unsafe-inline']
451 # Use capabilities from the oauth token if it exists and is a valid access token
452 if Authenticator.new(self, [:token]).allow?
453 Ability.new(nil).merge(Capability.new(current_token))
455 Ability.new(current_user)
459 def deny_access(exception)
460 if @api_deny_access_handling
461 api_deny_access(exception)
463 web_deny_access(exception)
467 def web_deny_access(_exception)
470 report_error t("oauth.permissions.missing"), :forbidden
473 respond_to do |format|
474 format.html { redirect_to :controller => "errors", :action => "forbidden" }
475 format.any { report_error t("application.permission_denied"), :forbidden }
478 respond_to do |format|
479 format.html { redirect_to :controller => "users", :action => "login", :referer => request.fullpath }
480 format.any { head :forbidden }
487 def api_deny_access(_exception)
490 report_error t("oauth.permissions.missing"), :forbidden
494 realm = "Web Password"
495 errormessage = "Couldn't authenticate you"
496 response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
497 render :plain => errormessage, :status => :unauthorized
501 attr_accessor :api_access_handling
503 def api_deny_access_handler
504 @api_deny_access_handling = true
509 # extract authorisation credentials from headers, returns user = nil if none
511 if request.env.key? "X-HTTP_AUTHORIZATION" # where mod_rewrite might have put it
512 authdata = request.env["X-HTTP_AUTHORIZATION"].to_s.split
513 elsif request.env.key? "REDIRECT_X_HTTP_AUTHORIZATION" # mod_fcgi
514 authdata = request.env["REDIRECT_X_HTTP_AUTHORIZATION"].to_s.split
515 elsif request.env.key? "HTTP_AUTHORIZATION" # regular location
516 authdata = request.env["HTTP_AUTHORIZATION"].to_s.split
518 # only basic authentication supported
519 user, pass = Base64.decode64(authdata[1]).split(":", 2) if authdata && authdata[0] == "Basic"
523 # override to stop oauth plugin sending errors
524 def invalid_oauth_response; end