1 # Filters added to this controller will be run for all controllers in the application.
2 # Likewise, all the methods added will be available for all controllers.
3 class ApplicationController < ActionController::Base
5 if OSM_STATUS == :database_readonly or OSM_STATUS == :database_offline
11 @user = User.find(session[:user], :conditions => {:status => ["active", "confirmed", "suspended"]})
13 if @user.status == "suspended"
15 session_expires_automatically
17 redirect_to :controller => "user", :action => "suspended"
20 @user = User.authenticate(:token => session[:token])
21 session[:user] = @user.id
23 rescue Exception => ex
24 logger.info("Exception authorizing user: #{ex.to_s}")
29 redirect_to :controller => 'user', :action => 'login', :referer => request.request_uri unless @user
33 # requires the user to be logged in by the token or HTTP methods, or have an
34 # OAuth token with the right capability. this method is a bit of a pain to call
35 # directly, since it's cumbersome to call filters with arguments in rails. to
36 # make it easier to read and write the code, there are some utility methods
38 def require_capability(cap)
39 # when the current token is nil, it means the user logged in with a different
40 # method, otherwise an OAuth token was used, which has to be checked.
41 unless current_token.nil?
42 unless current_token.read_attribute(cap)
43 render :text => "OAuth token doesn't have that capability.", :status => :forbidden
50 # require the user to have cookies enabled in their browser
52 if request.cookies["_osm_session"].to_s == ""
53 if params[:cookie_test].nil?
54 redirect_to params.merge(:cookie_test => "true")
57 flash.now[:warning] = t 'application.require_cookies.cookies_needed'
62 # Utility methods to make the controller filter methods easier to read and write.
63 def require_allow_read_prefs
64 require_capability(:allow_read_prefs)
66 def require_allow_write_prefs
67 require_capability(:allow_write_prefs)
69 def require_allow_write_diary
70 require_capability(:allow_write_diary)
72 def require_allow_write_api
73 require_capability(:allow_write_api)
75 def require_allow_read_gpx
76 require_capability(:allow_read_gpx)
78 def require_allow_write_gpx
79 require_capability(:allow_write_gpx)
83 # sets up the @user object for use by other methods. this is mostly called
84 # from the authorize method, but can be called elsewhere if authorisation
87 # try and setup using OAuth
89 @user = current_token.user
91 username, passwd = get_auth_data # parse from headers
92 # authenticate per-scheme
94 @user = nil # no authentication provided - perhaps first connect (client should retry after 401)
95 elsif username == 'token'
96 @user = User.authenticate(:token => passwd) # preferred - random token for user from db, passed in basic auth
98 @user = User.authenticate(:username => username, :password => passwd) # basic auth
102 # check if the user has been banned
103 unless @user.nil? or @user.active_blocks.empty?
104 # NOTE: need slightly more helpful message than this.
105 render :text => t('application.setup_user_auth.blocked'), :status => :forbidden
109 def authorize(realm='Web Password', errormessage="Couldn't authenticate you")
110 # make the @user object from any auth sources we have
113 # handle authenticate pass/fail
115 # no auth, the user does not exist or the password was wrong
116 response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
117 render :text => errormessage, :status => :unauthorized
122 def check_database_readable(need_api = false)
123 if OSM_STATUS == :database_offline or (need_api and OSM_STATUS == :api_offline)
124 redirect_to :controller => 'site', :action => 'offline'
128 def check_database_writable(need_api = false)
129 if OSM_STATUS == :database_offline or OSM_STATUS == :database_readonly or
130 (need_api and (OSM_STATUS == :api_offline or OSM_STATUS == :api_readonly))
131 redirect_to :controller => 'site', :action => 'offline'
135 def check_api_readable
136 if OSM_STATUS == :database_offline or OSM_STATUS == :api_offline
137 response.headers['Error'] = "Database offline for maintenance"
138 render :nothing => true, :status => :service_unavailable
143 def check_api_writable
144 if OSM_STATUS == :database_offline or OSM_STATUS == :database_readonly or
145 OSM_STATUS == :api_offline or OSM_STATUS == :api_readonly
146 response.headers['Error'] = "Database offline for maintenance"
147 render :nothing => true, :status => :service_unavailable
152 def require_public_data
153 unless @user.data_public?
154 response.headers['Error'] = "You must make your edits public to upload new data"
155 render :nothing => true, :status => :forbidden
160 # Report and error to the user
161 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
162 # rather than only a status code and having the web engine make up a
163 # phrase from that, we can also put the error message into the status
164 # message. For now, rails won't let us)
165 def report_error(message, status = :bad_request)
166 # Todo: some sort of escaping of problem characters in the message
167 response.headers['Error'] = message
168 render :text => message, :status => status
172 response.header['Vary'] = 'Accept-Language'
175 if !@user.languages.empty?
176 request.user_preferred_languages = @user.languages
177 response.header['Vary'] = '*'
178 elsif !request.user_preferred_languages.empty?
179 @user.languages = request.user_preferred_languages
184 I18n.locale = request.compatible_language_from(I18n.available_locales)
186 response.headers['Content-Language'] = I18n.locale.to_s
189 def api_call_handle_error
192 rescue ActiveRecord::RecordNotFound => ex
193 render :nothing => true, :status => :not_found
194 rescue LibXML::XML::Error, ArgumentError => ex
195 report_error ex.message, :bad_request
196 rescue ActiveRecord::RecordInvalid => ex
197 message = "#{ex.record.class} #{ex.record.id}: "
198 ex.record.errors.each { |attr,msg| message << "#{attr}: #{msg} (#{ex.record[attr].inspect})" }
199 report_error message, :bad_request
200 rescue OSM::APIError => ex
201 report_error ex.message, ex.status
202 rescue ActionController::UnknownAction => ex
204 rescue Exception => ex
205 logger.info("API threw unexpected #{ex.class} exception: #{ex.message}")
206 ex.backtrace.each { |l| logger.info(l) }
207 report_error "#{ex.class}: #{ex.message}", :internal_server_error
212 # asserts that the request method is the +method+ given as a parameter
213 # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
214 def assert_method(method)
215 ok = request.send((method.to_s.downcase + "?").to_sym)
216 raise OSM::APIBadMethodError.new(method) unless ok
220 SystemTimer.timeout_after(APP_CONFIG['api_timeout']) do
223 rescue Timeout::Error
224 raise OSM::APITimeoutError
228 # extend caches_action to include the parameters, locale and logged in
229 # status in all cache keys
230 def self.caches_action(*actions)
231 options = actions.extract_options!
232 cache_path = options[:cache_path] || Hash.new
234 options[:cache_path] = Proc.new do |controller|
235 user = controller.instance_variable_get("@user")
238 when user.nil? then user = :none
239 when user.display_name == controller.params[:display_name] then user = :self
240 when user.administrator? then user = :administrator
241 when user.moderator? then user = :moderator
245 cache_path.merge(controller.params).merge(:locale => I18n.locale, :user => user)
248 actions.push(options)
254 # extend expire_action to expire all variants
255 def expire_action(options = {})
256 path = ActionCachePath.path_for(self, options, false).gsub('?', '.').gsub(':', '.')
257 expire_fragment(Regexp.new(Regexp.escape(path) + "\\..*"))
261 # is the requestor logged in?
268 # extract authorisation credentials from headers, returns user = nil if none
270 if request.env.has_key? 'X-HTTP_AUTHORIZATION' # where mod_rewrite might have put it
271 authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split
272 elsif request.env.has_key? 'REDIRECT_X_HTTP_AUTHORIZATION' # mod_fcgi
273 authdata = request.env['REDIRECT_X_HTTP_AUTHORIZATION'].to_s.split
274 elsif request.env.has_key? 'HTTP_AUTHORIZATION' # regular location
275 authdata = request.env['HTTP_AUTHORIZATION'].to_s.split
277 # only basic authentication supported
278 if authdata and authdata[0] == 'Basic'
279 user, pass = Base64.decode64(authdata[1]).split(':',2)