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