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 if @user = User.authenticate(:token => session[:token])
39 session[:user] = @user.id
42 rescue Exception => ex
43 logger.info("Exception authorizing user: #{ex.to_s}")
48 redirect_to :controller => 'user', :action => 'login', :referer => request.fullpath unless @user
52 # requires the user to be logged in by the token or HTTP methods, or have an
53 # OAuth token with the right capability. this method is a bit of a pain to call
54 # directly, since it's cumbersome to call filters with arguments in rails. to
55 # make it easier to read and write the code, there are some utility methods
57 def require_capability(cap)
58 # when the current token is nil, it means the user logged in with a different
59 # method, otherwise an OAuth token was used, which has to be checked.
60 unless current_token.nil?
61 unless current_token.read_attribute(cap)
62 report_error "OAuth token doesn't have that capability.", :forbidden
69 # require the user to have cookies enabled in their browser
71 if request.cookies["_osm_session"].to_s == ""
72 if params[:cookie_test].nil?
73 session[:cookie_test] = true
74 redirect_to params.merge(:cookie_test => "true")
77 flash.now[:warning] = t 'application.require_cookies.cookies_needed'
80 session.delete(:cookie_test)
84 # Utility methods to make the controller filter methods easier to read and write.
85 def require_allow_read_prefs
86 require_capability(:allow_read_prefs)
88 def require_allow_write_prefs
89 require_capability(:allow_write_prefs)
91 def require_allow_write_diary
92 require_capability(:allow_write_diary)
94 def require_allow_write_api
95 require_capability(:allow_write_api)
97 if REQUIRE_TERMS_AGREED and @user.terms_agreed.nil?
98 report_error "You must accept the contributor terms before you can edit.", :forbidden
102 def require_allow_read_gpx
103 require_capability(:allow_read_gpx)
105 def require_allow_write_gpx
106 require_capability(:allow_write_gpx)
110 # sets up the @user object for use by other methods. this is mostly called
111 # from the authorize method, but can be called elsewhere if authorisation
114 # try and setup using OAuth
115 if not Authenticator.new(self, [:token]).allow?
116 username, passwd = get_auth_data # parse from headers
117 # authenticate per-scheme
119 @user = nil # no authentication provided - perhaps first connect (client should retry after 401)
120 elsif username == 'token'
121 @user = User.authenticate(:token => passwd) # preferred - random token for user from db, passed in basic auth
123 @user = User.authenticate(:username => username, :password => passwd) # basic auth
127 # have we identified the user?
129 # check if the user has been banned
130 if not @user.active_blocks.empty?
131 # NOTE: need slightly more helpful message than this.
132 report_error t('application.setup_user_auth.blocked'), :forbidden
135 # if the user hasn't seen the contributor terms then don't
136 # allow editing - they have to go to the web site and see
137 # (but can decline) the CTs to continue.
138 if REQUIRE_TERMS_SEEN and not @user.terms_seen and flash[:skip_terms].nil?
140 report_error t('application.setup_user_auth.need_to_see_terms'), :forbidden
145 def authorize(realm='Web Password', errormessage="Couldn't authenticate you")
146 # make the @user object from any auth sources we have
149 # handle authenticate pass/fail
151 # no auth, the user does not exist or the password was wrong
152 response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
153 render :text => errormessage, :status => :unauthorized
158 def check_database_readable(need_api = false)
159 if STATUS == :database_offline or (need_api and STATUS == :api_offline)
160 redirect_to :controller => 'site', :action => 'offline'
164 def check_database_writable(need_api = false)
165 if STATUS == :database_offline or STATUS == :database_readonly or
166 (need_api and (STATUS == :api_offline or STATUS == :api_readonly))
167 redirect_to :controller => 'site', :action => 'offline'
171 def check_api_readable
172 if STATUS == :database_offline or STATUS == :api_offline
173 report_error "Database offline for maintenance", :service_unavailable
178 def check_api_writable
179 if STATUS == :database_offline or STATUS == :database_readonly or
180 STATUS == :api_offline or STATUS == :api_readonly
181 report_error "Database offline for maintenance", :service_unavailable
186 def require_public_data
187 unless @user.data_public?
188 report_error "You must make your edits public to upload new data", :forbidden
193 # Report and error to the user
194 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
195 # rather than only a status code and having the web engine make up a
196 # phrase from that, we can also put the error message into the status
197 # message. For now, rails won't let us)
198 def report_error(message, status = :bad_request)
199 # Todo: some sort of escaping of problem characters in the message
200 response.headers['Error'] = message
202 if request.headers['X-Error-Format'] and
203 request.headers['X-Error-Format'].downcase == "xml"
204 result = OSM::API.new.get_xml_doc
205 result.root.name = "osmError"
206 result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
207 result.root << (XML::Node.new("message") << message)
209 render :text => result.to_s, :content_type => "text/xml"
211 render :text => message, :status => status
216 response.header['Vary'] = 'Accept-Language'
219 if !@user.languages.empty?
220 request.user_preferred_languages = @user.languages
221 response.header['Vary'] = '*'
222 elsif !request.user_preferred_languages.empty?
223 @user.languages = request.user_preferred_languages
228 if request.compatible_language_from(I18n.available_locales).nil?
229 request.user_preferred_languages = request.user_preferred_languages.collect do |pl|
232 while pl.match(/^(.*)-[^-]+$/)
233 pls.push($1) if I18n.available_locales.include?($1.to_sym)
240 if @user and not request.compatible_language_from(I18n.available_locales).nil?
241 @user.languages = request.user_preferred_languages
246 I18n.locale = request.compatible_language_from(I18n.available_locales)
248 response.headers['Content-Language'] = I18n.locale.to_s
251 def api_call_handle_error
254 rescue ActiveRecord::RecordNotFound => ex
255 render :nothing => true, :status => :not_found
256 rescue LibXML::XML::Error, ArgumentError => ex
257 report_error ex.message, :bad_request
258 rescue ActiveRecord::RecordInvalid => ex
259 message = "#{ex.record.class} #{ex.record.id}: "
260 ex.record.errors.each { |attr,msg| message << "#{attr}: #{msg} (#{ex.record[attr].inspect})" }
261 report_error message, :bad_request
262 rescue OSM::APIError => ex
263 report_error ex.message, ex.status
264 rescue ActionController::UnknownAction => ex
266 rescue Exception => ex
267 logger.info("API threw unexpected #{ex.class} exception: #{ex.message}")
268 ex.backtrace.each { |l| logger.info(l) }
269 report_error "#{ex.class}: #{ex.message}", :internal_server_error
274 # asserts that the request method is the +method+ given as a parameter
275 # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
276 def assert_method(method)
277 ok = request.send((method.to_s.downcase + "?").to_sym)
278 raise OSM::APIBadMethodError.new(method) unless ok
282 # wrap an api call in a timeout
284 SystemTimer.timeout_after(API_TIMEOUT) do
287 rescue Timeout::Error
288 raise OSM::APITimeoutError
292 # wrap a web page in a timeout
294 SystemTimer.timeout_after(WEB_TIMEOUT) do
297 rescue ActionView::TemplateError => ex
298 if ex.original_exception.is_a?(Timeout::Error)
299 render :action => "timeout"
303 rescue Timeout::Error
304 render :action => "timeout"
308 # extend caches_action to include the parameters, locale and logged in
309 # status in all cache keys
310 def self.caches_action(*actions)
311 options = actions.extract_options!
312 cache_path = options[:cache_path] || Hash.new
314 options[:unless] = case options[:unless]
315 when NilClass then Array.new
316 when Array then options[:unless]
317 else unlessp = [ options[:unless] ]
320 options[:unless].push(Proc.new do |controller|
321 controller.params.include?(:page)
324 options[:cache_path] = Proc.new do |controller|
325 cache_path.merge(controller.params).merge(:locale => I18n.locale)
328 actions.push(options)
334 # extend expire_action to expire all variants
335 def expire_action(options = {})
336 I18n.available_locales.each do |locale|
337 super options.merge(:locale => locale)
342 # is the requestor logged in?
349 # extract authorisation credentials from headers, returns user = nil if none
351 if request.env.has_key? 'X-HTTP_AUTHORIZATION' # where mod_rewrite might have put it
352 authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split
353 elsif request.env.has_key? 'REDIRECT_X_HTTP_AUTHORIZATION' # mod_fcgi
354 authdata = request.env['REDIRECT_X_HTTP_AUTHORIZATION'].to_s.split
355 elsif request.env.has_key? 'HTTP_AUTHORIZATION' # regular location
356 authdata = request.env['HTTP_AUTHORIZATION'].to_s.split
358 # only basic authentication supported
359 if authdata and authdata[0] == 'Basic'
360 user, pass = Base64.decode64(authdata[1]).split(':',2)
365 # used by oauth plugin to set the current user
366 def current_user=(user)
370 # override to stop oauth plugin sending errors
371 def invalid_oauth_response