1 class ApplicationController < ActionController::Base
2 include SessionPersistence
6 before_action :fetch_body
10 @user = User.where(:id => session[:user]).where("status IN ('active', 'confirmed', 'suspended')").first
12 if @user.status == "suspended"
14 session_expires_automatically
16 redirect_to :controller => "user", :action => "suspended"
18 # don't allow access to any auth-requiring part of the site unless
19 # the new CTs have been seen (and accept/decline chosen).
20 elsif !@user.terms_seen && flash[:skip_terms].nil?
21 flash[:notice] = t "user.terms.you need to accept or decline"
23 redirect_to :controller => "user", :action => "terms", :referer => params[:referer]
25 redirect_to :controller => "user", :action => "terms", :referer => request.fullpath
29 if @user = User.authenticate(:token => session[:token])
30 session[:user] = @user.id
33 rescue StandardError => ex
34 logger.info("Exception authorizing user: #{ex}")
42 redirect_to :controller => "user", :action => "login", :referer => request.fullpath
50 @oauth = @user.access_token(OAUTH_KEY) if @user && defined? OAUTH_KEY
54 # requires the user to be logged in by the token or HTTP methods, or have an
55 # OAuth token with the right capability. this method is a bit of a pain to call
56 # directly, since it's cumbersome to call filters with arguments in rails. to
57 # make it easier to read and write the code, there are some utility methods
59 def require_capability(cap)
60 # when the current token is nil, it means the user logged in with a different
61 # method, otherwise an OAuth token was used, which has to be checked.
62 unless current_token.nil?
63 unless current_token.read_attribute(cap)
65 report_error t("oauth.permissions.missing"), :forbidden
72 # require the user to have cookies enabled in their browser
74 if request.cookies["_osm_session"].to_s == ""
75 if params[:cookie_test].nil?
76 session[:cookie_test] = true
77 redirect_to Hash[params].merge(:cookie_test => "true")
80 flash.now[:warning] = t "application.require_cookies.cookies_needed"
83 session.delete(:cookie_test)
87 # Utility methods to make the controller filter methods easier to read and write.
88 def require_allow_read_prefs
89 require_capability(:allow_read_prefs)
92 def require_allow_write_prefs
93 require_capability(:allow_write_prefs)
96 def require_allow_write_diary
97 require_capability(:allow_write_diary)
100 def require_allow_write_api
101 require_capability(:allow_write_api)
103 if REQUIRE_TERMS_AGREED && @user.terms_agreed.nil?
104 report_error "You must accept the contributor terms before you can edit.", :forbidden
109 def require_allow_read_gpx
110 require_capability(:allow_read_gpx)
113 def require_allow_write_gpx
114 require_capability(:allow_write_gpx)
117 def require_allow_write_notes
118 require_capability(:allow_write_notes)
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 @user.moderator?
127 flash[:error] = t("application.require_moderator.not_a_moderator")
128 redirect_to :action => "index"
136 # sets up the @user object 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 @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 = @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 && !@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 @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 @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 @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"] &&
285 request.headers["X-Error-Format"].casecmp("xml").zero?
286 result = OSM::API.new.get_xml_doc
287 result.root.name = "osmError"
288 result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
289 result.root << (XML::Node.new("message") << message)
291 render :xml => result.to_s
293 render :plain => message, :status => status
297 def preferred_languages
298 @languages ||= if params[:locale]
299 Locale.list(params[:locale])
301 @user.preferred_languages
303 Locale.list(http_accept_language.user_preferred_languages)
307 helper_method :preferred_languages
310 if @user && @user.languages.empty? && !http_accept_language.user_preferred_languages.empty?
311 @user.languages = http_accept_language.user_preferred_languages
315 I18n.locale = Locale.available.preferred(preferred_languages)
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.new(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
366 ex = ex.original_exception
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 "this_user" instance variable
381 unless @this_user = User.active.find_by(:display_name => params[:display_name])
382 render_unknown_user params[:display_name]
387 # render a "no such user" page
388 def render_unknown_user(name)
389 @title = t "user.no_such_user.title"
390 @not_found_user = name
392 respond_to do |format|
393 format.html { render :template => "user/no_such_user", :status => :not_found }
394 format.all { head :not_found }
399 # Unfortunately if a PUT or POST request that has a body fails to
400 # read it then Apache will sometimes fail to return the response it
401 # is given to the client properly, instead erroring:
403 # https://issues.apache.org/bugzilla/show_bug.cgi?id=44782
405 # To work round this we call rewind on the body here, which is added
406 # as a filter, to force it to be fetched from Apache into a file.
412 append_content_security_policy_directives(
413 :connect_src => %w[nominatim.openstreetmap.org overpass-api.de router.project-osrm.org valhalla.mapzen.com],
414 :script_src => %w[graphhopper.com open.mapquestapi.com],
415 :img_src => %w[developer.mapquest.com]
418 if STATUS == :database_offline || STATUS == :api_offline
419 flash.now[:warning] = t("layouts.osm_offline")
420 elsif STATUS == :database_readonly || STATUS == :api_readonly
421 flash.now[:warning] = t("layouts.osm_read_only")
424 request.xhr? ? "xhr" : "map"
428 editor = if params[:editor]
430 elsif @user && @user.preferred_editor
431 @user.preferred_editor
439 helper_method :preferred_editor
442 if defined?(TOTP_KEY)
443 cookies["_osm_totp_token"] = {
444 :value => ROTP::TOTP.new(TOTP_KEY, :interval => 3600).now,
445 :domain => "openstreetmap.org",
446 :expires => 1.hour.from_now
453 # extract authorisation credentials from headers, returns user = nil if none
455 if request.env.key? "X-HTTP_AUTHORIZATION" # where mod_rewrite might have put it
456 authdata = request.env["X-HTTP_AUTHORIZATION"].to_s.split
457 elsif request.env.key? "REDIRECT_X_HTTP_AUTHORIZATION" # mod_fcgi
458 authdata = request.env["REDIRECT_X_HTTP_AUTHORIZATION"].to_s.split
459 elsif request.env.key? "HTTP_AUTHORIZATION" # regular location
460 authdata = request.env["HTTP_AUTHORIZATION"].to_s.split
462 # only basic authentication supported
463 if authdata && authdata[0] == "Basic"
464 user, pass = Base64.decode64(authdata[1]).split(":", 2)
469 # used by oauth plugin to get the current user
474 # used by oauth plugin to set the current user
475 def current_user=(user)
479 # override to stop oauth plugin sending errors
480 def invalid_oauth_response; end