1 class ApplicationController < ActionController::Base
5 if STATUS == :database_readonly or STATUS == :database_offline
8 def self.cache_sweeper(*sweepers)
14 @user = User.where(:id => session[:user]).where("status IN ('active', 'confirmed', 'suspended')").first
16 if @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 @user = User.authenticate(:token => session[:token])
34 session[:user] = @user.id
36 rescue Exception => ex
37 logger.info("Exception authorizing user: #{ex.to_s}")
42 redirect_to :controller => 'user', :action => 'login', :referer => request.fullpath unless @user
46 # requires the user to be logged in by the token or HTTP methods, or have an
47 # OAuth token with the right capability. this method is a bit of a pain to call
48 # directly, since it's cumbersome to call filters with arguments in rails. to
49 # make it easier to read and write the code, there are some utility methods
51 def require_capability(cap)
52 # when the current token is nil, it means the user logged in with a different
53 # method, otherwise an OAuth token was used, which has to be checked.
54 unless current_token.nil?
55 unless current_token.read_attribute(cap)
56 report_error "OAuth token doesn't have that capability.", :forbidden
63 # require the user to have cookies enabled in their browser
65 if request.cookies["_osm_session"].to_s == ""
66 if params[:cookie_test].nil?
67 session[:cookie_test] = true
68 redirect_to params.merge(:cookie_test => "true")
71 flash.now[:warning] = t 'application.require_cookies.cookies_needed'
74 session.delete(:cookie_test)
78 # Utility methods to make the controller filter methods easier to read and write.
79 def require_allow_read_prefs
80 require_capability(:allow_read_prefs)
82 def require_allow_write_prefs
83 require_capability(:allow_write_prefs)
85 def require_allow_write_diary
86 require_capability(:allow_write_diary)
88 def require_allow_write_api
89 require_capability(:allow_write_api)
91 if REQUIRE_TERMS_AGREED and @user.terms_agreed.nil?
92 report_error "You must accept the contributor terms before you can edit.", :forbidden
96 def require_allow_read_gpx
97 require_capability(:allow_read_gpx)
99 def require_allow_write_gpx
100 require_capability(:allow_write_gpx)
104 # sets up the @user object for use by other methods. this is mostly called
105 # from the authorize method, but can be called elsewhere if authorisation
108 # try and setup using OAuth
109 if not Authenticator.new(self, [:token]).allow?
110 username, passwd = get_auth_data # parse from headers
111 # authenticate per-scheme
113 @user = nil # no authentication provided - perhaps first connect (client should retry after 401)
114 elsif username == 'token'
115 @user = User.authenticate(:token => passwd) # preferred - random token for user from db, passed in basic auth
117 @user = User.authenticate(:username => username, :password => passwd) # basic auth
121 # have we identified the user?
123 # check if the user has been banned
124 if not @user.active_blocks.empty?
125 # NOTE: need slightly more helpful message than this.
126 report_error t('application.setup_user_auth.blocked'), :forbidden
129 # if the user hasn't seen the contributor terms then don't
130 # allow editing - they have to go to the web site and see
131 # (but can decline) the CTs to continue.
132 if REQUIRE_TERMS_SEEN and not @user.terms_seen and flash[:skip_terms].nil?
134 report_error t('application.setup_user_auth.need_to_see_terms'), :forbidden
139 def authorize(realm='Web Password', errormessage="Couldn't authenticate you")
140 # make the @user object from any auth sources we have
143 # handle authenticate pass/fail
145 # no auth, the user does not exist or the password was wrong
146 response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
147 render :text => errormessage, :status => :unauthorized
152 def check_database_readable(need_api = false)
153 if STATUS == :database_offline or (need_api and STATUS == :api_offline)
154 redirect_to :controller => 'site', :action => 'offline'
158 def check_database_writable(need_api = false)
159 if STATUS == :database_offline or STATUS == :database_readonly or
160 (need_api and (STATUS == :api_offline or STATUS == :api_readonly))
161 redirect_to :controller => 'site', :action => 'offline'
165 def check_api_readable
166 if STATUS == :database_offline or STATUS == :api_offline
167 report_error "Database offline for maintenance", :service_unavailable
172 def check_api_writable
173 if STATUS == :database_offline or STATUS == :database_readonly or
174 STATUS == :api_offline or STATUS == :api_readonly
175 report_error "Database offline for maintenance", :service_unavailable
180 def require_public_data
181 unless @user.data_public?
182 report_error "You must make your edits public to upload new data", :forbidden
187 # Report and error to the user
188 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
189 # rather than only a status code and having the web engine make up a
190 # phrase from that, we can also put the error message into the status
191 # message. For now, rails won't let us)
192 def report_error(message, status = :bad_request)
193 # Todo: some sort of escaping of problem characters in the message
194 response.headers['Error'] = message
196 if request.headers['X-Error-Format'] and
197 request.headers['X-Error-Format'].downcase == "xml"
198 result = OSM::API.new.get_xml_doc
199 result.root.name = "osmError"
200 result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
201 result.root << (XML::Node.new("message") << message)
203 render :text => result.to_s, :content_type => "text/xml"
205 render :text => message, :status => status
210 response.header['Vary'] = 'Accept-Language'
213 if !@user.languages.empty?
214 request.user_preferred_languages = @user.languages
215 response.header['Vary'] = '*'
216 elsif !request.user_preferred_languages.empty?
217 @user.languages = request.user_preferred_languages
222 if request.compatible_language_from(I18n.available_locales).nil?
223 request.user_preferred_languages = request.user_preferred_languages.collect do |pl|
226 while pl.match(/^(.*)-[^-]+$/)
227 pls.push($1) if I18n.available_locales.include?($1.to_sym)
234 if @user and not request.compatible_language_from(I18n.available_locales).nil?
235 @user.languages = request.user_preferred_languages
240 I18n.locale = request.compatible_language_from(I18n.available_locales)
242 response.headers['Content-Language'] = I18n.locale.to_s
245 def api_call_handle_error
248 rescue ActiveRecord::RecordNotFound => ex
249 render :nothing => true, :status => :not_found
250 rescue LibXML::XML::Error, ArgumentError => ex
251 report_error ex.message, :bad_request
252 rescue ActiveRecord::RecordInvalid => ex
253 message = "#{ex.record.class} #{ex.record.id}: "
254 ex.record.errors.each { |attr,msg| message << "#{attr}: #{msg} (#{ex.record[attr].inspect})" }
255 report_error message, :bad_request
256 rescue OSM::APIError => ex
257 report_error ex.message, ex.status
258 rescue ActionController::UnknownAction => ex
260 rescue Exception => ex
261 logger.info("API threw unexpected #{ex.class} exception: #{ex.message}")
262 ex.backtrace.each { |l| logger.info(l) }
263 report_error "#{ex.class}: #{ex.message}", :internal_server_error
268 # asserts that the request method is the +method+ given as a parameter
269 # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
270 def assert_method(method)
271 ok = request.send((method.to_s.downcase + "?").to_sym)
272 raise OSM::APIBadMethodError.new(method) unless ok
276 # wrap an api call in a timeout
278 SystemTimer.timeout_after(API_TIMEOUT) do
281 rescue Timeout::Error
282 raise OSM::APITimeoutError
286 # wrap a web page in a timeout
288 SystemTimer.timeout_after(WEB_TIMEOUT) do
291 rescue ActionView::TemplateError => ex
292 if ex.original_exception.is_a?(Timeout::Error)
293 render :action => "timeout"
297 rescue Timeout::Error
298 render :action => "timeout"
302 # extend caches_action to include the parameters, locale and logged in
303 # status in all cache keys
304 def self.caches_action(*actions)
305 options = actions.extract_options!
306 cache_path = options[:cache_path] || Hash.new
308 options[:unless] = case options[:unless]
309 when NilClass then Array.new
310 when Array then options[:unless]
311 else unlessp = [ options[:unless] ]
314 options[:unless].push(Proc.new do |controller|
315 controller.params.include?(:page)
318 options[:cache_path] = Proc.new do |controller|
319 cache_path.merge(controller.params).merge(:locale => I18n.locale)
322 actions.push(options)
328 # extend expire_action to expire all variants
329 def expire_action(options = {})
330 I18n.available_locales.each do |locale|
331 super options.merge(:locale => locale)
336 # is the requestor logged in?
343 # extract authorisation credentials from headers, returns user = nil if none
345 if request.env.has_key? 'X-HTTP_AUTHORIZATION' # where mod_rewrite might have put it
346 authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split
347 elsif request.env.has_key? 'REDIRECT_X_HTTP_AUTHORIZATION' # mod_fcgi
348 authdata = request.env['REDIRECT_X_HTTP_AUTHORIZATION'].to_s.split
349 elsif request.env.has_key? 'HTTP_AUTHORIZATION' # regular location
350 authdata = request.env['HTTP_AUTHORIZATION'].to_s.split
352 # only basic authentication supported
353 if authdata and authdata[0] == 'Basic'
354 user, pass = Base64.decode64(authdata[1]).split(':',2)
359 # used by oauth plugin to set the current user
360 def current_user=(user)
364 # override to stop oauth plugin sending errors
365 def invalid_oauth_response