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