]> git.openstreetmap.org Git - rails.git/blob - app/controllers/application_controller.rb
Make sure "please read the terms" error is issued in the right language
[rails.git] / app / controllers / application_controller.rb
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
4
5   if STATUS == :database_readonly or STATUS == :database_offline
6     session :off
7   end
8
9   def authorize_web
10     if session[:user]
11       @user = User.find(session[:user], :conditions => {:status => ["active", "confirmed", "suspended"]})
12
13       if @user.status == "suspended"
14         session[:user] = nil
15         session_expires_automatically
16
17         redirect_to :controller => "user", :action => "suspended"
18       end
19     elsif session[:token]
20       @user = User.authenticate(:token => session[:token])
21       session[:user] = @user.id
22     end
23   rescue Exception => ex
24     logger.info("Exception authorizing user: #{ex.to_s}")
25     @user = nil
26   end
27
28   def require_user
29     redirect_to :controller => 'user', :action => 'login', :referer => request.request_uri unless @user
30   end
31
32   ##
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
37   # below.
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
44         return false
45       end
46     end
47   end
48
49   ##
50   # require the user to have cookies enabled in their browser
51   def require_cookies
52     if request.cookies["_osm_session"].to_s == ""
53       if params[:cookie_test].nil?
54         redirect_to params.merge(:cookie_test => "true")
55         return false
56       else
57         flash.now[:warning] = t 'application.require_cookies.cookies_needed'
58       end
59     end
60   end
61
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)
65   end
66   def require_allow_write_prefs
67     require_capability(:allow_write_prefs)
68   end
69   def require_allow_write_diary
70     require_capability(:allow_write_diary)
71   end
72   def require_allow_write_api
73     require_capability(:allow_write_api)
74   end
75   def require_allow_read_gpx
76     require_capability(:allow_read_gpx)
77   end
78   def require_allow_write_gpx
79     require_capability(:allow_write_gpx)
80   end
81
82   ##
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
85   # is optional.
86   def setup_user_auth
87     # try and setup using OAuth
88     if oauthenticate
89       @user = current_token.user
90     else
91       username, passwd = get_auth_data # parse from headers
92       # authenticate per-scheme
93       if username.nil?
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
97       else
98         @user = User.authenticate(:username => username, :password => passwd) # basic auth
99       end
100     end
101
102     # have we identified the user?
103     if @user
104       # check if the user has been banned
105       if not  @user.active_blocks.empty?
106         # NOTE: need slightly more helpful message than this.
107         render :text => t('application.setup_user_auth.blocked'), :status => :forbidden
108       end
109
110       # if the user hasn't seen the contributor terms then don't
111       # allow editing - they have to go to the web site and see
112       # (but can decline) the CTs to continue.
113       if REQUIRE_TERMS_SEEN and not @user.terms_seen
114         set_locale
115         render :text => t('application.setup_user_auth.need_to_see_terms'), :status => :forbidden
116       end
117     end
118   end
119
120   def authorize(realm='Web Password', errormessage="Couldn't authenticate you") 
121     # make the @user object from any auth sources we have
122     setup_user_auth
123
124     # handle authenticate pass/fail
125     unless @user
126       # no auth, the user does not exist or the password was wrong
127       response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\"" 
128       render :text => errormessage, :status => :unauthorized
129       return false
130     end 
131   end 
132
133   def check_database_readable(need_api = false)
134     if STATUS == :database_offline or (need_api and STATUS == :api_offline)
135       redirect_to :controller => 'site', :action => 'offline'
136     end
137   end
138
139   def check_database_writable(need_api = false)
140     if STATUS == :database_offline or STATUS == :database_readonly or
141        (need_api and (STATUS == :api_offline or STATUS == :api_readonly))
142       redirect_to :controller => 'site', :action => 'offline'
143     end
144   end
145
146   def check_api_readable
147     if STATUS == :database_offline or STATUS == :api_offline
148       report_error "Database offline for maintenance", :service_unavailable
149       return false
150     end
151   end
152
153   def check_api_writable
154     if STATUS == :database_offline or STATUS == :database_readonly or
155        STATUS == :api_offline or STATUS == :api_readonly
156       report_error "Database offline for maintenance", :service_unavailable
157       return false
158     end
159   end
160
161   def require_public_data
162     unless @user.data_public?
163       report_error "You must make your edits public to upload new data", :forbidden
164       return false
165     end
166   end
167
168   # Report and error to the user
169   # (If anyone ever fixes Rails so it can set a http status "reason phrase",
170   #  rather than only a status code and having the web engine make up a 
171   #  phrase from that, we can also put the error message into the status
172   #  message. For now, rails won't let us)
173   def report_error(message, status = :bad_request)
174     # Todo: some sort of escaping of problem characters in the message
175     response.headers['Error'] = message
176
177     if request.headers['X-Error-Format'] and
178        request.headers['X-Error-Format'].downcase == "xml"
179       result = OSM::API.new.get_xml_doc
180       result.root.name = "osmError"
181       result.root << (XML::Node.new("status") << interpret_status(status))
182       result.root << (XML::Node.new("message") << message)
183
184       render :text => result.to_s, :content_type => "text/xml"
185     else
186       render :text => message, :status => status
187     end
188   end
189   
190   def set_locale
191     response.header['Vary'] = 'Accept-Language'
192
193     if @user
194       if !@user.languages.empty?
195         request.user_preferred_languages = @user.languages
196         response.header['Vary'] = '*'
197       elsif !request.user_preferred_languages.empty?
198         @user.languages = request.user_preferred_languages
199         @user.save
200       end
201     end
202
203     if request.compatible_language_from(I18n.available_locales).nil?
204       request.user_preferred_languages = request.user_preferred_languages.collect do |pl|
205         pls = [ pl ]
206
207         while pl.match(/^(.*)-[^-]+$/)
208           pls.push($1) if I18n.available_locales.include?($1.to_sym)
209           pl = $1
210         end
211
212         pls
213       end.flatten
214
215       if @user and not request.compatible_language_from(I18n.available_locales).nil?
216         @user.languages = request.user_preferred_languages
217         @user.save        
218       end
219     end
220
221     I18n.locale = request.compatible_language_from(I18n.available_locales)
222
223     response.headers['Content-Language'] = I18n.locale.to_s
224   end
225
226   def api_call_handle_error
227     begin
228       yield
229     rescue ActiveRecord::RecordNotFound => ex
230       render :nothing => true, :status => :not_found
231     rescue LibXML::XML::Error, ArgumentError => ex
232       report_error ex.message, :bad_request
233     rescue ActiveRecord::RecordInvalid => ex
234       message = "#{ex.record.class} #{ex.record.id}: "
235       ex.record.errors.each { |attr,msg| message << "#{attr}: #{msg} (#{ex.record[attr].inspect})" }
236       report_error message, :bad_request
237     rescue OSM::APIError => ex
238       report_error ex.message, ex.status
239     rescue ActionController::UnknownAction => ex
240       raise
241     rescue Exception => ex
242       logger.info("API threw unexpected #{ex.class} exception: #{ex.message}")
243       ex.backtrace.each { |l| logger.info(l) }
244       report_error "#{ex.class}: #{ex.message}", :internal_server_error
245     end
246   end
247
248   ##
249   # asserts that the request method is the +method+ given as a parameter
250   # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
251   def assert_method(method)
252     ok = request.send((method.to_s.downcase + "?").to_sym)
253     raise OSM::APIBadMethodError.new(method) unless ok
254   end
255
256   ##
257   # wrap an api call in a timeout
258   def api_call_timeout
259     SystemTimer.timeout_after(API_TIMEOUT) do
260       yield
261     end
262   rescue Timeout::Error
263     raise OSM::APITimeoutError
264   end
265
266   ##
267   # wrap a web page in a timeout
268   def web_timeout
269     SystemTimer.timeout_after(WEB_TIMEOUT) do
270       yield
271     end
272   rescue ActionView::TemplateError => ex
273     if ex.original_exception.is_a?(Timeout::Error)
274       render :action => "timeout"
275     else
276       raise
277     end
278   rescue Timeout::Error
279     render :action => "timeout"
280   end
281
282   ##
283   # extend caches_action to include the parameters, locale and logged in
284   # status in all cache keys
285   def self.caches_action(*actions)
286     options = actions.extract_options!
287     cache_path = options[:cache_path] || Hash.new
288
289     options[:unless] = case options[:unless]
290                        when NilClass then Array.new
291                        when Array then options[:unless]
292                        else unlessp = [ options[:unless] ]
293                        end
294
295     options[:unless].push(Proc.new do |controller|
296       controller.params.include?(:page)
297     end)
298
299     options[:cache_path] = Proc.new do |controller|
300       cache_path.merge(controller.params).merge(:locale => I18n.locale)
301     end
302
303     actions.push(options)
304
305     super *actions
306   end
307
308   ##
309   # extend expire_action to expire all variants
310   def expire_action(options = {})
311     I18n.available_locales.each do |locale|
312       super options.merge(:locale => locale)
313     end
314   end
315
316   ##
317   # is the requestor logged in?
318   def logged_in?
319     !@user.nil?
320   end
321
322 private 
323
324   # extract authorisation credentials from headers, returns user = nil if none
325   def get_auth_data 
326     if request.env.has_key? 'X-HTTP_AUTHORIZATION'          # where mod_rewrite might have put it 
327       authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split 
328     elsif request.env.has_key? 'REDIRECT_X_HTTP_AUTHORIZATION'          # mod_fcgi 
329       authdata = request.env['REDIRECT_X_HTTP_AUTHORIZATION'].to_s.split 
330     elsif request.env.has_key? 'HTTP_AUTHORIZATION'         # regular location
331       authdata = request.env['HTTP_AUTHORIZATION'].to_s.split
332     end 
333     # only basic authentication supported
334     if authdata and authdata[0] == 'Basic' 
335       user, pass = Base64.decode64(authdata[1]).split(':',2)
336     end 
337     return [user, pass] 
338   end 
339
340 end