]> git.openstreetmap.org Git - rails.git/blob - app/controllers/application_controller.rb
Rework the edit tab and it's associated drop down menu
[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   # require that the user is a moderator, or fill out a helpful error message
116   # and return them to the index for the controller this is wrapped from.
117   def require_moderator
118     unless @user.moderator?
119       if request.get?
120         flash[:error] = t('application.require_moderator.not_a_moderator')
121         redirect_to :action => 'index'
122       else
123         render :nothing => true, :status => :forbidden
124       end
125     end
126   end
127
128   ##
129   # sets up the @user object for use by other methods. this is mostly called
130   # from the authorize method, but can be called elsewhere if authorisation
131   # is optional.
132   def setup_user_auth
133     # try and setup using OAuth
134     if not Authenticator.new(self, [:token]).allow?
135       username, passwd = get_auth_data # parse from headers
136       # authenticate per-scheme
137       if username.nil?
138         @user = nil # no authentication provided - perhaps first connect (client should retry after 401)
139       elsif username == 'token'
140         @user = User.authenticate(:token => passwd) # preferred - random token for user from db, passed in basic auth
141       else
142         @user = User.authenticate(:username => username, :password => passwd) # basic auth
143       end
144     end
145
146     # have we identified the user?
147     if @user
148       # check if the user has been banned
149       if not  @user.active_blocks.empty?
150         # NOTE: need slightly more helpful message than this.
151         report_error t('application.setup_user_auth.blocked'), :forbidden
152       end
153
154       # if the user hasn't seen the contributor terms then don't
155       # allow editing - they have to go to the web site and see
156       # (but can decline) the CTs to continue.
157       if REQUIRE_TERMS_SEEN and not @user.terms_seen and flash[:skip_terms].nil?
158         set_locale
159         report_error t('application.setup_user_auth.need_to_see_terms'), :forbidden
160       end
161     end
162   end
163
164   def authorize(realm='Web Password', errormessage="Couldn't authenticate you") 
165     # make the @user object from any auth sources we have
166     setup_user_auth
167
168     # handle authenticate pass/fail
169     unless @user
170       # no auth, the user does not exist or the password was wrong
171       response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\"" 
172       render :text => errormessage, :status => :unauthorized
173       return false
174     end 
175   end 
176
177   ##
178   # to be used as a before_filter *after* authorize. this checks that
179   # the user is a moderator and, if not, returns a forbidden error.
180   #
181   # NOTE: this isn't a very good way of doing it - it duplicates logic
182   # from require_moderator - but what we really need to do is a fairly
183   # drastic refactoring based on :format and respond_to? but not a 
184   # good idea to do that in this branch.
185   def authorize_moderator(errormessage="Access restricted to moderators") 
186     # check user is a moderator
187     unless @user.moderator?
188       render :text => errormessage, :status => :forbidden
189       return false
190     end 
191   end 
192
193   def check_database_readable(need_api = false)
194     if STATUS == :database_offline or (need_api and STATUS == :api_offline)
195       redirect_to :controller => 'site', :action => 'offline'
196     end
197   end
198
199   def check_database_writable(need_api = false)
200     if STATUS == :database_offline or STATUS == :database_readonly or
201        (need_api and (STATUS == :api_offline or STATUS == :api_readonly))
202       redirect_to :controller => 'site', :action => 'offline'
203     end
204   end
205
206   def check_api_readable
207     if STATUS == :database_offline or STATUS == :api_offline
208       report_error "Database offline for maintenance", :service_unavailable
209       return false
210     end
211   end
212
213   def check_api_writable
214     if STATUS == :database_offline or STATUS == :database_readonly or
215        STATUS == :api_offline or STATUS == :api_readonly
216       report_error "Database offline for maintenance", :service_unavailable
217       return false
218     end
219   end
220
221   def require_public_data
222     unless @user.data_public?
223       report_error "You must make your edits public to upload new data", :forbidden
224       return false
225     end
226   end
227
228   # Report and error to the user
229   # (If anyone ever fixes Rails so it can set a http status "reason phrase",
230   #  rather than only a status code and having the web engine make up a 
231   #  phrase from that, we can also put the error message into the status
232   #  message. For now, rails won't let us)
233   def report_error(message, status = :bad_request)
234     # Todo: some sort of escaping of problem characters in the message
235     response.headers['Error'] = message
236
237     if request.headers['X-Error-Format'] and
238        request.headers['X-Error-Format'].downcase == "xml"
239       result = OSM::API.new.get_xml_doc
240       result.root.name = "osmError"
241       result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
242       result.root << (XML::Node.new("message") << message)
243
244       render :text => result.to_s, :content_type => "text/xml"
245     else
246       render :text => message, :status => status
247     end
248   end
249   
250   def set_locale
251     response.header['Vary'] = 'Accept-Language'
252
253     if @user
254       if !@user.languages.empty?
255         request.user_preferred_languages = @user.languages
256         response.header['Vary'] = '*'
257       elsif !request.user_preferred_languages.empty?
258         @user.languages = request.user_preferred_languages
259         @user.save
260       end
261     end
262
263     if request.compatible_language_from(I18n.available_locales).nil?
264       request.user_preferred_languages = request.user_preferred_languages.collect do |pl|
265         pls = [ pl ]
266
267         while pl.match(/^(.*)-[^-]+$/)
268           pls.push($1) if I18n.available_locales.include?($1.to_sym)
269           pl = $1
270         end
271
272         pls
273       end.flatten
274
275       if @user and not request.compatible_language_from(I18n.available_locales).nil?
276         @user.languages = request.user_preferred_languages
277         @user.save        
278       end
279     end
280
281     I18n.locale = request.compatible_language_from(I18n.available_locales) || I18n.default_locale
282
283     response.headers['Content-Language'] = I18n.locale.to_s
284   end
285
286   def api_call_handle_error
287     begin
288       yield
289     rescue ActiveRecord::RecordNotFound => ex
290       render :nothing => true, :status => :not_found
291     rescue LibXML::XML::Error, ArgumentError => ex
292       report_error ex.message, :bad_request
293     rescue ActiveRecord::RecordInvalid => ex
294       message = "#{ex.record.class} #{ex.record.id}: "
295       ex.record.errors.each { |attr,msg| message << "#{attr}: #{msg} (#{ex.record[attr].inspect})" }
296       report_error message, :bad_request
297     rescue OSM::APIError => ex
298       report_error ex.message, ex.status
299     rescue AbstractController::ActionNotFound => ex
300       raise
301     rescue Exception => ex
302       logger.info("API threw unexpected #{ex.class} exception: #{ex.message}")
303       ex.backtrace.each { |l| logger.info(l) }
304       report_error "#{ex.class}: #{ex.message}", :internal_server_error
305     end
306   end
307
308   ##
309   # asserts that the request method is the +method+ given as a parameter
310   # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
311   def assert_method(method)
312     ok = request.send((method.to_s.downcase + "?").to_sym)
313     raise OSM::APIBadMethodError.new(method) unless ok
314   end
315
316   ##
317   # wrap an api call in a timeout
318   def api_call_timeout
319     OSM::Timer.timeout(API_TIMEOUT) do
320       yield
321     end
322   rescue Timeout::Error
323     raise OSM::APITimeoutError
324   end
325
326   ##
327   # wrap a web page in a timeout
328   def web_timeout
329     OSM::Timer.timeout(WEB_TIMEOUT) do
330       yield
331     end
332   rescue ActionView::Template::Error => ex
333     ex = ex.original_exception
334
335     if ex.is_a?(ActiveRecord::StatementInvalid) and ex.message =~ /^Timeout::Error/
336       ex = Timeout::Error.new
337     end
338
339     if ex.is_a?(Timeout::Error)
340       render :action => "timeout"
341     else
342       raise
343     end
344   rescue Timeout::Error
345     render :action => "timeout"
346   end
347
348   ##
349   # extend caches_action to include the parameters, locale and logged in
350   # status in all cache keys
351   def self.caches_action(*actions)
352     options = actions.extract_options!
353     cache_path = options[:cache_path] || Hash.new
354
355     options[:unless] = case options[:unless]
356                        when NilClass then Array.new
357                        when Array then options[:unless]
358                        else unlessp = [ options[:unless] ]
359                        end
360
361     options[:unless].push(Proc.new do |controller|
362       controller.params.include?(:page)
363     end)
364
365     options[:cache_path] = Proc.new do |controller|
366       cache_path.merge(controller.params).merge(:host => SERVER_URL, :locale => I18n.locale)
367     end
368
369     actions.push(options)
370
371     super *actions
372   end
373
374   ##
375   # extend expire_action to expire all variants
376   def expire_action(options = {})
377     I18n.available_locales.each do |locale|
378       super options.merge(:host => SERVER_URL, :locale => locale)
379     end
380   end
381
382   ##
383   # is the requestor logged in?
384   def logged_in?
385     !@user.nil?
386   end
387
388   ##
389   # ensure that there is a "this_user" instance variable
390   def lookup_this_user
391     unless @this_user = User.active.find_by_display_name(params[:display_name])
392       render_unknown_user params[:display_name]
393     end
394   end
395
396   ##
397   # render a "no such user" page
398   def render_unknown_user(name)
399     @title = t "user.no_such_user.title"
400     @not_found_user = name
401
402     render :template => "user/no_such_user", :status => :not_found
403   end
404   
405 private 
406
407   # extract authorisation credentials from headers, returns user = nil if none
408   def get_auth_data 
409     if request.env.has_key? 'X-HTTP_AUTHORIZATION'          # where mod_rewrite might have put it 
410       authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split 
411     elsif request.env.has_key? 'REDIRECT_X_HTTP_AUTHORIZATION'          # mod_fcgi 
412       authdata = request.env['REDIRECT_X_HTTP_AUTHORIZATION'].to_s.split 
413     elsif request.env.has_key? 'HTTP_AUTHORIZATION'         # regular location
414       authdata = request.env['HTTP_AUTHORIZATION'].to_s.split
415     end 
416     # only basic authentication supported
417     if authdata and authdata[0] == 'Basic' 
418       user, pass = Base64.decode64(authdata[1]).split(':',2)
419     end 
420     return [user, pass] 
421   end 
422
423   # used by oauth plugin to get the current user
424   def current_user
425     @user
426   end
427
428   # used by oauth plugin to set the current user
429   def current_user=(user)
430     @user=user
431   end
432
433   # override to stop oauth plugin sending errors
434   def invalid_oauth_response
435   end
436
437 end