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