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 Authenticator.new(self, [:token]).allow?
110 @user = current_token.user
112 username, passwd = get_auth_data # parse from headers
113 # authenticate per-scheme
115 @user = nil # no authentication provided - perhaps first connect (client should retry after 401)
116 elsif username == 'token'
117 @user = User.authenticate(:token => passwd) # preferred - random token for user from db, passed in basic auth
119 @user = User.authenticate(:username => username, :password => passwd) # basic auth
123 # have we identified the user?
125 # check if the user has been banned
126 if not @user.active_blocks.empty?
127 # NOTE: need slightly more helpful message than this.
128 report_error t('application.setup_user_auth.blocked'), :forbidden
131 # if the user hasn't seen the contributor terms then don't
132 # allow editing - they have to go to the web site and see
133 # (but can decline) the CTs to continue.
134 if REQUIRE_TERMS_SEEN and not @user.terms_seen and flash[:skip_terms].nil?
136 report_error t('application.setup_user_auth.need_to_see_terms'), :forbidden
141 def authorize(realm='Web Password', errormessage="Couldn't authenticate you")
142 # make the @user object from any auth sources we have
145 # handle authenticate pass/fail
147 # no auth, the user does not exist or the password was wrong
148 response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
149 render :text => errormessage, :status => :unauthorized
154 def check_database_readable(need_api = false)
155 if STATUS == :database_offline or (need_api and STATUS == :api_offline)
156 redirect_to :controller => 'site', :action => 'offline'
160 def check_database_writable(need_api = false)
161 if STATUS == :database_offline or STATUS == :database_readonly or
162 (need_api and (STATUS == :api_offline or STATUS == :api_readonly))
163 redirect_to :controller => 'site', :action => 'offline'
167 def check_api_readable
168 if STATUS == :database_offline or STATUS == :api_offline
169 report_error "Database offline for maintenance", :service_unavailable
174 def check_api_writable
175 if STATUS == :database_offline or STATUS == :database_readonly or
176 STATUS == :api_offline or STATUS == :api_readonly
177 report_error "Database offline for maintenance", :service_unavailable
182 def require_public_data
183 unless @user.data_public?
184 report_error "You must make your edits public to upload new data", :forbidden
189 # Report and error to the user
190 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
191 # rather than only a status code and having the web engine make up a
192 # phrase from that, we can also put the error message into the status
193 # message. For now, rails won't let us)
194 def report_error(message, status = :bad_request)
195 # Todo: some sort of escaping of problem characters in the message
196 response.headers['Error'] = message
198 if request.headers['X-Error-Format'] and
199 request.headers['X-Error-Format'].downcase == "xml"
200 result = OSM::API.new.get_xml_doc
201 result.root.name = "osmError"
202 result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
203 result.root << (XML::Node.new("message") << message)
205 render :text => result.to_s, :content_type => "text/xml"
207 render :text => message, :status => status
212 response.header['Vary'] = 'Accept-Language'
215 if !@user.languages.empty?
216 request.user_preferred_languages = @user.languages
217 response.header['Vary'] = '*'
218 elsif !request.user_preferred_languages.empty?
219 @user.languages = request.user_preferred_languages
224 if request.compatible_language_from(I18n.available_locales).nil?
225 request.user_preferred_languages = request.user_preferred_languages.collect do |pl|
228 while pl.match(/^(.*)-[^-]+$/)
229 pls.push($1) if I18n.available_locales.include?($1.to_sym)
236 if @user and not request.compatible_language_from(I18n.available_locales).nil?
237 @user.languages = request.user_preferred_languages
242 I18n.locale = request.compatible_language_from(I18n.available_locales)
244 response.headers['Content-Language'] = I18n.locale.to_s
247 def api_call_handle_error
250 rescue ActiveRecord::RecordNotFound => ex
251 render :nothing => true, :status => :not_found
252 rescue LibXML::XML::Error, ArgumentError => ex
253 report_error ex.message, :bad_request
254 rescue ActiveRecord::RecordInvalid => ex
255 message = "#{ex.record.class} #{ex.record.id}: "
256 ex.record.errors.each { |attr,msg| message << "#{attr}: #{msg} (#{ex.record[attr].inspect})" }
257 report_error message, :bad_request
258 rescue OSM::APIError => ex
259 report_error ex.message, ex.status
260 rescue ActionController::UnknownAction => ex
262 rescue Exception => ex
263 logger.info("API threw unexpected #{ex.class} exception: #{ex.message}")
264 ex.backtrace.each { |l| logger.info(l) }
265 report_error "#{ex.class}: #{ex.message}", :internal_server_error
270 # asserts that the request method is the +method+ given as a parameter
271 # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
272 def assert_method(method)
273 ok = request.send((method.to_s.downcase + "?").to_sym)
274 raise OSM::APIBadMethodError.new(method) unless ok
278 # wrap an api call in a timeout
280 SystemTimer.timeout_after(API_TIMEOUT) do
283 rescue Timeout::Error
284 raise OSM::APITimeoutError
288 # wrap a web page in a timeout
290 SystemTimer.timeout_after(WEB_TIMEOUT) do
293 rescue ActionView::TemplateError => ex
294 if ex.original_exception.is_a?(Timeout::Error)
295 render :action => "timeout"
299 rescue Timeout::Error
300 render :action => "timeout"
304 # extend caches_action to include the parameters, locale and logged in
305 # status in all cache keys
306 def self.caches_action(*actions)
307 options = actions.extract_options!
308 cache_path = options[:cache_path] || Hash.new
310 options[:unless] = case options[:unless]
311 when NilClass then Array.new
312 when Array then options[:unless]
313 else unlessp = [ options[:unless] ]
316 options[:unless].push(Proc.new do |controller|
317 controller.params.include?(:page)
320 options[:cache_path] = Proc.new do |controller|
321 cache_path.merge(controller.params).merge(:locale => I18n.locale)
324 actions.push(options)
330 # extend expire_action to expire all variants
331 def expire_action(options = {})
332 I18n.available_locales.each do |locale|
333 super options.merge(:locale => locale)
338 # is the requestor logged in?
345 # extract authorisation credentials from headers, returns user = nil if none
347 if request.env.has_key? 'X-HTTP_AUTHORIZATION' # where mod_rewrite might have put it
348 authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split
349 elsif request.env.has_key? 'REDIRECT_X_HTTP_AUTHORIZATION' # mod_fcgi
350 authdata = request.env['REDIRECT_X_HTTP_AUTHORIZATION'].to_s.split
351 elsif request.env.has_key? 'HTTP_AUTHORIZATION' # regular location
352 authdata = request.env['HTTP_AUTHORIZATION'].to_s.split
354 # only basic authentication supported
355 if authdata and authdata[0] == 'Basic'
356 user, pass = Base64.decode64(authdata[1]).split(':',2)
361 # override to stop oauth plugin sending errors
362 def invalid_oauth_response