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