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