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 # sets up the @user object for use by other methods. this is mostly called
27 # from the authorize method, but can be called elsewhere if authorisation
30 username, passwd = get_auth_data # parse from headers
31 # authenticate per-scheme
33 @user = nil # no authentication provided - perhaps first connect (client should retry after 401)
34 elsif username == 'token'
35 @user = User.authenticate(:token => passwd) # preferred - random token for user from db, passed in basic auth
37 @user = User.authenticate(:username => username, :password => passwd) # basic auth
41 def authorize(realm='Web Password', errormessage="Couldn't authenticate you")
42 # make the @user object from any auth sources we have
45 # handle authenticate pass/fail
47 # no auth, the user does not exist or the password was wrong
48 response.headers["Status"] = "Unauthorized"
49 response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
50 render :text => errormessage, :status => :unauthorized
55 def check_database_readable(need_api = false)
56 if OSM_STATUS == :database_offline or (need_api and OSM_STATUS == :api_offline)
57 redirect_to :controller => 'site', :action => 'offline'
61 def check_database_writable(need_api = false)
62 if OSM_STATUS == :database_offline or OSM_STATUS == :database_readonly or
63 (need_api and (OSM_STATUS == :api_offline or OSM_STATUS == :api_readonly))
64 redirect_to :controller => 'site', :action => 'offline'
68 def check_api_readable
69 if OSM_STATUS == :database_offline or OSM_STATUS == :api_offline
70 response.headers['Error'] = "Database offline for maintenance"
71 render :nothing => true, :status => :service_unavailable
76 def check_api_writable
77 if OSM_STATUS == :database_offline or OSM_STATUS == :database_readonly or
78 OSM_STATUS == :api_offline or OSM_STATUS == :api_readonly
79 response.headers['Error'] = "Database offline for maintenance"
80 render :nothing => true, :status => :service_unavailable
85 def require_public_data
86 unless @user.data_public?
87 response.headers['Error'] = "You must make your edits public to upload new data"
88 render :nothing => true, :status => :forbidden
93 # Report and error to the user
94 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
95 # rather than only a status code and having the web engine make up a
96 # phrase from that, we can also put the error message into the status
97 # message. For now, rails won't let us)
98 def report_error(message, status = :bad_request)
99 # Todo: some sort of escaping of problem characters in the message
100 response.headers['Error'] = message
101 render :text => message, :status => status
106 if !@user.languages.empty?
107 request.user_preferred_languages = @user.languages
108 elsif !request.user_preferred_languages.empty?
109 @user.languages = request.user_preferred_languages
114 I18n.locale = request.compatible_language_from(I18n.available_locales)
116 response.headers['Content-Language'] = I18n.locale
119 def api_call_handle_error
122 rescue ActiveRecord::RecordNotFound => ex
123 render :nothing => true, :status => :not_found
124 rescue LibXML::XML::Error, ArgumentError => ex
125 report_error ex.message, :bad_request
126 rescue ActiveRecord::RecordInvalid => ex
127 message = "#{ex.record.class} #{ex.record.id}: "
128 ex.record.errors.each { |attr,msg| message << "#{attr}: #{msg} (#{ex.record[attr].inspect})" }
129 report_error message, :bad_request
130 rescue OSM::APIError => ex
131 report_error ex.message, ex.status
132 rescue Exception => ex
133 report_error "#{ex.class}: #{ex.message}", :internal_server_error
138 # asserts that the request method is the +method+ given as a parameter
139 # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
140 def assert_method(method)
141 ok = request.send((method.to_s.downcase + "?").to_sym)
142 raise OSM::APIBadMethodError.new(method) unless ok
146 Timeout::timeout(APP_CONFIG['api_timeout'], OSM::APITimeoutError) do
152 # extract authorisation credentials from headers, returns user = nil if none
154 if request.env.has_key? 'X-HTTP_AUTHORIZATION' # where mod_rewrite might have put it
155 authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split
156 elsif request.env.has_key? 'REDIRECT_X_HTTP_AUTHORIZATION' # mod_fcgi
157 authdata = request.env['REDIRECT_X_HTTP_AUTHORIZATION'].to_s.split
158 elsif request.env.has_key? 'HTTP_AUTHORIZATION' # regular location
159 authdata = request.env['HTTP_AUTHORIZATION'].to_s.split
161 # only basic authentication supported
162 if authdata and authdata[0] == 'Basic'
163 user, pass = Base64.decode64(authdata[1]).split(':',2)