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 => {:visible => true})
13 @user = User.authenticate(:token => session[:token])
14 session[:user] = @user.id
16 rescue Exception => ex
17 logger.info("Exception authorizing user: #{ex.to_s}")
22 redirect_to :controller => 'user', :action => 'login', :referer => request.request_uri unless @user
26 # requires the user to be logged in by the token or HTTP methods, or have an
27 # OAuth token with the right capability. this method is a bit of a pain to call
28 # directly, since it's cumbersome to call filters with arguments in rails. to
29 # make it easier to read and write the code, there are some utility methods
31 def require_capability(cap)
32 # when the current token is nil, it means the user logged in with a different
33 # method, otherwise an OAuth token was used, which has to be checked.
34 unless current_token.nil?
35 unless current_token.read_attribute(cap)
36 render :text => "OAuth token doesn't have that capability.", :status => :forbidden
42 # Utility methods to make the controller filter methods easier to read and write.
43 def require_allow_read_prefs
44 require_capability(:allow_read_prefs)
46 def require_allow_write_prefs
47 require_capability(:allow_write_prefs)
49 def require_allow_write_diary
50 require_capability(:allow_write_diary)
52 def require_allow_write_api
53 require_capability(:allow_write_api)
55 def require_allow_read_gpx
56 require_capability(:allow_read_gpx)
58 def require_allow_write_gpx
59 require_capability(:allow_write_gpx)
63 # sets up the @user object for use by other methods. this is mostly called
64 # from the authorize method, but can be called elsewhere if authorisation
67 # try and setup using OAuth
69 @user = current_token.user
71 username, passwd = get_auth_data # parse from headers
72 # authenticate per-scheme
74 @user = nil # no authentication provided - perhaps first connect (client should retry after 401)
75 elsif username == 'token'
76 @user = User.authenticate(:token => passwd) # preferred - random token for user from db, passed in basic auth
78 @user = User.authenticate(:username => username, :password => passwd) # basic auth
83 def authorize(realm='Web Password', errormessage="Couldn't authenticate you")
84 # make the @user object from any auth sources we have
87 # handle authenticate pass/fail
89 # no auth, the user does not exist or the password was wrong
90 response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
91 render :text => errormessage, :status => :unauthorized
96 def check_database_readable(need_api = false)
97 if OSM_STATUS == :database_offline or (need_api and OSM_STATUS == :api_offline)
98 redirect_to :controller => 'site', :action => 'offline'
102 def check_database_writable(need_api = false)
103 if OSM_STATUS == :database_offline or OSM_STATUS == :database_readonly or
104 (need_api and (OSM_STATUS == :api_offline or OSM_STATUS == :api_readonly))
105 redirect_to :controller => 'site', :action => 'offline'
109 def check_api_readable
110 if OSM_STATUS == :database_offline or OSM_STATUS == :api_offline
111 response.headers['Error'] = "Database offline for maintenance"
112 render :nothing => true, :status => :service_unavailable
117 def check_api_writable
118 if OSM_STATUS == :database_offline or OSM_STATUS == :database_readonly or
119 OSM_STATUS == :api_offline or OSM_STATUS == :api_readonly
120 response.headers['Error'] = "Database offline for maintenance"
121 render :nothing => true, :status => :service_unavailable
126 def require_public_data
127 unless @user.data_public?
128 response.headers['Error'] = "You must make your edits public to upload new data"
129 render :nothing => true, :status => :forbidden
134 # Report and error to the user
135 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
136 # rather than only a status code and having the web engine make up a
137 # phrase from that, we can also put the error message into the status
138 # message. For now, rails won't let us)
139 def report_error(message, status = :bad_request)
140 # Todo: some sort of escaping of problem characters in the message
141 response.headers['Error'] = message
142 render :text => message, :status => status
146 response.header['Vary'] = 'Accept-Language'
149 if !@user.languages.empty?
150 request.user_preferred_languages = @user.languages
151 response.header['Vary'] = '*'
152 elsif !request.user_preferred_languages.empty?
153 @user.languages = request.user_preferred_languages
158 I18n.locale = request.compatible_language_from(I18n.available_locales)
160 response.headers['Content-Language'] = I18n.locale.to_s
163 def api_call_handle_error
166 rescue ActiveRecord::RecordNotFound => ex
167 render :nothing => true, :status => :not_found
168 rescue LibXML::XML::Error, ArgumentError => ex
169 report_error ex.message, :bad_request
170 rescue ActiveRecord::RecordInvalid => ex
171 message = "#{ex.record.class} #{ex.record.id}: "
172 ex.record.errors.each { |attr,msg| message << "#{attr}: #{msg} (#{ex.record[attr].inspect})" }
173 report_error message, :bad_request
174 rescue OSM::APIError => ex
175 report_error ex.message, ex.status
176 rescue Exception => ex
177 logger.info("API threw unexpected #{ex.class} exception: #{ex.message}")
178 ex.backtrace.each { |l| logger.info(l) }
179 report_error "#{ex.class}: #{ex.message}", :internal_server_error
184 # asserts that the request method is the +method+ given as a parameter
185 # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
186 def assert_method(method)
187 ok = request.send((method.to_s.downcase + "?").to_sym)
188 raise OSM::APIBadMethodError.new(method) unless ok
192 Timeout::timeout(APP_CONFIG['api_timeout'], OSM::APITimeoutError) do
198 # extract authorisation credentials from headers, returns user = nil if none
200 if request.env.has_key? 'X-HTTP_AUTHORIZATION' # where mod_rewrite might have put it
201 authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split
202 elsif request.env.has_key? 'REDIRECT_X_HTTP_AUTHORIZATION' # mod_fcgi
203 authdata = request.env['REDIRECT_X_HTTP_AUTHORIZATION'].to_s.split
204 elsif request.env.has_key? 'HTTP_AUTHORIZATION' # regular location
205 authdata = request.env['HTTP_AUTHORIZATION'].to_s.split
207 # only basic authentication supported
208 if authdata and authdata[0] == 'Basic'
209 user, pass = Base64.decode64(authdata[1]).split(':',2)