1 class ApplicationController < ActionController::Base
5 if STATUS == :database_readonly or STATUS == :database_offline
6 after_filter :clear_session
13 def self.cache_sweeper(*sweepers)
19 @user = User.where(:id => session[:user]).where("status IN ('active', 'confirmed', 'suspended')").first
21 if @user.status == "suspended"
23 session_expires_automatically
25 redirect_to :controller => "user", :action => "suspended"
27 # don't allow access to any auth-requiring part of the site unless
28 # the new CTs have been seen (and accept/decline chosen).
29 elsif !@user.terms_seen and flash[:skip_terms].nil?
30 flash[:notice] = t 'user.terms.you need to accept or decline'
32 redirect_to :controller => "user", :action => "terms", :referer => params[:referer]
34 redirect_to :controller => "user", :action => "terms", :referer => request.fullpath
38 @user = User.authenticate(:token => session[:token])
39 session[:user] = @user.id
41 rescue Exception => ex
42 logger.info("Exception authorizing user: #{ex.to_s}")
47 redirect_to :controller => 'user', :action => 'login', :referer => request.fullpath unless @user
51 # requires the user to be logged in by the token or HTTP methods, or have an
52 # OAuth token with the right capability. this method is a bit of a pain to call
53 # directly, since it's cumbersome to call filters with arguments in rails. to
54 # make it easier to read and write the code, there are some utility methods
56 def require_capability(cap)
57 # when the current token is nil, it means the user logged in with a different
58 # method, otherwise an OAuth token was used, which has to be checked.
59 unless current_token.nil?
60 unless current_token.read_attribute(cap)
61 report_error "OAuth token doesn't have that capability.", :forbidden
68 # require the user to have cookies enabled in their browser
70 if request.cookies["_osm_session"].to_s == ""
71 if params[:cookie_test].nil?
72 session[:cookie_test] = true
73 redirect_to params.merge(:cookie_test => "true")
76 flash.now[:warning] = t 'application.require_cookies.cookies_needed'
79 session.delete(:cookie_test)
83 # Utility methods to make the controller filter methods easier to read and write.
84 def require_allow_read_prefs
85 require_capability(:allow_read_prefs)
87 def require_allow_write_prefs
88 require_capability(:allow_write_prefs)
90 def require_allow_write_diary
91 require_capability(:allow_write_diary)
93 def require_allow_write_api
94 require_capability(:allow_write_api)
96 if REQUIRE_TERMS_AGREED and @user.terms_agreed.nil?
97 report_error "You must accept the contributor terms before you can edit.", :forbidden
101 def require_allow_read_gpx
102 require_capability(:allow_read_gpx)
104 def require_allow_write_gpx
105 require_capability(:allow_write_gpx)
109 # sets up the @user object for use by other methods. this is mostly called
110 # from the authorize method, but can be called elsewhere if authorisation
113 # try and setup using OAuth
114 if not Authenticator.new(self, [:token]).allow?
115 username, passwd = get_auth_data # parse from headers
116 # authenticate per-scheme
118 @user = nil # no authentication provided - perhaps first connect (client should retry after 401)
119 elsif username == 'token'
120 @user = User.authenticate(:token => passwd) # preferred - random token for user from db, passed in basic auth
122 @user = User.authenticate(:username => username, :password => passwd) # basic auth
126 # have we identified the user?
128 # check if the user has been banned
129 if not @user.active_blocks.empty?
130 # NOTE: need slightly more helpful message than this.
131 report_error t('application.setup_user_auth.blocked'), :forbidden
134 # if the user hasn't seen the contributor terms then don't
135 # allow editing - they have to go to the web site and see
136 # (but can decline) the CTs to continue.
137 if REQUIRE_TERMS_SEEN and not @user.terms_seen and flash[:skip_terms].nil?
139 report_error t('application.setup_user_auth.need_to_see_terms'), :forbidden
144 def authorize(realm='Web Password', errormessage="Couldn't authenticate you")
145 # make the @user object from any auth sources we have
148 # handle authenticate pass/fail
150 # no auth, the user does not exist or the password was wrong
151 response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
152 render :text => errormessage, :status => :unauthorized
157 def check_database_readable(need_api = false)
158 if STATUS == :database_offline or (need_api and STATUS == :api_offline)
159 redirect_to :controller => 'site', :action => 'offline'
163 def check_database_writable(need_api = false)
164 if STATUS == :database_offline or STATUS == :database_readonly or
165 (need_api and (STATUS == :api_offline or STATUS == :api_readonly))
166 redirect_to :controller => 'site', :action => 'offline'
170 def check_api_readable
171 if STATUS == :database_offline or STATUS == :api_offline
172 report_error "Database offline for maintenance", :service_unavailable
177 def check_api_writable
178 if STATUS == :database_offline or STATUS == :database_readonly or
179 STATUS == :api_offline or STATUS == :api_readonly
180 report_error "Database offline for maintenance", :service_unavailable
185 def require_public_data
186 unless @user.data_public?
187 report_error "You must make your edits public to upload new data", :forbidden
192 # Report and error to the user
193 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
194 # rather than only a status code and having the web engine make up a
195 # phrase from that, we can also put the error message into the status
196 # message. For now, rails won't let us)
197 def report_error(message, status = :bad_request)
198 # Todo: some sort of escaping of problem characters in the message
199 response.headers['Error'] = message
201 if request.headers['X-Error-Format'] and
202 request.headers['X-Error-Format'].downcase == "xml"
203 result = OSM::API.new.get_xml_doc
204 result.root.name = "osmError"
205 result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
206 result.root << (XML::Node.new("message") << message)
208 render :text => result.to_s, :content_type => "text/xml"
210 render :text => message, :status => status
215 response.header['Vary'] = 'Accept-Language'
218 if !@user.languages.empty?
219 request.user_preferred_languages = @user.languages
220 response.header['Vary'] = '*'
221 elsif !request.user_preferred_languages.empty?
222 @user.languages = request.user_preferred_languages
227 if request.compatible_language_from(I18n.available_locales).nil?
228 request.user_preferred_languages = request.user_preferred_languages.collect do |pl|
231 while pl.match(/^(.*)-[^-]+$/)
232 pls.push($1) if I18n.available_locales.include?($1.to_sym)
239 if @user and not request.compatible_language_from(I18n.available_locales).nil?
240 @user.languages = request.user_preferred_languages
245 I18n.locale = request.compatible_language_from(I18n.available_locales)
247 response.headers['Content-Language'] = I18n.locale.to_s
250 def api_call_handle_error
253 rescue ActiveRecord::RecordNotFound => ex
254 render :nothing => true, :status => :not_found
255 rescue LibXML::XML::Error, ArgumentError => ex
256 report_error ex.message, :bad_request
257 rescue ActiveRecord::RecordInvalid => ex
258 message = "#{ex.record.class} #{ex.record.id}: "
259 ex.record.errors.each { |attr,msg| message << "#{attr}: #{msg} (#{ex.record[attr].inspect})" }
260 report_error message, :bad_request
261 rescue OSM::APIError => ex
262 report_error ex.message, ex.status
263 rescue ActionController::UnknownAction => ex
265 rescue Exception => ex
266 logger.info("API threw unexpected #{ex.class} exception: #{ex.message}")
267 ex.backtrace.each { |l| logger.info(l) }
268 report_error "#{ex.class}: #{ex.message}", :internal_server_error
273 # asserts that the request method is the +method+ given as a parameter
274 # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
275 def assert_method(method)
276 ok = request.send((method.to_s.downcase + "?").to_sym)
277 raise OSM::APIBadMethodError.new(method) unless ok
281 # wrap an api call in a timeout
283 SystemTimer.timeout_after(API_TIMEOUT) do
286 rescue Timeout::Error
287 raise OSM::APITimeoutError
291 # wrap a web page in a timeout
293 SystemTimer.timeout_after(WEB_TIMEOUT) do
296 rescue ActionView::TemplateError => ex
297 if ex.original_exception.is_a?(Timeout::Error)
298 render :action => "timeout"
302 rescue Timeout::Error
303 render :action => "timeout"
307 # extend caches_action to include the parameters, locale and logged in
308 # status in all cache keys
309 def self.caches_action(*actions)
310 options = actions.extract_options!
311 cache_path = options[:cache_path] || Hash.new
313 options[:unless] = case options[:unless]
314 when NilClass then Array.new
315 when Array then options[:unless]
316 else unlessp = [ options[:unless] ]
319 options[:unless].push(Proc.new do |controller|
320 controller.params.include?(:page)
323 options[:cache_path] = Proc.new do |controller|
324 cache_path.merge(controller.params).merge(:locale => I18n.locale)
327 actions.push(options)
333 # extend expire_action to expire all variants
334 def expire_action(options = {})
335 I18n.available_locales.each do |locale|
336 super options.merge(:locale => locale)
341 # is the requestor logged in?
348 # extract authorisation credentials from headers, returns user = nil if none
350 if request.env.has_key? 'X-HTTP_AUTHORIZATION' # where mod_rewrite might have put it
351 authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split
352 elsif request.env.has_key? 'REDIRECT_X_HTTP_AUTHORIZATION' # mod_fcgi
353 authdata = request.env['REDIRECT_X_HTTP_AUTHORIZATION'].to_s.split
354 elsif request.env.has_key? 'HTTP_AUTHORIZATION' # regular location
355 authdata = request.env['HTTP_AUTHORIZATION'].to_s.split
357 # only basic authentication supported
358 if authdata and authdata[0] == 'Basic'
359 user, pass = Base64.decode64(authdata[1]).split(':',2)
364 # used by oauth plugin to set the current user
365 def current_user=(user)
369 # override to stop oauth plugin sending errors
370 def invalid_oauth_response