1 class ApplicationController < ActionController::Base
2 include SessionPersistence
6 before_filter :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
44 render :text => "", :status => :forbidden
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)
64 report_error "OAuth token doesn't have that capability.", :forbidden
71 # require the user to have cookies enabled in their browser
73 if request.cookies["_osm_session"].to_s == ""
74 if params[:cookie_test].nil?
75 session[:cookie_test] = true
76 redirect_to Hash[params].merge(:cookie_test => "true")
79 flash.now[:warning] = t "application.require_cookies.cookies_needed"
82 session.delete(:cookie_test)
86 # Utility methods to make the controller filter methods easier to read and write.
87 def require_allow_read_prefs
88 require_capability(:allow_read_prefs)
91 def require_allow_write_prefs
92 require_capability(:allow_write_prefs)
95 def require_allow_write_diary
96 require_capability(:allow_write_diary)
99 def require_allow_write_api
100 require_capability(:allow_write_api)
102 if REQUIRE_TERMS_AGREED && @user.terms_agreed.nil?
103 report_error "You must accept the contributor terms before you can edit.", :forbidden
108 def require_allow_read_gpx
109 require_capability(:allow_read_gpx)
112 def require_allow_write_gpx
113 require_capability(:allow_write_gpx)
116 def require_allow_write_notes
117 require_capability(:allow_write_notes)
121 # require that the user is a moderator, or fill out a helpful error message
122 # and return them to the index for the controller this is wrapped from.
123 def require_moderator
124 unless @user.moderator?
126 flash[:error] = t("application.require_moderator.not_a_moderator")
127 redirect_to :action => "index"
129 render :text => "", :status => :forbidden
135 # sets up the @user object for use by other methods. this is mostly called
136 # from the authorize method, but can be called elsewhere if authorisation
139 # try and setup using OAuth
140 unless Authenticator.new(self, [:token]).allow?
141 username, passwd = get_auth_data # parse from headers
142 # authenticate per-scheme
144 @user = nil # no authentication provided - perhaps first connect (client should retry after 401)
145 elsif username == "token"
146 @user = User.authenticate(:token => passwd) # preferred - random token for user from db, passed in basic auth
148 @user = User.authenticate(:username => username, :password => passwd) # basic auth
152 # have we identified the user?
154 # check if the user has been banned
155 if @user.blocks.active.exists?
156 # NOTE: need slightly more helpful message than this.
157 report_error t("application.setup_user_auth.blocked"), :forbidden
160 # if the user hasn't seen the contributor terms then don't
161 # allow editing - they have to go to the web site and see
162 # (but can decline) the CTs to continue.
163 if REQUIRE_TERMS_SEEN && !@user.terms_seen && flash[:skip_terms].nil?
165 report_error t("application.setup_user_auth.need_to_see_terms"), :forbidden
170 def authorize(realm = "Web Password", errormessage = "Couldn't authenticate you")
171 # make the @user object from any auth sources we have
174 # handle authenticate pass/fail
176 # no auth, the user does not exist or the password was wrong
177 response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
178 render :text => errormessage, :status => :unauthorized
184 # to be used as a before_filter *after* authorize. this checks that
185 # the user is a moderator and, if not, returns a forbidden error.
187 # NOTE: this isn't a very good way of doing it - it duplicates logic
188 # from require_moderator - but what we really need to do is a fairly
189 # drastic refactoring based on :format and respond_to? but not a
190 # good idea to do that in this branch.
191 def authorize_moderator(errormessage = "Access restricted to moderators")
192 # check user is a moderator
193 unless @user.moderator?
194 render :text => errormessage, :status => :forbidden
199 def check_database_readable(need_api = false)
200 if STATUS == :database_offline || (need_api && STATUS == :api_offline)
202 report_error "Database offline for maintenance", :service_unavailable
204 redirect_to :controller => "site", :action => "offline"
209 def check_database_writable(need_api = false)
210 if STATUS == :database_offline || STATUS == :database_readonly ||
211 (need_api && (STATUS == :api_offline || STATUS == :api_readonly))
213 report_error "Database offline for maintenance", :service_unavailable
215 redirect_to :controller => "site", :action => "offline"
220 def check_api_readable
221 if api_status == :offline
222 report_error "Database offline for maintenance", :service_unavailable
227 def check_api_writable
228 unless api_status == :online
229 report_error "Database offline for maintenance", :service_unavailable
235 if STATUS == :database_offline
237 elsif STATUS == :database_readonly
245 status = database_status
247 if STATUS == :api_offline
249 elsif STATUS == :api_readonly
257 status = database_status
258 status = :offline if status == :online && STATUS == :gpx_offline
262 def require_public_data
263 unless @user.data_public?
264 report_error "You must make your edits public to upload new data", :forbidden
269 # Report and error to the user
270 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
271 # rather than only a status code and having the web engine make up a
272 # phrase from that, we can also put the error message into the status
273 # message. For now, rails won't let us)
274 def report_error(message, status = :bad_request)
275 # TODO: some sort of escaping of problem characters in the message
276 response.headers["Error"] = message
278 if request.headers["X-Error-Format"] &&
279 request.headers["X-Error-Format"].downcase == "xml"
280 result = OSM::API.new.get_xml_doc
281 result.root.name = "osmError"
282 result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
283 result.root << (XML::Node.new("message") << message)
285 render :text => result.to_s, :content_type => "text/xml"
287 render :text => message, :status => status, :content_type => "text/plain"
292 response.header["Vary"] = "Accept-Language"
294 if @user && !@user.languages.empty?
295 http_accept_language.user_preferred_languages = @user.languages
296 response.header["Vary"] = "*"
299 I18n.locale = select_locale
301 if @user && @user.languages.empty? && !http_accept_language.user_preferred_languages.empty?
302 @user.languages = http_accept_language.user_preferred_languages
306 response.headers["Content-Language"] = I18n.locale.to_s
309 def select_locale(locales = I18n.available_locales)
311 http_accept_language.user_preferred_languages = [params[:locale]]
314 if http_accept_language.compatible_language_from(locales).nil?
315 http_accept_language.user_preferred_languages = http_accept_language.user_preferred_languages.collect do |pl|
318 while pl.match(/^(.*)-[^-]+$/)
319 pls.push($1) if locales.include?($1) || locales.include?($1.to_sym)
327 http_accept_language.compatible_language_from(locales) || I18n.default_locale
330 helper_method :select_locale
332 def api_call_handle_error
334 rescue ActiveRecord::RecordNotFound => ex
335 render :text => "", :status => :not_found
336 rescue LibXML::XML::Error, ArgumentError => ex
337 report_error ex.message, :bad_request
338 rescue ActiveRecord::RecordInvalid => ex
339 message = "#{ex.record.class} #{ex.record.id}: "
340 ex.record.errors.each { |attr, msg| message << "#{attr}: #{msg} (#{ex.record[attr].inspect})" }
341 report_error message, :bad_request
342 rescue OSM::APIError => ex
343 report_error ex.message, ex.status
344 rescue AbstractController::ActionNotFound => ex
346 rescue StandardError => ex
347 logger.info("API threw unexpected #{ex.class} exception: #{ex.message}")
348 ex.backtrace.each { |l| logger.info(l) }
349 report_error "#{ex.class}: #{ex.message}", :internal_server_error
353 # asserts that the request method is the +method+ given as a parameter
354 # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
355 def assert_method(method)
356 ok = request.send((method.to_s.downcase + "?").to_sym)
357 fail OSM::APIBadMethodError.new(method) unless ok
361 # wrap an api call in a timeout
363 OSM::Timer.timeout(API_TIMEOUT) do
366 rescue Timeout::Error
367 raise OSM::APITimeoutError
371 # wrap a web page in a timeout
373 OSM::Timer.timeout(WEB_TIMEOUT) do
376 rescue ActionView::Template::Error => ex
377 ex = ex.original_exception
379 if ex.is_a?(ActiveRecord::StatementInvalid) && ex.message =~ /execution expired/
380 ex = Timeout::Error.new
383 if ex.is_a?(Timeout::Error)
384 render :action => "timeout"
388 rescue Timeout::Error
389 render :action => "timeout"
393 # is the requestor logged in?
399 # ensure that there is a "this_user" instance variable
401 unless @this_user = User.active.find_by_display_name(params[:display_name])
402 render_unknown_user params[:display_name]
407 # render a "no such user" page
408 def render_unknown_user(name)
409 @title = t "user.no_such_user.title"
410 @not_found_user = name
412 respond_to do |format|
413 format.html { render :template => "user/no_such_user", :status => :not_found }
414 format.all { render :text => "", :status => :not_found }
419 # Unfortunately if a PUT or POST request that has a body fails to
420 # read it then Apache will sometimes fail to return the response it
421 # is given to the client properly, instead erroring:
423 # https://issues.apache.org/bugzilla/show_bug.cgi?id=44782
425 # To work round this we call rewind on the body here, which is added
426 # as a filter, to force it to be fetched from Apache into a file.
432 request.xhr? ? "xhr" : "map"
436 editor = if params[:editor]
438 elsif @user && @user.preferred_editor
439 @user.preferred_editor
444 if request.env["HTTP_USER_AGENT"] =~ /MSIE|Trident/ && editor == "id"
451 helper_method :preferred_editor
455 # extract authorisation credentials from headers, returns user = nil if none
457 if request.env.key? "X-HTTP_AUTHORIZATION" # where mod_rewrite might have put it
458 authdata = request.env["X-HTTP_AUTHORIZATION"].to_s.split
459 elsif request.env.key? "REDIRECT_X_HTTP_AUTHORIZATION" # mod_fcgi
460 authdata = request.env["REDIRECT_X_HTTP_AUTHORIZATION"].to_s.split
461 elsif request.env.key? "HTTP_AUTHORIZATION" # regular location
462 authdata = request.env["HTTP_AUTHORIZATION"].to_s.split
464 # only basic authentication supported
465 if authdata && authdata[0] == "Basic"
466 user, pass = Base64.decode64(authdata[1]).split(":", 2)
471 # used by oauth plugin to get the current user
476 # used by oauth plugin to set the current user
477 def current_user=(user)
481 # override to stop oauth plugin sending errors
482 def invalid_oauth_response