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 and 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 Exception => ex
34 logger.info("Exception authorizing user: #{ex.to_s}")
42 redirect_to :controller => 'user', :action => 'login', :referer => request.fullpath
44 render :text => "", :status => :forbidden
50 @oauth = @user.access_token(OAUTH_KEY) if @user and 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 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)
90 def require_allow_write_prefs
91 require_capability(:allow_write_prefs)
93 def require_allow_write_diary
94 require_capability(:allow_write_diary)
96 def require_allow_write_api
97 require_capability(:allow_write_api)
99 if REQUIRE_TERMS_AGREED and @user.terms_agreed.nil?
100 report_error "You must accept the contributor terms before you can edit.", :forbidden
104 def require_allow_read_gpx
105 require_capability(:allow_read_gpx)
107 def require_allow_write_gpx
108 require_capability(:allow_write_gpx)
110 def require_allow_write_notes
111 require_capability(:allow_write_notes)
115 # require that the user is a moderator, or fill out a helpful error message
116 # and return them to the index for the controller this is wrapped from.
117 def require_moderator
118 unless @user.moderator?
120 flash[:error] = t('application.require_moderator.not_a_moderator')
121 redirect_to :action => 'index'
123 render :text => "", :status => :forbidden
129 # sets up the @user object for use by other methods. this is mostly called
130 # from the authorize method, but can be called elsewhere if authorisation
133 # try and setup using OAuth
134 if not Authenticator.new(self, [:token]).allow?
135 username, passwd = get_auth_data # parse from headers
136 # authenticate per-scheme
138 @user = nil # no authentication provided - perhaps first connect (client should retry after 401)
139 elsif username == 'token'
140 @user = User.authenticate(:token => passwd) # preferred - random token for user from db, passed in basic auth
142 @user = User.authenticate(:username => username, :password => passwd) # basic auth
146 # have we identified the user?
148 # check if the user has been banned
149 if @user.blocks.active.exists?
150 # NOTE: need slightly more helpful message than this.
151 report_error t('application.setup_user_auth.blocked'), :forbidden
154 # if the user hasn't seen the contributor terms then don't
155 # allow editing - they have to go to the web site and see
156 # (but can decline) the CTs to continue.
157 if REQUIRE_TERMS_SEEN and not @user.terms_seen and flash[:skip_terms].nil?
159 report_error t('application.setup_user_auth.need_to_see_terms'), :forbidden
164 def authorize(realm='Web Password', errormessage="Couldn't authenticate you")
165 # make the @user object from any auth sources we have
168 # handle authenticate pass/fail
170 # no auth, the user does not exist or the password was wrong
171 response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
172 render :text => errormessage, :status => :unauthorized
178 # to be used as a before_filter *after* authorize. this checks that
179 # the user is a moderator and, if not, returns a forbidden error.
181 # NOTE: this isn't a very good way of doing it - it duplicates logic
182 # from require_moderator - but what we really need to do is a fairly
183 # drastic refactoring based on :format and respond_to? but not a
184 # good idea to do that in this branch.
185 def authorize_moderator(errormessage="Access restricted to moderators")
186 # check user is a moderator
187 unless @user.moderator?
188 render :text => errormessage, :status => :forbidden
193 def check_database_readable(need_api = false)
194 if STATUS == :database_offline or (need_api and STATUS == :api_offline)
195 redirect_to :controller => 'site', :action => 'offline'
199 def check_database_writable(need_api = false)
200 if STATUS == :database_offline or STATUS == :database_readonly or
201 (need_api and (STATUS == :api_offline or STATUS == :api_readonly))
202 redirect_to :controller => 'site', :action => 'offline'
206 def check_api_readable
207 if api_status == :offline
208 report_error "Database offline for maintenance", :service_unavailable
213 def check_api_writable
214 unless api_status == :online
215 report_error "Database offline for maintenance", :service_unavailable
221 if STATUS == :database_offline
223 elsif STATUS == :database_readonly
231 status = database_status
233 if STATUS == :api_offline
235 elsif STATUS == :api_readonly
243 status = database_status
245 status = :offline if STATUS == :gpx_offline
250 def require_public_data
251 unless @user.data_public?
252 report_error "You must make your edits public to upload new data", :forbidden
257 # Report and error to the user
258 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
259 # rather than only a status code and having the web engine make up a
260 # phrase from that, we can also put the error message into the status
261 # message. For now, rails won't let us)
262 def report_error(message, status = :bad_request)
263 # Todo: some sort of escaping of problem characters in the message
264 response.headers['Error'] = message
266 if request.headers['X-Error-Format'] and
267 request.headers['X-Error-Format'].downcase == "xml"
268 result = OSM::API.new.get_xml_doc
269 result.root.name = "osmError"
270 result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
271 result.root << (XML::Node.new("message") << message)
273 render :text => result.to_s, :content_type => "text/xml"
275 render :text => message, :status => status, :content_type => "text/plain"
280 response.header['Vary'] = 'Accept-Language'
282 if @user && !@user.languages.empty?
283 http_accept_language.user_preferred_languages = @user.languages
284 response.header['Vary'] = '*'
287 I18n.locale = select_locale
289 if @user && @user.languages.empty? && !http_accept_language.user_preferred_languages.empty?
290 @user.languages = http_accept_language.user_preferred_languages
294 response.headers['Content-Language'] = I18n.locale.to_s
297 def select_locale(locales = I18n.available_locales)
299 http_accept_language.user_preferred_languages = [ params[:locale] ]
302 if http_accept_language.compatible_language_from(locales).nil?
303 http_accept_language.user_preferred_languages = http_accept_language.user_preferred_languages.collect do |pl|
306 while pl.match(/^(.*)-[^-]+$/)
307 pls.push($1) if locales.include?($1) or locales.include?($1.to_sym)
315 http_accept_language.compatible_language_from(locales) || I18n.default_locale
318 helper_method :select_locale
320 def api_call_handle_error
323 rescue ActiveRecord::RecordNotFound => ex
324 render :text => "", :status => :not_found
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 Exception => 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
343 # asserts that the request method is the +method+ given as a parameter
344 # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
345 def assert_method(method)
346 ok = request.send((method.to_s.downcase + "?").to_sym)
347 raise OSM::APIBadMethodError.new(method) unless ok
351 # wrap an api call in a timeout
353 OSM::Timer.timeout(API_TIMEOUT) do
356 rescue Timeout::Error
357 raise OSM::APITimeoutError
361 # wrap a web page in a timeout
363 OSM::Timer.timeout(WEB_TIMEOUT) do
366 rescue ActionView::Template::Error => ex
367 ex = ex.original_exception
369 if ex.is_a?(ActiveRecord::StatementInvalid) and ex.message =~ /execution expired/
370 ex = Timeout::Error.new
373 if ex.is_a?(Timeout::Error)
374 render :action => "timeout"
378 rescue Timeout::Error
379 render :action => "timeout"
383 # is the requestor logged in?
389 # ensure that there is a "this_user" instance variable
391 unless @this_user = User.active.find_by_display_name(params[:display_name])
392 render_unknown_user params[:display_name]
397 # render a "no such user" page
398 def render_unknown_user(name)
399 @title = t "user.no_such_user.title"
400 @not_found_user = name
402 respond_to do |format|
403 format.html { render :template => "user/no_such_user", :status => :not_found }
404 format.all { render :text => "", :status => :not_found }
409 # Unfortunately if a PUT or POST request that has a body fails to
410 # read it then Apache will sometimes fail to return the response it
411 # is given to the client properly, instead erroring:
413 # https://issues.apache.org/bugzilla/show_bug.cgi?id=44782
415 # To work round this we call rewind on the body here, which is added
416 # as a filter, to force it to be fetched from Apache into a file.
422 request.xhr? ? 'xhr' : 'map'
426 editor = if params[:editor]
428 elsif @user and @user.preferred_editor
429 @user.preferred_editor
434 if request.env['HTTP_USER_AGENT'] =~ /MSIE|Trident/ and editor == 'id'
441 helper_method :preferred_editor
445 # extract authorisation credentials from headers, returns user = nil if none
447 if request.env.has_key? 'X-HTTP_AUTHORIZATION' # where mod_rewrite might have put it
448 authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split
449 elsif request.env.has_key? 'REDIRECT_X_HTTP_AUTHORIZATION' # mod_fcgi
450 authdata = request.env['REDIRECT_X_HTTP_AUTHORIZATION'].to_s.split
451 elsif request.env.has_key? 'HTTP_AUTHORIZATION' # regular location
452 authdata = request.env['HTTP_AUTHORIZATION'].to_s.split
454 # only basic authentication supported
455 if authdata and authdata[0] == 'Basic'
456 user, pass = Base64.decode64(authdata[1]).split(':',2)
461 # used by oauth plugin to get the current user
466 # used by oauth plugin to set the current user
467 def current_user=(user)
471 # override to stop oauth plugin sending errors
472 def invalid_oauth_response