1 class ApplicationController < ActionController::Base
2 include SessionPersistence
5 protect_from_forgery :with => :exception
7 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 => "user", :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 "user.terms.you need to accept or decline"
30 redirect_to :controller => "user", :action => "terms", :referer => params[:referer]
32 redirect_to :controller => "user", :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 => "user", :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)
122 def require_allow_write_notes
123 require_capability(:allow_write_notes)
127 # require that the user is a moderator, or fill out a helpful error message
128 # and return them to the index for the controller this is wrapped from.
129 def require_moderator
130 unless current_user.moderator?
132 flash[:error] = t("application.require_moderator.not_a_moderator")
133 redirect_to :action => "index"
141 # sets up the current_user for use by other methods. this is mostly called
142 # from the authorize method, but can be called elsewhere if authorisation
145 # try and setup using OAuth
146 unless Authenticator.new(self, [:token]).allow?
147 username, passwd = get_auth_data # parse from headers
148 # authenticate per-scheme
149 self.current_user = if username.nil?
150 nil # no authentication provided - perhaps first connect (client should retry after 401)
151 elsif username == "token"
152 User.authenticate(:token => passwd) # preferred - random token for user from db, passed in basic auth
154 User.authenticate(:username => username, :password => passwd) # basic auth
158 # have we identified the user?
160 # check if the user has been banned
161 user_block = current_user.blocks.active.take
162 unless user_block.nil?
164 if user_block.zero_hour?
165 report_error t("application.setup_user_auth.blocked_zero_hour"), :forbidden
167 report_error t("application.setup_user_auth.blocked"), :forbidden
171 # if the user hasn't seen the contributor terms then don't
172 # allow editing - they have to go to the web site and see
173 # (but can decline) the CTs to continue.
174 if REQUIRE_TERMS_SEEN && !current_user.terms_seen && flash[:skip_terms].nil?
176 report_error t("application.setup_user_auth.need_to_see_terms"), :forbidden
181 def authorize(realm = "Web Password", errormessage = "Couldn't authenticate you")
182 # make the current_user object from any auth sources we have
185 # handle authenticate pass/fail
187 # no auth, the user does not exist or the password was wrong
188 response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
189 render :plain => errormessage, :status => :unauthorized
195 # to be used as a before_filter *after* authorize. this checks that
196 # the user is a moderator and, if not, returns a forbidden error.
198 # NOTE: this isn't a very good way of doing it - it duplicates logic
199 # from require_moderator - but what we really need to do is a fairly
200 # drastic refactoring based on :format and respond_to? but not a
201 # good idea to do that in this branch.
202 def authorize_moderator(errormessage = "Access restricted to moderators")
203 # check user is a moderator
204 unless current_user.moderator?
205 render :plain => errormessage, :status => :forbidden
210 def check_database_readable(need_api = false)
211 if STATUS == :database_offline || (need_api && STATUS == :api_offline)
213 report_error "Database offline for maintenance", :service_unavailable
215 redirect_to :controller => "site", :action => "offline"
220 def check_database_writable(need_api = false)
221 if STATUS == :database_offline || STATUS == :database_readonly ||
222 (need_api && (STATUS == :api_offline || STATUS == :api_readonly))
224 report_error "Database offline for maintenance", :service_unavailable
226 redirect_to :controller => "site", :action => "offline"
231 def check_api_readable
232 if api_status == :offline
233 report_error "Database offline for maintenance", :service_unavailable
238 def check_api_writable
239 unless api_status == :online
240 report_error "Database offline for maintenance", :service_unavailable
246 if STATUS == :database_offline
248 elsif STATUS == :database_readonly
256 status = database_status
258 if STATUS == :api_offline
260 elsif STATUS == :api_readonly
268 status = database_status
269 status = :offline if status == :online && STATUS == :gpx_offline
273 def require_public_data
274 unless current_user.data_public?
275 report_error "You must make your edits public to upload new data", :forbidden
280 # Report and error to the user
281 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
282 # rather than only a status code and having the web engine make up a
283 # phrase from that, we can also put the error message into the status
284 # message. For now, rails won't let us)
285 def report_error(message, status = :bad_request)
286 # TODO: some sort of escaping of problem characters in the message
287 response.headers["Error"] = message
289 if request.headers["X-Error-Format"] &&
290 request.headers["X-Error-Format"].casecmp("xml").zero?
291 result = OSM::API.new.get_xml_doc
292 result.root.name = "osmError"
293 result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
294 result.root << (XML::Node.new("message") << message)
296 render :xml => result.to_s
298 render :plain => message, :status => status
302 def preferred_languages(reset = false)
303 @preferred_languages = nil if reset
304 @preferred_languages ||= if params[:locale]
305 Locale.list(params[:locale])
307 current_user.preferred_languages
309 Locale.list(http_accept_language.user_preferred_languages)
313 helper_method :preferred_languages
315 def set_locale(reset = false)
316 if current_user && current_user.languages.empty? && !http_accept_language.user_preferred_languages.empty?
317 current_user.languages = http_accept_language.user_preferred_languages
321 I18n.locale = Locale.available.preferred(preferred_languages(reset))
323 response.headers["Vary"] = "Accept-Language"
324 response.headers["Content-Language"] = I18n.locale.to_s
327 def api_call_handle_error
329 rescue ActiveRecord::RecordNotFound => ex
331 rescue LibXML::XML::Error, ArgumentError => ex
332 report_error ex.message, :bad_request
333 rescue ActiveRecord::RecordInvalid => ex
334 message = "#{ex.record.class} #{ex.record.id}: "
335 ex.record.errors.each { |attr, msg| message << "#{attr}: #{msg} (#{ex.record[attr].inspect})" }
336 report_error message, :bad_request
337 rescue OSM::APIError => ex
338 report_error ex.message, ex.status
339 rescue AbstractController::ActionNotFound => ex
341 rescue StandardError => ex
342 logger.info("API threw unexpected #{ex.class} exception: #{ex.message}")
343 ex.backtrace.each { |l| logger.info(l) }
344 report_error "#{ex.class}: #{ex.message}", :internal_server_error
348 # asserts that the request method is the +method+ given as a parameter
349 # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
350 def assert_method(method)
351 ok = request.send((method.to_s.downcase + "?").to_sym)
352 raise OSM::APIBadMethodError, method unless ok
356 # wrap an api call in a timeout
358 OSM::Timer.timeout(API_TIMEOUT, Timeout::Error) do
361 rescue Timeout::Error
362 raise OSM::APITimeoutError
366 # wrap a web page in a timeout
368 OSM::Timer.timeout(WEB_TIMEOUT, Timeout::Error) do
371 rescue ActionView::Template::Error => ex
374 if ex.is_a?(Timeout::Error) ||
375 (ex.is_a?(ActiveRecord::StatementInvalid) && ex.message =~ /execution expired/)
376 render :action => "timeout"
380 rescue Timeout::Error
381 render :action => "timeout"
385 # ensure that there is a "user" instance variable
387 render_unknown_user params[:display_name] unless @user = User.active.find_by(:display_name => params[:display_name])
391 # render a "no such user" page
392 def render_unknown_user(name)
393 @title = t "user.no_such_user.title"
394 @not_found_user = name
396 respond_to do |format|
397 format.html { render :template => "user/no_such_user", :status => :not_found }
398 format.all { head :not_found }
403 # Unfortunately if a PUT or POST request that has a body fails to
404 # read it then Apache will sometimes fail to return the response it
405 # is given to the client properly, instead erroring:
407 # https://issues.apache.org/bugzilla/show_bug.cgi?id=44782
409 # To work round this we call rewind on the body here, which is added
410 # as a filter, to force it to be fetched from Apache into a file.
416 append_content_security_policy_directives(
417 :child_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
418 :frame_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
419 :connect_src => %w[nominatim.openstreetmap.org overpass-api.de router.project-osrm.org graphhopper.com],
420 :form_action => %w[render.openstreetmap.org],
421 :script_src => %w[open.mapquestapi.com],
422 :img_src => %w[developer.mapquest.com]
425 if STATUS == :database_offline || STATUS == :api_offline
426 flash.now[:warning] = t("layouts.osm_offline")
427 elsif STATUS == :database_readonly || STATUS == :api_readonly
428 flash.now[:warning] = t("layouts.osm_read_only")
431 request.xhr? ? "xhr" : "map"
434 def allow_thirdparty_images
435 append_content_security_policy_directives(:img_src => %w[*])
439 editor = if params[:editor]
441 elsif current_user && current_user.preferred_editor
442 current_user.preferred_editor
450 helper_method :preferred_editor
453 if defined?(TOTP_KEY)
454 cookies["_osm_totp_token"] = {
455 :value => ROTP::TOTP.new(TOTP_KEY, :interval => 3600).now,
456 :domain => "openstreetmap.org",
457 :expires => 1.hour.from_now
462 def better_errors_allow_inline
465 append_content_security_policy_directives(
466 :script_src => %w['unsafe-inline'],
467 :style_src => %w['unsafe-inline']
474 Ability.new(current_user).merge(granted_capabily)
478 Capability.new(current_user, current_token)
481 def deny_access(exception)
484 report_error t("oauth.permissions.missing"), :forbidden
492 # extract authorisation credentials from headers, returns user = nil if none
494 if request.env.key? "X-HTTP_AUTHORIZATION" # where mod_rewrite might have put it
495 authdata = request.env["X-HTTP_AUTHORIZATION"].to_s.split
496 elsif request.env.key? "REDIRECT_X_HTTP_AUTHORIZATION" # mod_fcgi
497 authdata = request.env["REDIRECT_X_HTTP_AUTHORIZATION"].to_s.split
498 elsif request.env.key? "HTTP_AUTHORIZATION" # regular location
499 authdata = request.env["HTTP_AUTHORIZATION"].to_s.split
501 # only basic authentication supported
502 user, pass = Base64.decode64(authdata[1]).split(":", 2) if authdata && authdata[0] == "Basic"
506 # override to stop oauth plugin sending errors
507 def invalid_oauth_response; end