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.display_name != cookies["_osm_username"]
13 logger.info "Session user '#{@user.display_name}' does not match cookie user '#{cookies['_osm_username']}'"
16 elsif @user.status == "suspended"
18 session_expires_automatically
20 redirect_to :controller => "user", :action => "suspended"
22 # don't allow access to any auth-requiring part of the site unless
23 # the new CTs have been seen (and accept/decline chosen).
24 elsif !@user.terms_seen and flash[:skip_terms].nil?
25 flash[:notice] = t 'user.terms.you need to accept or decline'
27 redirect_to :controller => "user", :action => "terms", :referer => params[:referer]
29 redirect_to :controller => "user", :action => "terms", :referer => request.fullpath
33 if @user = User.authenticate(:token => session[:token])
34 session[:user] = @user.id
37 rescue Exception => ex
38 logger.info("Exception authorizing user: #{ex.to_s}")
46 redirect_to :controller => 'user', :action => 'login', :referer => request.fullpath
48 render :text => "", :status => :forbidden
54 @oauth = @user.access_token(OAUTH_KEY) if @user and 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)
68 report_error "OAuth token doesn't have that capability.", :forbidden
75 # require the user to have cookies enabled in their browser
77 if request.cookies["_osm_session"].to_s == ""
78 if params[:cookie_test].nil?
79 session[:cookie_test] = true
80 redirect_to params.merge(:cookie_test => "true")
83 flash.now[:warning] = t 'application.require_cookies.cookies_needed'
86 session.delete(:cookie_test)
90 # Utility methods to make the controller filter methods easier to read and write.
91 def require_allow_read_prefs
92 require_capability(:allow_read_prefs)
94 def require_allow_write_prefs
95 require_capability(:allow_write_prefs)
97 def require_allow_write_diary
98 require_capability(:allow_write_diary)
100 def require_allow_write_api
101 require_capability(:allow_write_api)
103 if REQUIRE_TERMS_AGREED and @user.terms_agreed.nil?
104 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)
111 def require_allow_write_gpx
112 require_capability(:allow_write_gpx)
114 def require_allow_write_notes
115 require_capability(:allow_write_notes)
119 # require that the user is a moderator, or fill out a helpful error message
120 # and return them to the index for the controller this is wrapped from.
121 def require_moderator
122 unless @user.moderator?
124 flash[:error] = t('application.require_moderator.not_a_moderator')
125 redirect_to :action => 'index'
127 render :text => "", :status => :forbidden
133 # sets up the @user object for use by other methods. this is mostly called
134 # from the authorize method, but can be called elsewhere if authorisation
137 # try and setup using OAuth
138 if not Authenticator.new(self, [:token]).allow?
139 username, passwd = get_auth_data # parse from headers
140 # authenticate per-scheme
142 @user = nil # no authentication provided - perhaps first connect (client should retry after 401)
143 elsif username == 'token'
144 @user = User.authenticate(:token => passwd) # preferred - random token for user from db, passed in basic auth
146 @user = User.authenticate(:username => username, :password => passwd) # basic auth
150 # have we identified the user?
152 # check if the user has been banned
153 if @user.blocks.active.exists?
154 # NOTE: need slightly more helpful message than this.
155 report_error t('application.setup_user_auth.blocked'), :forbidden
158 # if the user hasn't seen the contributor terms then don't
159 # allow editing - they have to go to the web site and see
160 # (but can decline) the CTs to continue.
161 if REQUIRE_TERMS_SEEN and not @user.terms_seen and flash[:skip_terms].nil?
163 report_error t('application.setup_user_auth.need_to_see_terms'), :forbidden
168 def authorize(realm='Web Password', errormessage="Couldn't authenticate you")
169 # make the @user object from any auth sources we have
172 # handle authenticate pass/fail
174 # no auth, the user does not exist or the password was wrong
175 response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
176 render :text => errormessage, :status => :unauthorized
182 # to be used as a before_filter *after* authorize. this checks that
183 # the user is a moderator and, if not, returns a forbidden error.
185 # NOTE: this isn't a very good way of doing it - it duplicates logic
186 # from require_moderator - but what we really need to do is a fairly
187 # drastic refactoring based on :format and respond_to? but not a
188 # good idea to do that in this branch.
189 def authorize_moderator(errormessage="Access restricted to moderators")
190 # check user is a moderator
191 unless @user.moderator?
192 render :text => errormessage, :status => :forbidden
197 def check_database_readable(need_api = false)
198 if STATUS == :database_offline or (need_api and STATUS == :api_offline)
199 redirect_to :controller => 'site', :action => 'offline'
203 def check_database_writable(need_api = false)
204 if STATUS == :database_offline or STATUS == :database_readonly or
205 (need_api and (STATUS == :api_offline or STATUS == :api_readonly))
206 redirect_to :controller => 'site', :action => 'offline'
210 def check_api_readable
211 if api_status == :offline
212 report_error "Database offline for maintenance", :service_unavailable
217 def check_api_writable
218 unless api_status == :online
219 report_error "Database offline for maintenance", :service_unavailable
225 if STATUS == :database_offline
227 elsif STATUS == :database_readonly
235 status = database_status
237 if STATUS == :api_offline
239 elsif STATUS == :api_readonly
247 status = database_status
249 status = :offline if STATUS == :gpx_offline
254 def require_public_data
255 unless @user.data_public?
256 report_error "You must make your edits public to upload new data", :forbidden
261 # Report and error to the user
262 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
263 # rather than only a status code and having the web engine make up a
264 # phrase from that, we can also put the error message into the status
265 # message. For now, rails won't let us)
266 def report_error(message, status = :bad_request)
267 # Todo: some sort of escaping of problem characters in the message
268 response.headers['Error'] = message
270 if request.headers['X-Error-Format'] and
271 request.headers['X-Error-Format'].downcase == "xml"
272 result = OSM::API.new.get_xml_doc
273 result.root.name = "osmError"
274 result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
275 result.root << (XML::Node.new("message") << message)
277 render :text => result.to_s, :content_type => "text/xml"
279 render :text => message, :status => status, :content_type => "text/plain"
284 response.header['Vary'] = 'Accept-Language'
286 if @user && !@user.languages.empty?
287 request.user_preferred_languages = @user.languages
288 response.header['Vary'] = '*'
291 I18n.locale = select_locale
293 if @user && @user.languages.empty? && !request.user_preferred_languages.empty?
294 @user.languages = request.user_preferred_languages
298 response.headers['Content-Language'] = I18n.locale.to_s
301 def select_locale(locales = I18n.available_locales)
303 request.user_preferred_languages = [ params[:locale] ]
306 if request.compatible_language_from(locales).nil?
307 request.user_preferred_languages = request.user_preferred_languages.collect do |pl|
310 while pl.match(/^(.*)-[^-]+$/)
311 pls.push($1) if locales.include?($1) or locales.include?($1.to_sym)
319 request.compatible_language_from(locales) || I18n.default_locale
322 helper_method :select_locale
324 def api_call_handle_error
327 rescue ActiveRecord::RecordNotFound => ex
328 render :text => "", :status => :not_found
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 Exception => 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
347 # asserts that the request method is the +method+ given as a parameter
348 # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
349 def assert_method(method)
350 ok = request.send((method.to_s.downcase + "?").to_sym)
351 raise OSM::APIBadMethodError.new(method) unless ok
355 # wrap an api call in a timeout
357 OSM::Timer.timeout(API_TIMEOUT) do
360 rescue Timeout::Error
361 raise OSM::APITimeoutError
365 # wrap a web page in a timeout
367 OSM::Timer.timeout(WEB_TIMEOUT) do
370 rescue ActionView::Template::Error => ex
371 ex = ex.original_exception
373 if ex.is_a?(ActiveRecord::StatementInvalid) and ex.message =~ /^Timeout::Error/
374 ex = Timeout::Error.new
377 if ex.is_a?(Timeout::Error)
378 render :action => "timeout"
382 rescue Timeout::Error
383 render :action => "timeout"
387 # is the requestor logged in?
393 # ensure that there is a "this_user" instance variable
395 unless @this_user = User.active.find_by_display_name(params[:display_name])
396 render_unknown_user params[:display_name]
401 # render a "no such user" page
402 def render_unknown_user(name)
403 @title = t "user.no_such_user.title"
404 @not_found_user = name
406 respond_to do |format|
407 format.html { render :template => "user/no_such_user", :status => :not_found }
408 format.all { render :text => "", :status => :not_found }
413 # Unfortunately if a PUT or POST request that has a body fails to
414 # read it then Apache will sometimes fail to return the response it
415 # is given to the client properly, instead erroring:
417 # https://issues.apache.org/bugzilla/show_bug.cgi?id=44782
419 # To work round this we call rewind on the body here, which is added
420 # as a filter, to force it to be fetched from Apache into a file.
427 # extract authorisation credentials from headers, returns user = nil if none
429 if request.env.has_key? 'X-HTTP_AUTHORIZATION' # where mod_rewrite might have put it
430 authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split
431 elsif request.env.has_key? 'REDIRECT_X_HTTP_AUTHORIZATION' # mod_fcgi
432 authdata = request.env['REDIRECT_X_HTTP_AUTHORIZATION'].to_s.split
433 elsif request.env.has_key? 'HTTP_AUTHORIZATION' # regular location
434 authdata = request.env['HTTP_AUTHORIZATION'].to_s.split
436 # only basic authentication supported
437 if authdata and authdata[0] == 'Basic'
438 user, pass = Base64.decode64(authdata[1]).split(':',2)
443 # used by oauth plugin to get the current user
448 # used by oauth plugin to set the current user
449 def current_user=(user)
453 # override to stop oauth plugin sending errors
454 def invalid_oauth_response