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