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