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 # require that the user is a moderator, or fill out a helpful error message
123 # and return them to the index for the controller this is wrapped from.
124 def require_moderator
125 unless current_user.moderator?
127 flash[:error] = t("application.require_moderator.not_a_moderator")
128 redirect_to :action => "index"
136 # sets up the current_user for use by other methods. this is mostly called
137 # from the authorize method, but can be called elsewhere if authorisation
140 # try and setup using OAuth
141 unless Authenticator.new(self, [:token]).allow?
142 username, passwd = get_auth_data # parse from headers
143 # authenticate per-scheme
144 self.current_user = if username.nil?
145 nil # no authentication provided - perhaps first connect (client should retry after 401)
146 elsif username == "token"
147 User.authenticate(:token => passwd) # preferred - random token for user from db, passed in basic auth
149 User.authenticate(:username => username, :password => passwd) # basic auth
153 # have we identified the user?
155 # check if the user has been banned
156 user_block = current_user.blocks.active.take
157 unless user_block.nil?
159 if user_block.zero_hour?
160 report_error t("application.setup_user_auth.blocked_zero_hour"), :forbidden
162 report_error t("application.setup_user_auth.blocked"), :forbidden
166 # if the user hasn't seen the contributor terms then don't
167 # allow editing - they have to go to the web site and see
168 # (but can decline) the CTs to continue.
169 if REQUIRE_TERMS_SEEN && !current_user.terms_seen && flash[:skip_terms].nil?
171 report_error t("application.setup_user_auth.need_to_see_terms"), :forbidden
176 def authorize(realm = "Web Password", errormessage = "Couldn't authenticate you")
177 # make the current_user object from any auth sources we have
180 # handle authenticate pass/fail
182 # no auth, the user does not exist or the password was wrong
183 response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
184 render :plain => errormessage, :status => :unauthorized
190 # to be used as a before_filter *after* authorize. this checks that
191 # the user is a moderator and, if not, returns a forbidden error.
193 # NOTE: this isn't a very good way of doing it - it duplicates logic
194 # from require_moderator - but what we really need to do is a fairly
195 # drastic refactoring based on :format and respond_to? but not a
196 # good idea to do that in this branch.
197 def authorize_moderator(errormessage = "Access restricted to moderators")
198 # check user is a moderator
199 unless current_user.moderator?
200 render :plain => errormessage, :status => :forbidden
205 def check_database_readable(need_api = false)
206 if STATUS == :database_offline || (need_api && STATUS == :api_offline)
208 report_error "Database offline for maintenance", :service_unavailable
210 redirect_to :controller => "site", :action => "offline"
215 def check_database_writable(need_api = false)
216 if STATUS == :database_offline || STATUS == :database_readonly ||
217 (need_api && (STATUS == :api_offline || STATUS == :api_readonly))
219 report_error "Database offline for maintenance", :service_unavailable
221 redirect_to :controller => "site", :action => "offline"
226 def check_api_readable
227 if api_status == :offline
228 report_error "Database offline for maintenance", :service_unavailable
233 def check_api_writable
234 unless api_status == :online
235 report_error "Database offline for maintenance", :service_unavailable
241 if STATUS == :database_offline
243 elsif STATUS == :database_readonly
251 status = database_status
253 if STATUS == :api_offline
255 elsif STATUS == :api_readonly
263 status = database_status
264 status = :offline if status == :online && STATUS == :gpx_offline
268 def require_public_data
269 unless current_user.data_public?
270 report_error "You must make your edits public to upload new data", :forbidden
275 # Report and error to the user
276 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
277 # rather than only a status code and having the web engine make up a
278 # phrase from that, we can also put the error message into the status
279 # message. For now, rails won't let us)
280 def report_error(message, status = :bad_request)
281 # TODO: some sort of escaping of problem characters in the message
282 response.headers["Error"] = message
284 if request.headers["X-Error-Format"]&.casecmp("xml")&.zero?
285 result = OSM::API.new.get_xml_doc
286 result.root.name = "osmError"
287 result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
288 result.root << (XML::Node.new("message") << message)
290 render :xml => result.to_s
292 render :plain => message, :status => status
296 def preferred_languages(reset = false)
297 @preferred_languages = nil if reset
298 @preferred_languages ||= if params[:locale]
299 Locale.list(params[:locale])
301 current_user.preferred_languages
303 Locale.list(http_accept_language.user_preferred_languages)
307 helper_method :preferred_languages
309 def set_locale(reset = false)
310 if current_user&.languages&.empty? && !http_accept_language.user_preferred_languages.empty?
311 current_user.languages = http_accept_language.user_preferred_languages
315 I18n.locale = Locale.available.preferred(preferred_languages(reset))
317 response.headers["Vary"] = "Accept-Language"
318 response.headers["Content-Language"] = I18n.locale.to_s
321 def api_call_handle_error
323 rescue ActiveRecord::RecordNotFound => ex
325 rescue LibXML::XML::Error, ArgumentError => ex
326 report_error ex.message, :bad_request
327 rescue ActiveRecord::RecordInvalid => ex
328 message = "#{ex.record.class} #{ex.record.id}: "
329 ex.record.errors.each { |attr, msg| message << "#{attr}: #{msg} (#{ex.record[attr].inspect})" }
330 report_error message, :bad_request
331 rescue OSM::APIError => ex
332 report_error ex.message, ex.status
333 rescue AbstractController::ActionNotFound => ex
335 rescue StandardError => ex
336 logger.info("API threw unexpected #{ex.class} exception: #{ex.message}")
337 ex.backtrace.each { |l| logger.info(l) }
338 report_error "#{ex.class}: #{ex.message}", :internal_server_error
342 # asserts that the request method is the +method+ given as a parameter
343 # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
344 def assert_method(method)
345 ok = request.send((method.to_s.downcase + "?").to_sym)
346 raise OSM::APIBadMethodError, method unless ok
350 # wrap an api call in a timeout
352 OSM::Timer.timeout(API_TIMEOUT, Timeout::Error) do
355 rescue Timeout::Error
356 raise OSM::APITimeoutError
360 # wrap a web page in a timeout
362 OSM::Timer.timeout(WEB_TIMEOUT, Timeout::Error) do
365 rescue ActionView::Template::Error => ex
368 if ex.is_a?(Timeout::Error) ||
369 (ex.is_a?(ActiveRecord::StatementInvalid) && ex.message =~ /execution expired/)
370 render :action => "timeout"
374 rescue Timeout::Error
375 render :action => "timeout"
379 # ensure that there is a "user" instance variable
381 render_unknown_user params[:display_name] unless @user = User.active.find_by(:display_name => params[:display_name])
385 # render a "no such user" page
386 def render_unknown_user(name)
387 @title = t "users.no_such_user.title"
388 @not_found_user = name
390 respond_to do |format|
391 format.html { render :template => "users/no_such_user", :status => :not_found }
392 format.all { head :not_found }
397 # Unfortunately if a PUT or POST request that has a body fails to
398 # read it then Apache will sometimes fail to return the response it
399 # is given to the client properly, instead erroring:
401 # https://issues.apache.org/bugzilla/show_bug.cgi?id=44782
403 # To work round this we call rewind on the body here, which is added
404 # as a filter, to force it to be fetched from Apache into a file.
410 append_content_security_policy_directives(
411 :child_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
412 :frame_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
413 :connect_src => [NOMINATIM_URL, OVERPASS_URL, OSRM_URL, GRAPHHOPPER_URL],
414 :form_action => %w[render.openstreetmap.org],
415 :script_src => [MAPQUEST_DIRECTIONS_URL],
416 :img_src => %w[developer.mapquest.com]
419 if STATUS == :database_offline || STATUS == :api_offline
420 flash.now[:warning] = t("layouts.osm_offline")
421 elsif STATUS == :database_readonly || STATUS == :api_readonly
422 flash.now[:warning] = t("layouts.osm_read_only")
425 request.xhr? ? "xhr" : "map"
428 def allow_thirdparty_images
429 append_content_security_policy_directives(:img_src => %w[*])
433 editor = if params[:editor]
435 elsif current_user&.preferred_editor
436 current_user.preferred_editor
444 helper_method :preferred_editor
447 if defined?(TOTP_KEY)
448 cookies["_osm_totp_token"] = {
449 :value => ROTP::TOTP.new(TOTP_KEY, :interval => 3600).now,
450 :domain => "openstreetmap.org",
451 :expires => 1.hour.from_now
456 def better_errors_allow_inline
459 append_content_security_policy_directives(
460 :script_src => %w['unsafe-inline'],
461 :style_src => %w['unsafe-inline']
468 # Add in capabilities from the oauth token if it exists and is a valid access token
469 if Authenticator.new(self, [:token]).allow?
470 Ability.new(current_user).merge(Capability.new(current_token))
472 Ability.new(current_user)
476 def deny_access(exception)
477 if @api_deny_access_handling
478 api_deny_access(exception)
480 web_deny_access(exception)
484 def web_deny_access(_exception)
487 report_error t("oauth.permissions.missing"), :forbidden
490 respond_to do |format|
491 format.html { redirect_to :controller => "errors", :action => "forbidden" }
492 format.any { report_error t("application.permission_denied"), :forbidden }
495 respond_to do |format|
496 format.html { redirect_to :controller => "users", :action => "login", :referer => request.fullpath }
497 format.any { head :forbidden }
504 def api_deny_access(_exception)
507 report_error t("oauth.permissions.missing"), :forbidden
511 realm = "Web Password"
512 errormessage = "Couldn't authenticate you"
513 response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
514 render :plain => errormessage, :status => :unauthorized
518 attr_accessor :api_access_handling
520 def api_deny_access_handler
521 @api_deny_access_handling = true
526 # extract authorisation credentials from headers, returns user = nil if none
528 if request.env.key? "X-HTTP_AUTHORIZATION" # where mod_rewrite might have put it
529 authdata = request.env["X-HTTP_AUTHORIZATION"].to_s.split
530 elsif request.env.key? "REDIRECT_X_HTTP_AUTHORIZATION" # mod_fcgi
531 authdata = request.env["REDIRECT_X_HTTP_AUTHORIZATION"].to_s.split
532 elsif request.env.key? "HTTP_AUTHORIZATION" # regular location
533 authdata = request.env["HTTP_AUTHORIZATION"].to_s.split
535 # only basic authentication supported
536 user, pass = Base64.decode64(authdata[1]).split(":", 2) if authdata && authdata[0] == "Basic"
540 # override to stop oauth plugin sending errors
541 def invalid_oauth_response; end