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)
121 def require_allow_write_notes
122 require_capability(:allow_write_notes)
126 # require that the user is a moderator, or fill out a helpful error message
127 # and return them to the index for the controller this is wrapped from.
128 def require_moderator
129 unless current_user.moderator?
131 flash[:error] = t("application.require_moderator.not_a_moderator")
132 redirect_to :action => "index"
140 # sets up the current_user for use by other methods. this is mostly called
141 # from the authorize method, but can be called elsewhere if authorisation
144 # try and setup using OAuth
145 unless Authenticator.new(self, [:token]).allow?
146 username, passwd = get_auth_data # parse from headers
147 # authenticate per-scheme
148 self.current_user = if username.nil?
149 nil # no authentication provided - perhaps first connect (client should retry after 401)
150 elsif username == "token"
151 User.authenticate(:token => passwd) # preferred - random token for user from db, passed in basic auth
153 User.authenticate(:username => username, :password => passwd) # basic auth
157 # have we identified the user?
159 # check if the user has been banned
160 user_block = current_user.blocks.active.take
161 unless user_block.nil?
163 if user_block.zero_hour?
164 report_error t("application.setup_user_auth.blocked_zero_hour"), :forbidden
166 report_error t("application.setup_user_auth.blocked"), :forbidden
170 # if the user hasn't seen the contributor terms then don't
171 # allow editing - they have to go to the web site and see
172 # (but can decline) the CTs to continue.
173 if REQUIRE_TERMS_SEEN && !current_user.terms_seen && flash[:skip_terms].nil?
175 report_error t("application.setup_user_auth.need_to_see_terms"), :forbidden
180 def authorize(realm = "Web Password", errormessage = "Couldn't authenticate you")
181 # make the current_user object from any auth sources we have
184 # handle authenticate pass/fail
186 # no auth, the user does not exist or the password was wrong
187 response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
188 render :plain => errormessage, :status => :unauthorized
194 # to be used as a before_filter *after* authorize. this checks that
195 # the user is a moderator and, if not, returns a forbidden error.
197 # NOTE: this isn't a very good way of doing it - it duplicates logic
198 # from require_moderator - but what we really need to do is a fairly
199 # drastic refactoring based on :format and respond_to? but not a
200 # good idea to do that in this branch.
201 def authorize_moderator(errormessage = "Access restricted to moderators")
202 # check user is a moderator
203 unless current_user.moderator?
204 render :plain => errormessage, :status => :forbidden
209 def check_database_readable(need_api = false)
210 if STATUS == :database_offline || (need_api && STATUS == :api_offline)
212 report_error "Database offline for maintenance", :service_unavailable
214 redirect_to :controller => "site", :action => "offline"
219 def check_database_writable(need_api = false)
220 if STATUS == :database_offline || STATUS == :database_readonly ||
221 (need_api && (STATUS == :api_offline || STATUS == :api_readonly))
223 report_error "Database offline for maintenance", :service_unavailable
225 redirect_to :controller => "site", :action => "offline"
230 def check_api_readable
231 if api_status == :offline
232 report_error "Database offline for maintenance", :service_unavailable
237 def check_api_writable
238 unless api_status == :online
239 report_error "Database offline for maintenance", :service_unavailable
245 if STATUS == :database_offline
247 elsif STATUS == :database_readonly
255 status = database_status
257 if STATUS == :api_offline
259 elsif STATUS == :api_readonly
267 status = database_status
268 status = :offline if status == :online && STATUS == :gpx_offline
272 def require_public_data
273 unless current_user.data_public?
274 report_error "You must make your edits public to upload new data", :forbidden
279 # Report and error to the user
280 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
281 # rather than only a status code and having the web engine make up a
282 # phrase from that, we can also put the error message into the status
283 # message. For now, rails won't let us)
284 def report_error(message, status = :bad_request)
285 # TODO: some sort of escaping of problem characters in the message
286 response.headers["Error"] = message
288 if request.headers["X-Error-Format"]&.casecmp("xml")&.zero?
289 result = OSM::API.new.get_xml_doc
290 result.root.name = "osmError"
291 result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
292 result.root << (XML::Node.new("message") << message)
294 render :xml => result.to_s
296 render :plain => message, :status => status
300 def preferred_languages(reset = false)
301 @preferred_languages = nil if reset
302 @preferred_languages ||= if params[:locale]
303 Locale.list(params[:locale])
305 current_user.preferred_languages
307 Locale.list(http_accept_language.user_preferred_languages)
311 helper_method :preferred_languages
313 def set_locale(reset = false)
314 if current_user&.languages&.empty? && !http_accept_language.user_preferred_languages.empty?
315 current_user.languages = http_accept_language.user_preferred_languages
319 I18n.locale = Locale.available.preferred(preferred_languages(reset))
321 response.headers["Vary"] = "Accept-Language"
322 response.headers["Content-Language"] = I18n.locale.to_s
325 def api_call_handle_error
327 rescue ActiveRecord::RecordNotFound => ex
329 rescue LibXML::XML::Error, ArgumentError => ex
330 report_error ex.message, :bad_request
331 rescue ActiveRecord::RecordInvalid => ex
332 message = "#{ex.record.class} #{ex.record.id}: "
333 ex.record.errors.each { |attr, msg| message << "#{attr}: #{msg} (#{ex.record[attr].inspect})" }
334 report_error message, :bad_request
335 rescue OSM::APIError => ex
336 report_error ex.message, ex.status
337 rescue AbstractController::ActionNotFound => ex
339 rescue StandardError => ex
340 logger.info("API threw unexpected #{ex.class} exception: #{ex.message}")
341 ex.backtrace.each { |l| logger.info(l) }
342 report_error "#{ex.class}: #{ex.message}", :internal_server_error
346 # asserts that the request method is the +method+ given as a parameter
347 # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
348 def assert_method(method)
349 ok = request.send((method.to_s.downcase + "?").to_sym)
350 raise OSM::APIBadMethodError, method unless ok
354 # wrap an api call in a timeout
356 OSM::Timer.timeout(API_TIMEOUT, Timeout::Error) do
359 rescue Timeout::Error
360 raise OSM::APITimeoutError
364 # wrap a web page in a timeout
366 OSM::Timer.timeout(WEB_TIMEOUT, Timeout::Error) do
369 rescue ActionView::Template::Error => ex
372 if ex.is_a?(Timeout::Error) ||
373 (ex.is_a?(ActiveRecord::StatementInvalid) && ex.message =~ /execution expired/)
374 render :action => "timeout"
378 rescue Timeout::Error
379 render :action => "timeout"
383 # ensure that there is a "user" instance variable
385 render_unknown_user params[:display_name] unless @user = User.active.find_by(:display_name => params[:display_name])
389 # render a "no such user" page
390 def render_unknown_user(name)
391 @title = t "users.no_such_user.title"
392 @not_found_user = name
394 respond_to do |format|
395 format.html { render :template => "users/no_such_user", :status => :not_found }
396 format.all { head :not_found }
401 # Unfortunately if a PUT or POST request that has a body fails to
402 # read it then Apache will sometimes fail to return the response it
403 # is given to the client properly, instead erroring:
405 # https://issues.apache.org/bugzilla/show_bug.cgi?id=44782
407 # To work round this we call rewind on the body here, which is added
408 # as a filter, to force it to be fetched from Apache into a file.
414 append_content_security_policy_directives(
415 :child_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
416 :frame_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
417 :connect_src => %w[nominatim.openstreetmap.org overpass-api.de router.project-osrm.org graphhopper.com],
418 :form_action => %w[render.openstreetmap.org],
419 :script_src => %w[open.mapquestapi.com],
420 :img_src => %w[developer.mapquest.com]
423 if STATUS == :database_offline || STATUS == :api_offline
424 flash.now[:warning] = t("layouts.osm_offline")
425 elsif STATUS == :database_readonly || STATUS == :api_readonly
426 flash.now[:warning] = t("layouts.osm_read_only")
429 request.xhr? ? "xhr" : "map"
432 def allow_thirdparty_images
433 append_content_security_policy_directives(:img_src => %w[*])
437 editor = if params[:editor]
439 elsif current_user&.preferred_editor
440 current_user.preferred_editor
448 helper_method :preferred_editor
451 if defined?(TOTP_KEY)
452 cookies["_osm_totp_token"] = {
453 :value => ROTP::TOTP.new(TOTP_KEY, :interval => 3600).now,
454 :domain => "openstreetmap.org",
455 :expires => 1.hour.from_now
460 def better_errors_allow_inline
463 append_content_security_policy_directives(
464 :script_src => %w['unsafe-inline'],
465 :style_src => %w['unsafe-inline']
472 # Add in capabilities from the oauth token if it exists and is a valid access token
473 if Authenticator.new(self, [:token]).allow?
474 Ability.new(current_user).merge(Capability.new(current_token))
476 Ability.new(current_user)
480 def deny_access(_exception)
483 report_error t("oauth.permissions.missing"), :forbidden
486 report_error t("application.permission_denied"), :forbidden
488 redirect_to :controller => "users", :action => "login", :referer => request.fullpath
496 # extract authorisation credentials from headers, returns user = nil if none
498 if request.env.key? "X-HTTP_AUTHORIZATION" # where mod_rewrite might have put it
499 authdata = request.env["X-HTTP_AUTHORIZATION"].to_s.split
500 elsif request.env.key? "REDIRECT_X_HTTP_AUTHORIZATION" # mod_fcgi
501 authdata = request.env["REDIRECT_X_HTTP_AUTHORIZATION"].to_s.split
502 elsif request.env.key? "HTTP_AUTHORIZATION" # regular location
503 authdata = request.env["HTTP_AUTHORIZATION"].to_s.split
505 # only basic authentication supported
506 user, pass = Base64.decode64(authdata[1]).split(":", 2) if authdata && authdata[0] == "Basic"
510 # override to stop oauth plugin sending errors
511 def invalid_oauth_response; end